forked from pytorch/benchmark
-
Notifications
You must be signed in to change notification settings - Fork 0
/
common.py
4006 lines (3511 loc) · 139 KB
/
common.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
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
from __future__ import annotations
import abc
import argparse
import collections
import contextlib
import copy
import csv
import dataclasses
import functools
import importlib
import itertools
import logging
import os
import pathlib
import shutil
import signal
import subprocess
import sys
import time
import weakref
from contextlib import contextmanager
from typing import (
Any,
Callable,
Generator,
List,
Mapping,
NamedTuple,
Optional,
Sequence,
Tuple,
Type,
TYPE_CHECKING,
)
from unittest.mock import MagicMock
from typing_extensions import Self
if TYPE_CHECKING:
from torch.onnx._internal.fx import diagnostics
import numpy as np
import pandas as pd
import psutil
import torch
import torch._dynamo
import torch._dynamo.utils
import torch._export
import torch.distributed
import torch.multiprocessing as mp
from scipy.stats import gmean, ttest_ind
from torch._dynamo.profiler import fx_insert_profiling, Profiler
from torch._dynamo.testing import (
dummy_fx_compile,
format_speedup,
reset_rng_state,
same,
)
try:
from torch._dynamo.utils import (
clone_inputs,
graph_break_reasons,
maybe_enable_compiled_autograd,
)
from torch._inductor.utils import fresh_inductor_cache
except ImportError:
from _dynamo.utils import (
clone_inputs,
graph_break_reasons,
maybe_enable_compiled_autograd,
)
from torch._functorch.aot_autograd import set_model_name
from torch._inductor import config as inductor_config, metrics
from torch._subclasses.fake_tensor import FakeTensorMode
from torch.utils import _pytree as pytree
from torch.utils._pytree import tree_map, tree_map_only
from tqdm.auto import tqdm, trange
try:
import torch_xla
import torch_xla.core.xla_model as xm
# This is to woraround the backward issue https://github.com/pytorch/xla/issues/4174
torch_xla._XLAC._init_computation_client()
except ImportError:
# ignore the error if torch_xla is not installed
pass
log = logging.getLogger(__name__)
# We are primarily interested in TF32
torch.backends.cuda.matmul.allow_tf32 = True
# Suppress torch.profiler spam
os.environ["KINETO_LOG_LEVEL"] = "5"
current_name = ""
current_device = ""
current_onnx_compiler = ""
current_batch_size = None
output_filename = None
MAX_DOWNLOAD_ATTEMPTS = 5
class CI(NamedTuple):
backend: str # aot_eager or inductor
training: bool
dynamic: bool = False
device: str = "cuda"
CI_SKIP_OPTIMIZER = {
# TIMM
"convmixer_768_32", # accuracy
"hrnet_w18", # Stack issue in fx
# HF
"pnasnet5large", # Stack issue in fx
"MobileBertForMaskedLM", # Stack issue in fx
"MobileBertForQuestionAnswering", # Stack issue in fx
"PegasusForConditionalGeneration", # OOM
}
CI_SKIP_DYNAMIC_BATCH_ONLY = {
"sam",
# See https://github.com/mindee/doctr/blob/f2114758d529ed8d3d0030581638f0520b6b98d8/doctr/models/detection/core.py#L89
# It iterates over the batch, which is dynamic, and dynamo chokes
# We should be able to graphbreak there.
"doctr_det_predictor",
"dlrm",
"pyhpc_isoneutral_mixing",
"pyhpc_equation_of_state",
"pyhpc_turbulent_kinetic_energy",
"detectron2_fcos_r_50_fpn",
}
# These models currently fail accuracy with eager Adam optimizer
# so we use SGD when running the full benchmarks
# https://github.com/pytorch/pytorch/issues/115966
BENCHMARK_USE_SGD = {
# TorchBench
"BERT_pytorch",
"LearningToPaint",
"alexnet",
"dcgan",
"demucs",
"densenet121",
"dlrm",
"fastNLP_Bert",
"mobilenet_v2",
"phlippe_densenet",
"phlippe_resnet",
"pytorch_stargan",
"resnet18",
"shufflenet_v2_x1_0",
"speech_transformer",
"squeezenet1_1",
"stable_diffusion_text_encoder",
"timm_efficientdet",
"timm_nfnet",
"timm_regnet",
"timm_vision_transformer",
"timm_vovnet",
"vgg16",
"hf_T5", # Fails dynamic https://github.com/pytorch/pytorch/issues/115968
# HF
"AlbertForMaskedLM",
"BartForCausalLM",
"BartForConditionalGeneration",
"BlenderbotSmallForCausalLM",
"BlenderbotSmallForConditionalGeneration",
"DebertaV2ForQuestionAnswering", # eager OOM
"ElectraForCausalLM",
"M2M100ForConditionalGeneration",
"MBartForCausalLM",
"MBartForConditionalGeneration",
"OPTForCausalLM",
"PLBartForCausalLM",
"PLBartForConditionalGeneration",
"PegasusForCausalLM",
"Speech2Text2ForCausalLM",
"TrOCRForCausalLM",
"XGLMForCausalLM",
# TIMM
"adv_inception_v3",
"botnet26t_256",
"cait_m36_384", # OOM
"coat_lite_mini",
"convit_base",
"dpn107",
"fbnetv3_b",
"gernet_l",
"lcnet_050",
"mixnet_l",
"res2net101_26w_4s",
"res2net50_14w_8s",
"res2next50",
"resnest101e",
"sebotnet33ts_256",
"swsl_resnext101_32x16d",
"tf_efficientnet_b0",
"ghostnet_100",
"gmixer_24_224",
"tinynet_a",
}
# These models OOM in CI
# due to the extra memory of Adam optimizer states,
# so we fall back to SGD in CI
CI_USE_SGD = {
"torchrec_dlrm",
"demucs",
"detectron2_fasterrcnn_r_101_c4",
"detectron2_fasterrcnn_r_101_dc5",
"detectron2_fasterrcnn_r_101_fpn",
"detectron2_fasterrcnn_r_50_c4",
"detectron2_fasterrcnn_r_50_dc5",
"detectron2_fasterrcnn_r_50_fpn",
"detectron2_maskrcnn_r_101_c4",
"detectron2_maskrcnn_r_101_fpn",
"detectron2_maskrcnn_r_50_c4",
"detectron2_maskrcnn_r_50_fpn",
"hf_T5_base",
"hf_clip",
"llama_v2_7b_16h",
"mobilenet_v2_quantized_qat",
"phi_1_5 resnet50_quantized_qat",
"BlenderbotForCausalLM",
"cait_m36_384",
"DALLE2_pytorch",
"moco",
"timm_efficientdet",
"ghostnet_100",
"regnety_002",
"poolformer_m36",
"inception_v3",
"tinynet_a",
"selecsls42b",
"mobilevit_s",
"pytorch_CycleGAN_and_pix2pix",
"vision_maskrcnn",
"resmlp_12_224",
"dlrm",
"resnet50",
"dm_nfnet_f0",
"pit_b_224",
"tf_mixnet_l",
}
DO_NOT_CAST_INPUTS = {"stable_diffusion"}
def model_specified_by_path(path_and_class_str):
return ":" in path_and_class_str
def load_model_from_path(path_and_class_str):
configs = {}
for kvstr in path_and_class_str.split(","):
k, v = kvstr.split(":")
configs[k] = v
for name in ["path", "class"]:
if name not in configs:
raise RuntimeError(
"Invalid --only arguments. Check help message for the correct format"
)
path = configs["path"]
class_name = configs["class"]
if path[:1] != "/":
raise RuntimeError(
"Use absolute path since dynamo may change the current working directory which makes using relative path tricky"
)
spec = importlib.util.spec_from_file_location("module_name", path)
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
model_class = getattr(module, class_name)
assert issubclass(model_class, torch.nn.Module)
model = model_class()
assert hasattr(model, "get_example_inputs")
inputs = model.get_example_inputs()
return model, inputs
def output_csv(filename, headers, row):
if os.path.exists(filename):
with open(filename) as fd:
lines = list(csv.reader(fd)) or [[]]
if headers and len(headers) > len(lines[0]):
# if prior results failed the header might not be filled in yet
lines[0] = headers
else:
headers = lines[0]
else:
lines = [headers]
lines.append([(f"{x:.6f}" if isinstance(x, float) else x) for x in row])
with open(filename, "w") as fd:
writer = csv.writer(fd, lineterminator="\n")
for line in lines:
writer.writerow(list(line) + ["0"] * (len(headers) - len(line)))
def nothing(f):
return f
@functools.lru_cache(None)
def patch_torch_manual_seed():
"""Make torch manual seed deterministic. Helps with accuracy testing."""
def deterministic_torch_manual_seed(*args, **kwargs):
from torch._C import default_generator
seed = 1337
try:
import intel_extension_for_pytorch
if torch.xpu.is_available() and not torch.xpu._is_in_bad_fork():
torch.xpu.manual_seed_all(seed)
except:
import torch.cuda
if torch.cuda.is_available() and not torch.cuda._is_in_bad_fork():
torch.cuda.manual_seed_all(seed)
return default_generator.manual_seed(seed)
torch.manual_seed = deterministic_torch_manual_seed
def synchronize():
pass
def summarize_graph_break(filename):
"""
Sorts and de-dupes the graphs breaks on the reason string. Note that this
function is just a best effort to reduce the logging information. We could
miss some graph breaks because of de-duping. We can further refine this
function as need arises.
"""
log_file = f"{filename.rstrip('.csv')}_graph_breaks.csv"
if os.path.exists(log_file):
df = pd.read_csv(log_file)
df = df.sort_values("reason").drop_duplicates(subset="reason")
# Specialize for multi tensor sgd as reason is not identical
multi_tensor_sgd_row = df.loc[df["reason"].str.contains("_multi_tensor_sgd")]
if len(multi_tensor_sgd_row):
df = df[
~df["reason"].str.contains("_multi_tensor_sgd")
] # Drop all sgd rows
df = pd.concat(
[df, pd.DataFrame([multi_tensor_sgd_row.iloc[0]])], axis=0
) # Add back a single row
df.to_csv(f"{log_file.rstrip('.csv')}_deduped.csv", index=False)
def print_summary(filename, print_dataframe=False):
if not (filename and os.path.exists(filename)):
return
data = pd.read_csv(filename)
if "tag" in data.columns:
for tag in data.tag.unique():
if tag == "0.0000":
continue # This happens for failed runs
print(f"\nSummary for tag={tag}:")
print_summary_table(data[data.tag == tag], print_dataframe=print_dataframe)
else:
print_summary_table(data, print_dataframe=print_dataframe)
summarize_graph_break(filename)
def print_summary_table(data, print_dataframe=False):
if print_dataframe:
pd.options.display.max_rows = 1000
pd.options.display.max_columns = 1000
pd.options.display.width = 2000
print(data)
width = max(map(len, data.columns))
for col in data.columns:
try:
if col in ("dev", "name", "batch_size", "tag"):
continue
elif col in ("pct_ops", "pct_time"):
print(col.ljust(width), f"{data[col].mean():.3%}")
elif col in ("graphs", "graph_calls", "captured_ops", "total_ops"):
print(col.ljust(width), f"{data[col].mean():.3f}")
elif col in ("compilation_latency"):
print(col.ljust(width), f"mean={data[col].mean():.3f} seconds")
elif col in ("compression_ratio"):
print(col.ljust(width), f"mean={data[col].mean():.3f}x")
elif col in ("accuracy"):
pass_rate = (data[col] == "pass").mean()
print(col.ljust(width), f"pass_rate={100*pass_rate:.2f}%")
else:
cdata = data[col]
print(
col.ljust(width),
f"gmean={gmean(cdata):.2f}x mean={cdata.mean():.3f}x",
)
except Exception as e:
pass
def tensor_is_on_xla(tensors):
def visit(x: torch.Tensor):
nonlocal result
if x.device.type == "xla":
result = True
result = False
tree_map_only(torch.Tensor, visit, tensors)
return result
def timed(
model,
model_iter_fn,
example_inputs,
times=1,
return_result=False,
collect_outputs=False,
):
use_xla = tensor_is_on_xla(example_inputs)
synchronize()
if use_xla:
xm.mark_step()
xm.wait_device_ops()
time_total = 0
# Dont collect outputs to correctly measure timing
for _ in range(times):
# Put this call inside the loop to reset the seed for each iteration.
# Don't include reset_rng_state() to correctly measure timing
reset_rng_state(use_xla)
t_iter_begin = time.perf_counter()
result = model_iter_fn(model, example_inputs, collect_outputs=collect_outputs)
# instead of calling sync on result_list, we should call mark_step.
# In training case, result_list may be empty, but we want to
# send all the pending graphs for compilation.
if use_xla:
# For the model running on regular torchxla (baseline), we need the
# mark step to send the accumulated graph for compilation.
#
# For the model running with dynamo/torchxla bridge, in training case,
# we need the mark step to send the optimizer graph out for
# compilation.
xm.mark_step()
t_iter_end = time.perf_counter()
time_total += t_iter_end - t_iter_begin
t_0 = time.perf_counter()
if use_xla:
xm.wait_device_ops()
synchronize()
t_1 = time.perf_counter()
time_total += t_1 - t_0
return (time_total, result) if return_result else time_total
def _normalize_bench_inputs(example_inputs) -> Tuple[Tuple[Any], Mapping[str, Any]]:
# NOTE(bowbao): For huggingface benchmark, example_inputs are formatted as dictionary,
# and consumed like `model(**example_inputs)`.
# For other benchmarks, example_inputs are formatted as tuple and consumed
# like `model(*example_inputs)`.
if isinstance(example_inputs, dict):
return (), example_inputs
else:
return tuple(example_inputs), {}
def _register_dataclass_output_as_pytree(example_outputs) -> None:
# NOTE(angelayi): For huggingface benchmark, some example outputs are
# formatted as a dataclass which pytree cannot consume. So we want
# to register the pytree implementation here
example_outputs_flat = pytree.tree_leaves(example_outputs)
output_dataclass_types = [
type(out) for out in example_outputs_flat if dataclasses.is_dataclass(type(out))
]
for output_type in output_dataclass_types:
from torch._export.utils import register_dataclass_as_pytree_node
register_dataclass_as_pytree_node(
output_type,
serialized_type_name=f"{output_type.__module__}.{output_type.__name__}",
)
class Stats:
totals = collections.defaultdict(collections.Counter)
@classmethod
def reset_counters(cls):
for k, v in torch._dynamo.utils.counters.items():
cls.totals[k].update(v)
ok = torch._dynamo.utils.counters["frames"]["ok"]
total = torch._dynamo.utils.counters["frames"]["total"]
torch._dynamo.utils.counters.clear()
return ok, total
@classmethod
def print_summary(cls):
for k, v in sorted(cls.totals.items()):
lines = "\n ".join(map(str, v.most_common(50)))
print(f"STATS {k}\n {lines}")
@classmethod
def aot_summary(cls):
return [cls.totals["aot_autograd"]["total"], cls.totals["aot_autograd"]["ok"]]
def coverage_experiment(args, model_iter_fn, model, example_inputs):
"""
Test operator/model coverage of TorchDynamo and record statistics
taken from a profiler. This target is mainly intended to check
correctness.
Writes to ./coverage.csv
"""
profiler = Profiler()
frozen_model_iter_fn = torch._dynamo.run(model_iter_fn)
with profiler.prof:
frozen_model_iter_fn(model, example_inputs)
coverage_result = profiler.results()
output_csv(
output_filename,
(
"dev",
"name",
"batch_size",
"graphs",
"graph_calls",
"captured_ops",
"total_ops",
"pct_ops",
"pct_time",
),
[
current_device,
current_name,
current_batch_size,
]
+ coverage_result.tocsv(),
)
return coverage_result
def speedup_experiment_fx2trt(args, model_iter_fn, model, example_inputs):
"""
Measure speedups over eager using the trt inference backend. TRT backend is based fx graph
generated by torch._dynamo.
Writes to ./speedups_fx2trt.csv
"""
return speedup_experiment(args, model_iter_fn, model, example_inputs)
def recompile_profiler_experiment(args, model_iter_fn, model, example_inputs):
prof = torch._dynamo.utils.CompilerProfiler()
opt_model_iter_fn = torch._dynamo.optimize(prof, nopython=args.nopython)(
model_iter_fn
)
opt_model_iter_fn(model, example_inputs)
output_csv(
output_filename, ["model", "profiler report"], [current_name, prof.report()]
)
met = prof.get_metrics()
guard_failures = len(met["guard_failures"])
return [guard_failures]
def randomize_input(inputs):
if isinstance(inputs, (list, tuple)):
return type(inputs)([randomize_input(x) for x in inputs])
elif isinstance(inputs, torch.Tensor):
if inputs.dtype in (torch.float32, torch.float64):
torch._dynamo.utils.counters["randomize_input"]["times"] += 1
return torch.randn_like(inputs)
elif inputs.dtype == torch.int64:
# Note: we can not simply tune integer tensors as follows
# `return torch.randint_like(inputs, high=inputs.max().item())`
# This may break some invariants between tensors.
# E.g. in embedding lookup case, one tensor is the length
# and another is an indices tensor.
return inputs
else:
raise RuntimeError(
f"randomize_input need support tensor of type {inputs.dtype}"
)
else:
raise RuntimeError(
f"randomize_input can not handle input of type {type(inputs)}"
)
def maybe_mark_step(args):
if args.trace_on_xla:
xm.mark_step()
def speedup_experiment(args, model_iter_fn, model, example_inputs, **kwargs):
"""
Measure speedups over eager.
Writes to ./speedups.csv
"""
# if args.dynamic_shapes:
# return speedup_experiment_ds(args, model_iter_fn, model, example_inputs)
timings = np.zeros((args.repeat, 2), np.float64)
# if we randomize the input, we should also check the result is correct
should_randomize_input = args.randomize_input
import contextlib
from torch._inductor.utils import maybe_profile
@contextlib.contextmanager
def maybe_mark_profile(*args, **kwargs):
prof: torch.profiler.profile = kwargs.pop("p", None)
mark = kwargs.pop("mark", None)
if prof:
with torch.profiler.record_function(mark):
yield
else:
yield
times = args.iterations_per_run
# Use higher tolerance for XLA since XLA cause numerical unstability when
# graph size changes
tolerance = args.xla_tolerance if args.trace_on_xla else 1e-4
torch._dynamo.config.repro_tolerance = tolerance
with maybe_profile(args.export_profiler_trace) as p:
if args.export_aot_inductor:
frozen_model_iter_fn = export_aot_inductor(
model, example_inputs, args.devices[0]
)
else:
frozen_model_iter_fn = torch._dynamo.run(model_iter_fn)
for rep in trange(args.repeat, desc="running benchmark"):
inputs = (
randomize_input(copy.deepcopy(example_inputs))
if should_randomize_input
else example_inputs
)
# need call mark_step to perform the computation
# on randomize_input. Otherwise the first call using the
# inputs will incur high penalty then the next one.
maybe_mark_step(args)
# interleave the runs to handle frequency scaling and load changes
with maybe_mark_profile(p=p, mark="expected"):
timings[rep, 0], expected_output = timed(
model,
model_iter_fn,
inputs,
return_result=True,
times=times,
collect_outputs=args.collect_outputs,
)
# call mark_step between the 2 calls to make the comparison fair.
maybe_mark_step(args)
with maybe_mark_profile(p=p, mark="actual"), maybe_enable_compiled_autograd(
args.compiled_autograd
):
timings[rep, 1], actual_output = timed(
model,
frozen_model_iter_fn,
inputs,
return_result=True,
times=times,
collect_outputs=args.collect_outputs,
)
if args.export_profiler_trace:
name = args.profiler_trace_name + "_" + model.name
if hasattr(args, "rank"):
name += f"_rank_{args.rank}"
name += ".json"
name = os.path.join(torch._dynamo.config.base_dir, name)
p.export_chrome_trace(name)
median = np.median(timings, axis=0)
speedup = median[0] / median[1]
if args.dump_raw_metrics:
np.save(
f"{output_filename[:-4]}-raw_timings-{current_name}-{current_device}.npy",
timings,
)
first_headers = ["dev", "name", "batch_size"]
first_fields = [current_device, current_name, current_batch_size]
if "tag" in kwargs:
first_headers.append("tag")
first_fields.append(kwargs["tag"])
headers = first_headers + ["speedup", "abs_latency"]
row = first_fields + [float(speedup), median[1] * 1000]
msg = f"{speedup:.3f}x"
if args.baseline:
headers.extend(
[
"baseline",
"speedup_vs_baseline",
]
)
df = pd.read_csv(args.baseline)
try:
baseline_speedup = df[df["name"] == current_name]["speedup"].item()
row.extend([baseline_speedup, speedup / baseline_speedup])
msg = f"{baseline_speedup:.3f}x -> {speedup:.3f}x [{speedup / baseline_speedup:.3f}x]"
except (KeyError, ZeroDivisionError):
row.extend(
[
0.0,
0.0,
]
)
if "compilation_latency" in kwargs:
headers += [
"compilation_latency",
"compression_ratio",
"eager_peak_mem",
"dynamo_peak_mem",
]
row.append(kwargs["compilation_latency"])
row.append(kwargs["compression_ratio"])
row.append(kwargs["eager_peak_mem"])
row.append(kwargs["dynamo_peak_mem"])
if "dynamo_stats" in kwargs:
for k, v in kwargs["dynamo_stats"].items():
headers.append(k)
row.append(v)
output_csv(
output_filename,
headers,
row,
)
headers, data = torch._dynamo.utils.compile_times(repr="csv", aggregate=True)
assert (
output_filename.find(".csv") > 0
), f"expected output_filename to be a .csv, but got {output_filename}"
output_csv(
output_filename[:-4] + "_compilation_metrics.csv",
first_headers + headers,
first_fields + data,
)
return msg
def speedup_experiment_ds(args, model_iter_fn, model, example_inputs):
"""
Run dynamic shapes benchmarks.
Requires dynamic shape compatible models, which provide a list of example inputs.
Warms up using the first input example and then iterates the inputs,
measuring (and expecting minimal) variance between the runtime for different examples.
"""
timings = np.zeros((args.repeat, len(example_inputs), 2), np.float64)
if args.repeat > 5:
print(
f"\ndynamic shapes experiments are slow, consider setting --repeat less than {args.repeat}\n"
)
nwarmup = 4
for rep in range(args.repeat):
# Start each rep fresh, e.g. only warmup on example 0
torch._dynamo.reset()
optimized_model_iter_fn = optimize_ctx(model_iter_fn)
for _ in range(nwarmup):
optimized_model_iter_fn(model, example_inputs[0])
for input_idx, inputs in enumerate(example_inputs):
# interleave the runs to handle frequency scaling and load changes
timings[rep, input_idx, 0] = timed(
model, model_iter_fn, inputs, return_result=False
)
# different from regular speedup_experiment, we _DO_ want to allow recompilation
timings[rep, input_idx, 1] = timed(
model, optimized_model_iter_fn, inputs, return_result=False
)
medians = np.median(timings, axis=0)
speedups = list(medians[:, 0] / medians[:, 1])
speedups_mean = np.mean(speedups)
speedups_median = np.median(speedups)
speedups_var = np.var(speedups)
# TODO this x[0] is not going to work in general but bert only has 1 input
shapes = [x[0].shape for x in example_inputs]
shape_keys = sorted(set(shapes))
shape_speedups = {
shape: [
it[1] for it in filter(lambda it: it[0] == shape, zip(shapes, speedups))
]
for shape in shape_keys
}
output_str = (
f"mean: {speedups_mean:.3f}, median: {speedups_median:.3f}, var: {speedups_var:.3f}"
+ "\nSpeedups by shape: "
+ "\n".join(
[
f"{shape}: "
+ ", ".join([f"{speedup: .3g}" for speedup in shape_speedups[shape]])
for shape in shape_keys
]
)
)
output_csv(
output_filename,
("dev", "name", "batch_size", "speedup mean", "speedup median", "speedup var"),
[
current_device,
current_name,
current_batch_size,
speedups_mean,
speedups_median,
speedups_var,
],
)
return output_str
@contextlib.contextmanager
def override_synchronize_with_onnx_iobinding(iobinding):
global synchronize
prev_synchrnoize = synchronize
try:
if iobinding is not None:
def new_synchronize():
iobinding.synchronize_inputs()
iobinding.synchronize_outputs()
synchronize = new_synchronize
yield
finally:
synchronize = prev_synchrnoize
def speedup_experiment_onnx(
args,
model_iter_fn,
onnx_model: OnnxModel,
model,
example_inputs,
**kwargs,
):
"""
Measure speedups over eager.
This function is responsible for the following:
1. Creating iobinding with OnnxModel if device is CUDA, which is essential for perf measurement.
2. Running ORT with OnnxModel.
Writes to ./{output_filename}, which should be
`pathlib.Path(self.output_dir) / f"{self.compiler}_{suite}_{self.dtype}_{self.mode}_{self.device}_{self.testing}.csv".
TODO(bowbao): Record export time and export peak memory usage.
"""
timings = np.zeros((args.repeat, 2), np.float64)
is_correct = True
should_randomize_input = args.randomize_input
times = args.iterations_per_run
def create_onnx_input_binded_fn(onnx_model: OnnxModel, pt_inputs, example_outputs):
# Goal is to move the iobinding creation outside of the timer function.
iobinding, outputs = onnx_model.create_iobinding(pt_inputs, example_outputs)
def onnxrt_model_iter_fn(model, inputs, collect_outputs=True):
onnx_model.run_with_iobinding(iobinding, outputs)
if collect_outputs:
return outputs
return onnxrt_model_iter_fn, iobinding
def create_onnx_fn(onnx_model: OnnxModel, pt_inputs):
# NOTE: Making perf comparison fair by moving out the i/o adapting part.
# 1. Pre-adapt `pt_inputs` to `onnx_inputs` here.
# 2. Drop `onnx_outputs` to `pt_outputs` adapting. Output comparison is not part of perf measurement.
onnx_inputs = onnx_model.adapt_pt_inputs_to_onnx(pt_inputs)
def onnxrt_model_iter_fn(model, inputs, collect_outputs=True):
return onnx_model.run_with_onnx_inputs(onnx_inputs)
return onnxrt_model_iter_fn
def timed_onnx(model, onnx_model: OnnxModel, inputs):
if current_device == "cpu" or onnx_model.is_cpu():
onnxrt_model_iter_fn = create_onnx_fn(onnx_model, inputs)
iobinding = None
else:
onnxrt_model_iter_fn, iobinding = create_onnx_input_binded_fn(
onnx_model, inputs, expected_output
)
with override_synchronize_with_onnx_iobinding(iobinding):
return timed(
model,
onnxrt_model_iter_fn,
inputs,
return_result=True,
times=times,
collect_outputs=args.collect_outputs,
)
# Insert ONNX warm-up
inputs = (
randomize_input(copy.deepcopy(example_inputs))
if should_randomize_input
else example_inputs
)
_, expected_output = timed(
model,
model_iter_fn,
inputs,
return_result=True,
times=times,
collect_outputs=args.collect_outputs,
)
for _ in range(2):
timed_onnx(model, onnx_model, inputs)
for rep in range(args.repeat):
inputs = (
randomize_input(copy.deepcopy(example_inputs))
if should_randomize_input
else example_inputs
)
if torch.cuda.device_count() > 1:
# Manually set correct torch.cuda.current_device to ensure torch.cuda.synchronize() works as intended.
# When there are more than 1 cuda devices, the first one is used for pytorch eager.
# The second one is used for onnx ort.
torch.cuda.set_device(0)
timings[rep, 0], expected_output = timed(
model,
model_iter_fn,
inputs,
return_result=True,
times=times,
collect_outputs=args.collect_outputs,
)
if torch.cuda.device_count() > 1:
# Manually set correct torch.cuda.current_device to ensure torch.cuda.synchronize() works as intended.
# When there are more than 1 cuda devices, the first one is used for pytorch eager.
# The second one is used for onnx ort.
torch.cuda.set_device(1)
timings[rep, 1], actual_output = timed_onnx(model, onnx_model, inputs)
pvalue = ttest_ind(timings[:, 0], timings[:, 1]).pvalue
median = np.median(timings, axis=0)
speedup = median[0] / median[1]
if args.dump_raw_metrics:
np.save(
f"{output_filename[:-4]}-raw_timings-{current_name}-{current_device}.npy",
timings,
)
headers = ["dev", "name", "batch_size", "speedup", "abs_latency"]
row = [
current_device,
current_name,
current_batch_size,
float(speedup),
median[1] * 1000,
]
if "compilation_latency" in kwargs:
headers = headers + ["compilation_latency", "compression_ratio"]
row.append(kwargs["compilation_latency"])
row.append(kwargs["compression_ratio"])
output_csv(
output_filename,
headers,
row,
)
headers, data = torch._dynamo.utils.compile_times(repr="csv", aggregate=True)
assert (
output_filename.find(".csv") > 0
), f"expected output_filename to be a .csv, but got {output_filename}"
output_csv(
output_filename[:-4] + "_compilation_metrics.csv",