forked from pytorch/pytorch
-
Notifications
You must be signed in to change notification settings - Fork 0
/
run_test.py
executable file
·1790 lines (1562 loc) · 62.4 KB
/
run_test.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
import argparse
import copy
import glob
import json
import os
import pathlib
import re
import shutil
import signal
import subprocess
import sys
import tempfile
import time
from contextlib import ExitStack
from datetime import datetime
from typing import Any, cast, Dict, List, NamedTuple, Optional, Tuple, Union
import pkg_resources
import torch
import torch.distributed as dist
from packaging import version
from torch.multiprocessing import current_process, get_context
from torch.testing._internal.common_utils import (
FILE_SCHEMA,
get_report_path,
IS_CI,
parser as common_parser,
retry_shell,
set_cwd,
shell,
TEST_WITH_ASAN,
TEST_WITH_ROCM,
TEST_WITH_SLOW_GRADCHECK,
)
REPO_ROOT = pathlib.Path(__file__).resolve().parent.parent
# using tools/ to optimize test run.
sys.path.insert(0, str(REPO_ROOT))
from tools.stats.export_test_times import TEST_TIMES_FILE
from tools.stats.upload_metrics import add_global_metric, emit_metric
from tools.testing.target_determination.determinator import (
AggregatedHeuristics,
get_test_prioritizations,
)
from tools.testing.test_selections import (
calculate_shards,
get_test_case_configs,
NUM_PROCS,
ShardedTest,
THRESHOLD,
)
HAVE_TEST_SELECTION_TOOLS = True
# Make sure to remove REPO_ROOT after import is done
sys.path.remove(str(REPO_ROOT))
RERUN_DISABLED_TESTS = os.getenv("PYTORCH_TEST_RERUN_DISABLED_TESTS", "0") == "1"
CPP_TEST_PREFIX = "cpp"
CPP_TEST_PATH = "build/bin"
DISTRIBUTED_TEST_PREFIX = "distributed"
# Note [ROCm parallel CI testing]
# https://github.com/pytorch/pytorch/pull/85770 added file-granularity parallel testing.
# In .ci/pytorch/test.sh, TEST_CONFIG == "default", CUDA and HIP_VISIBLE_DEVICES is set to 0.
# This results in multiple test files sharing the same GPU.
# This should be a supported use case for ROCm, but it exposed issues in the kernel driver resulting in hangs.
# See https://github.com/pytorch/pytorch/issues/90940.
#
# Further, ROCm self-hosted runners have up to 4 GPUs.
# Device visibility was set to 0 to match CUDA test behavior, but this was wasting available GPU resources.
# Assigning each Pool worker their own dedicated GPU avoids the ROCm oversubscription issues.
# This should also result in better overall wall clock time since all GPUs can be utilized.
def maybe_set_hip_visible_devies():
# Special handling of ROCm GHA runners for parallel (file granularity) tests.
if torch.version.hip:
p = current_process()
if p.name != "MainProcess":
# this is a Process from a parallel Pool, not the MainProcess
os.environ["HIP_VISIBLE_DEVICES"] = str(p._identity[0] % NUM_PROCS)
def strtobool(s):
if s.lower() in ["", "0", "false", "off"]:
return False
return True
def parse_test_module(test):
return test.split(".")[0]
class TestChoices(list):
def __init__(self, *args, **kwargs):
super().__init__(args[0])
def __contains__(self, item):
return list.__contains__(self, parse_test_module(item))
def discover_tests(
base_dir: Optional[pathlib.Path] = None,
cpp_tests_dir: Optional[pathlib.Path] = None,
blocklisted_patterns: Optional[List[str]] = None,
blocklisted_tests: Optional[List[str]] = None,
extra_tests: Optional[List[str]] = None,
) -> List[str]:
"""
Searches for all python files starting with test_ excluding one specified by patterns.
If cpp_tests_dir is provided, also scan for all C++ tests under that directory. They
are usually found in build/bin
"""
def skip_test_p(name: str) -> bool:
rc = False
if blocklisted_patterns is not None:
rc |= any(name.startswith(pattern) for pattern in blocklisted_patterns)
if blocklisted_tests is not None:
rc |= name in blocklisted_tests
return rc
cwd = pathlib.Path(__file__).resolve().parent if base_dir is None else base_dir
# This supports symlinks, so we can link domain library tests to PyTorch test directory
all_py_files = [
pathlib.Path(p) for p in glob.glob(f"{cwd}/**/test_*.py", recursive=True)
]
cpp_tests_dir = (
f"{cwd.parent}/{CPP_TEST_PATH}" if cpp_tests_dir is None else cpp_tests_dir
)
# CPP test files are located under pytorch/build/bin. Unlike Python test, C++ tests
# are just binaries and could have any name, i.e. basic or atest
all_cpp_files = [
pathlib.Path(p) for p in glob.glob(f"{cpp_tests_dir}/**/*", recursive=True)
]
rc = [str(fname.relative_to(cwd))[:-3] for fname in all_py_files]
# Add the cpp prefix for C++ tests so that we can tell them apart
rc.extend(
[
parse_test_module(f"{CPP_TEST_PREFIX}/{fname.relative_to(cpp_tests_dir)}")
for fname in all_cpp_files
]
)
# Invert slashes on Windows
if sys.platform == "win32":
rc = [name.replace("\\", "/") for name in rc]
rc = [test for test in rc if not skip_test_p(test)]
if extra_tests is not None:
rc += extra_tests
return sorted(rc)
CPP_TESTS_DIR = os.path.abspath(os.getenv("CPP_TESTS_DIR", default=CPP_TEST_PATH))
TESTS = discover_tests(
cpp_tests_dir=CPP_TESTS_DIR,
blocklisted_patterns=[
"ao",
"bottleneck_test",
"custom_backend",
"custom_operator",
"fx", # executed by test_fx.py
"jit", # executed by test_jit.py
"mobile",
"onnx_caffe2",
"package", # executed by test_package.py
"quantization", # executed by test_quantization.py
"autograd", # executed by test_autograd.py
],
blocklisted_tests=[
"test_bundled_images",
"test_cpp_extensions_aot",
"test_determination",
"test_jit_fuser",
"test_jit_simple",
"test_jit_string",
"test_kernel_launch_checks",
"test_nnapi",
"test_static_runtime",
"test_throughput_benchmark",
"test_typing",
"distributed/bin/test_script",
"distributed/elastic/multiprocessing/bin/test_script",
"distributed/launcher/bin/test_script",
"distributed/launcher/bin/test_script_init_method",
"distributed/launcher/bin/test_script_is_torchelastic_launched",
"distributed/launcher/bin/test_script_local_rank",
"distributed/test_c10d_spawn",
"distributions/test_transforms",
"distributions/test_utils",
"onnx/test_pytorch_onnx_onnxruntime_cuda",
"onnx/test_models",
# These are not C++ tests
f"{CPP_TEST_PREFIX}/CMakeFiles",
f"{CPP_TEST_PREFIX}/CTestTestfile.cmake",
f"{CPP_TEST_PREFIX}/Makefile",
f"{CPP_TEST_PREFIX}/cmake_install.cmake",
f"{CPP_TEST_PREFIX}/c10_intrusive_ptr_benchmark",
f"{CPP_TEST_PREFIX}/example_allreduce",
f"{CPP_TEST_PREFIX}/parallel_benchmark",
f"{CPP_TEST_PREFIX}/protoc",
f"{CPP_TEST_PREFIX}/protoc-3.13.0.0",
f"{CPP_TEST_PREFIX}/torch_shm_manager",
f"{CPP_TEST_PREFIX}/tutorial_tensorexpr",
],
extra_tests=[
"test_cpp_extensions_aot_ninja",
"test_cpp_extensions_aot_no_ninja",
"distributed/elastic/timer/api_test",
"distributed/elastic/timer/local_timer_example",
"distributed/elastic/timer/local_timer_test",
"distributed/elastic/events/lib_test",
"distributed/elastic/metrics/api_test",
"distributed/elastic/utils/logging_test",
"distributed/elastic/utils/util_test",
"distributed/elastic/utils/distributed_test",
"distributed/elastic/multiprocessing/api_test",
],
)
# The doctests are a special case that don't correspond to a file that discover
# tests can enable.
TESTS = TESTS + ["doctests"]
FSDP_TEST = [test for test in TESTS if test.startswith("distributed/fsdp")]
WINDOWS_BLOCKLIST = [
"distributed/nn/jit/test_instantiator",
"distributed/rpc/test_faulty_agent",
"distributed/rpc/test_tensorpipe_agent",
"distributed/rpc/test_share_memory",
"distributed/rpc/cuda/test_tensorpipe_agent",
"distributed/pipeline/sync/skip/test_api",
"distributed/pipeline/sync/skip/test_gpipe",
"distributed/pipeline/sync/skip/test_inspect_skip_layout",
"distributed/pipeline/sync/skip/test_leak",
"distributed/pipeline/sync/skip/test_portal",
"distributed/pipeline/sync/skip/test_stash_pop",
"distributed/pipeline/sync/skip/test_tracker",
"distributed/pipeline/sync/skip/test_verify_skippables",
"distributed/pipeline/sync/test_balance",
"distributed/pipeline/sync/test_bugs",
"distributed/pipeline/sync/test_checkpoint",
"distributed/pipeline/sync/test_copy",
"distributed/pipeline/sync/test_deferred_batch_norm",
"distributed/pipeline/sync/test_dependency",
"distributed/pipeline/sync/test_inplace",
"distributed/pipeline/sync/test_microbatch",
"distributed/pipeline/sync/test_phony",
"distributed/pipeline/sync/test_pipe",
"distributed/pipeline/sync/test_pipeline",
"distributed/pipeline/sync/test_stream",
"distributed/pipeline/sync/test_transparency",
"distributed/pipeline/sync/test_worker",
"distributed/elastic/agent/server/test/api_test",
"distributed/elastic/multiprocessing/api_test",
"distributed/_shard/checkpoint/test_checkpoint"
"distributed/_shard/checkpoint/test_file_system_checkpoint"
"distributed/_shard/sharding_spec/test_sharding_spec",
"distributed/_shard/sharding_plan/test_sharding_plan",
"distributed/_shard/sharded_tensor/test_sharded_tensor",
"distributed/_shard/sharded_tensor/test_sharded_tensor_reshard",
"distributed/_shard/sharded_tensor/ops/test_embedding",
"distributed/_shard/sharded_tensor/ops/test_embedding_bag",
"distributed/_shard/sharded_tensor/ops/test_binary_cmp",
"distributed/_shard/sharded_tensor/ops/test_init",
"distributed/_shard/sharded_optim/test_sharded_optim",
] + FSDP_TEST
ROCM_BLOCKLIST = [
"distributed/rpc/test_faulty_agent",
"distributed/rpc/test_tensorpipe_agent",
"distributed/rpc/test_share_memory",
"distributed/rpc/cuda/test_tensorpipe_agent",
"distributed/_shard/checkpoint/test_checkpoint"
"distributed/_shard/checkpoint/test_file_system_checkpoint"
"distributed/_shard/sharding_spec/test_sharding_spec",
"distributed/_shard/sharding_plan/test_sharding_plan",
"distributed/_shard/sharded_tensor/test_sharded_tensor",
"distributed/_shard/sharded_tensor/test_sharded_tensor_reshard",
"distributed/_shard/sharded_tensor/ops/test_embedding",
"distributed/_shard/sharded_tensor/ops/test_embedding_bag",
"distributed/_shard/sharded_tensor/ops/test_binary_cmp",
"distributed/_shard/sharded_tensor/ops/test_init",
"distributed/_shard/sharded_optim/test_sharded_optim",
"test_determination",
"test_jit_legacy",
"test_cuda_nvml_based_avail",
"test_jit_cuda_fuser",
]
# The tests inside these files should never be run in parallel with each other
RUN_PARALLEL_BLOCKLIST = [
"test_cpp_extensions_jit",
"test_cpp_extensions_open_device_registration",
"test_jit_disabled",
"test_mobile_optimizer",
"test_multiprocessing",
"test_multiprocessing_spawn",
"test_namedtuple_return_api",
"test_overrides",
"test_show_pickle",
"test_tensorexpr",
"test_cuda_primary_ctx",
"test_cuda_trace",
"test_cuda_nvml_based_avail",
# temporarily sets a global config
"test_autograd_fallback",
] + FSDP_TEST
# Test files that should always be run serially with other test files,
# but it's okay if the tests inside them are run in parallel with each other.
CI_SERIAL_LIST = [
"test_nn",
"test_fake_tensor",
"test_cpp_api_parity",
"test_reductions",
"test_cuda",
"test_cuda_expandable_segments",
"test_indexing",
"test_fx_backends",
"test_linalg",
"test_cpp_extensions_jit",
"test_torch",
"test_tensor_creation_ops",
"test_sparse_csr",
"test_dispatch",
"test_python_dispatch", # torch.library creation and deletion must be serialized
"test_spectral_ops", # Cause CUDA illegal memory access https://github.com/pytorch/pytorch/issues/88916
"nn/test_pooling",
"nn/test_convolution", # Doesn't respect set_per_process_memory_fraction, results in OOM for other tests in slow gradcheck
"distributions/test_distributions",
"test_autograd", # slow gradcheck runs a test that checks the cuda memory allocator
"test_prims", # slow gradcheck runs a test that checks the cuda memory allocator
"test_modules", # failed test due to mismatched elements
"functorch/test_vmap", # OOM
"test_fx", # gets SIGKILL
"test_dataloader", # frequently hangs for ROCm
"test_serialization", # test_serialization_2gb_file allocates a tensor of 2GB, and could cause OOM
"test_schema_check", # Cause CUDA illegal memory access https://github.com/pytorch/pytorch/issues/95749
"functorch/test_memory_efficient_fusion", # Cause CUDA OOM on ROCm
"test_utils", # OOM
"test_sort_and_select", # OOM
"test_backward_compatible_arguments", # OOM
"test_module_init", # OOM
"test_autocast", # OOM
"test_native_mha", # OOM
"test_module_hooks", # OOM
"inductor/test_max_autotune", # Testing, probably revert later
]
# A subset of onnx tests that cannot run in parallel due to high memory usage.
ONNX_SERIAL_LIST = [
"onnx/test_models",
"onnx/test_models_quantized_onnxruntime",
"onnx/test_models_onnxruntime",
"onnx/test_custom_ops",
"onnx/test_utility_funs",
]
# A subset of our TEST list that validates PyTorch's ops, modules, and autograd function as expected
CORE_TEST_LIST = [
"test_autograd",
"test_autograd_fallback",
"test_modules",
"test_nn",
"test_ops",
"test_ops_gradients",
"test_ops_fwd_gradients",
"test_ops_jit",
"test_torch",
]
# if a test file takes longer than 5 min, we add it to TARGET_DET_LIST
SLOW_TEST_THRESHOLD = 300
DISTRIBUTED_TESTS_CONFIG = {}
if dist.is_available():
DISTRIBUTED_TESTS_CONFIG["test"] = {"WORLD_SIZE": "1"}
if not TEST_WITH_ROCM and dist.is_mpi_available():
DISTRIBUTED_TESTS_CONFIG["mpi"] = {
"WORLD_SIZE": "3",
"TEST_REPORT_SOURCE_OVERRIDE": "dist-mpi",
}
if dist.is_nccl_available():
DISTRIBUTED_TESTS_CONFIG["nccl"] = {
"WORLD_SIZE": "2" if torch.cuda.device_count() == 2 else "3",
"TEST_REPORT_SOURCE_OVERRIDE": "dist-nccl",
}
if dist.is_gloo_available():
DISTRIBUTED_TESTS_CONFIG["gloo"] = {
"WORLD_SIZE": "2" if torch.cuda.device_count() == 2 else "3",
"TEST_REPORT_SOURCE_OVERRIDE": "dist-gloo",
}
if dist.is_ucc_available():
DISTRIBUTED_TESTS_CONFIG["ucc"] = {
"WORLD_SIZE": "2" if torch.cuda.device_count() == 2 else "3",
"TEST_REPORT_SOURCE_OVERRIDE": "dist-ucc",
"UCX_TLS": "tcp,cuda",
"UCC_TLS": "nccl,ucp,cuda",
"UCC_TL_UCP_TUNE": "cuda:0", # don't use UCP TL on CUDA as it is not well supported
"UCC_EC_CUDA_USE_COOPERATIVE_LAUNCH": "n", # CI nodes (M60) fail if it is on
}
# https://stackoverflow.com/questions/2549939/get-signal-names-from-numbers-in-python
SIGNALS_TO_NAMES_DICT = {
getattr(signal, n): n for n in dir(signal) if n.startswith("SIG") and "_" not in n
}
CPP_EXTENSIONS_ERROR = """
Ninja (https://ninja-build.org) is required for some of the C++ extensions
tests, but it could not be found. Install ninja with `pip install ninja`
or `conda install ninja`. Alternatively, disable said tests with
`run_test.py --exclude test_cpp_extensions_aot_ninja test_cpp_extensions_jit`.
"""
PYTORCH_COLLECT_COVERAGE = bool(os.environ.get("PYTORCH_COLLECT_COVERAGE"))
JIT_EXECUTOR_TESTS = [
"test_jit_profiling",
"test_jit_legacy",
"test_jit_fuser_legacy",
]
DISTRIBUTED_TESTS = [test for test in TESTS if test.startswith(DISTRIBUTED_TEST_PREFIX)]
FUNCTORCH_TESTS = [test for test in TESTS if test.startswith("functorch")]
ONNX_TESTS = [test for test in TESTS if test.startswith("onnx")]
CPP_TESTS = [test for test in TESTS if test.startswith(CPP_TEST_PREFIX)]
TESTS_REQUIRING_LAPACK = [
"distributions/test_constraints",
"distributions/test_distributions",
]
# These are just the slowest ones, this isn't an exhaustive list.
TESTS_NOT_USING_GRADCHECK = [
# Note that you should use skipIfSlowGradcheckEnv if you do not wish to
# skip all the tests in that file, e.g. test_mps
"doctests",
"test_meta",
"test_hub",
"test_fx",
"test_decomp",
"test_cpp_extensions_jit",
"test_jit",
"test_ops",
"test_ops_jit",
"dynamo/test_recompile_ux",
"inductor/test_smoke",
"test_quantization",
]
def print_to_stderr(message):
print(message, file=sys.stderr)
def get_executable_command(options, disable_coverage=False, is_cpp_test=False):
if options.coverage and not disable_coverage:
if not is_cpp_test:
executable = ["coverage", "run", "--parallel-mode", "--source=torch"]
else:
# TODO: C++ with coverage is not yet supported
executable = []
else:
if not is_cpp_test:
executable = [sys.executable, "-bb"]
else:
executable = ["pytest"]
return executable
def run_test(
test_module,
test_directory,
options,
launcher_cmd=None,
extra_unittest_args=None,
env=None,
) -> int:
maybe_set_hip_visible_devies()
unittest_args = options.additional_unittest_args.copy()
test_file = test_module
stepcurrent_key = test_file
use_sharded_test = False
if isinstance(test_file, ShardedTest):
test_file = test_module.name
use_sharded_test = True
is_distributed_test = test_file.startswith(DISTRIBUTED_TEST_PREFIX)
is_cpp_test = test_file.startswith(CPP_TEST_PREFIX)
# NB: Rerun disabled tests depends on pytest-flakefinder and it doesn't work with
# pytest-cpp atm. We also don't have support to disable C++ test yet, so it's ok
# to just return successfully here
if is_cpp_test and RERUN_DISABLED_TESTS:
print_to_stderr(
"Skipping C++ tests when running under RERUN_DISABLED_TESTS mode"
)
return 0
if use_sharded_test:
if is_cpp_test:
stepcurrent_key = test_file
else:
unittest_args.extend(
[
f"--shard-id={test_module.shard - 1}",
f"--num-shards={test_module.num_shards}",
]
)
stepcurrent_key = f"{test_file}_{test_module.shard - 1}"
if options.verbose:
unittest_args.append(f'-{"v"*options.verbose}') # in case of pytest
if test_file in RUN_PARALLEL_BLOCKLIST:
unittest_args = [
arg for arg in unittest_args if not arg.startswith("--run-parallel")
]
if extra_unittest_args:
assert isinstance(extra_unittest_args, list)
unittest_args.extend(extra_unittest_args)
# If using pytest, replace -f with equivalent -x
if options.pytest:
unittest_args.extend(
get_pytest_args(
options,
stepcurrent_key,
is_cpp_test=is_cpp_test,
is_distributed_test=is_distributed_test,
)
)
unittest_args = [arg if arg != "-f" else "-x" for arg in unittest_args]
# TODO: These features are not available for C++ test yet
if IS_CI and not is_cpp_test:
ci_args = ["--import-slow-tests", "--import-disabled-tests"]
if RERUN_DISABLED_TESTS:
ci_args.append("--rerun-disabled-tests")
# use the downloaded test cases configuration, not supported in pytest
unittest_args.extend(ci_args)
if test_file in PYTEST_SKIP_RETRIES:
if not options.pytest:
raise RuntimeError(
"A test running without pytest cannot skip retries using "
"the PYTEST_SKIP_RETRIES set."
)
unittest_args = [arg for arg in unittest_args if "--reruns" not in arg]
# Extra arguments are not supported with pytest
executable = get_executable_command(options, is_cpp_test=is_cpp_test)
if not executable:
# If there is no eligible executable returning here, it means an unsupported
# case such as coverage for C++ test. So just returning ok makes sense
return 0
if test_file.startswith(CPP_TEST_PREFIX):
# C++ tests are not the regular test directory
if CPP_TESTS_DIR:
cpp_test = os.path.join(
CPP_TESTS_DIR,
test_file.replace(f"{CPP_TEST_PREFIX}/", ""),
)
else:
cpp_test = os.path.join(
pathlib.Path(test_directory).parent,
CPP_TEST_PATH,
test_file.replace(f"{CPP_TEST_PREFIX}/", ""),
)
argv = [
cpp_test if sys.platform != "win32" else cpp_test + ".exe"
] + unittest_args
else:
# Can't call `python -m unittest test_*` here because it doesn't run code
# in `if __name__ == '__main__': `. So call `python test_*.py` instead.
argv = [test_file + ".py"] + unittest_args
os.makedirs(REPO_ROOT / "test" / "test-reports", exist_ok=True)
if IS_CI:
log_fd, log_path = tempfile.mkstemp(
dir=REPO_ROOT / "test" / "test-reports",
prefix=f"{sanitize_file_name(str(test_module))}_",
suffix="_toprint.log",
)
os.close(log_fd)
command = (launcher_cmd or []) + executable + argv
should_file_rerun = (
"--subprocess" not in command
and not RERUN_DISABLED_TESTS
and not options.continue_through_error
)
is_slow = "slow" in os.environ.get("TEST_CONFIG", "") or "slow" in os.environ.get(
"BUILD_ENVRIONMENT", ""
)
timeout = (
THRESHOLD * 6
if is_slow
else THRESHOLD * 3
if should_file_rerun
and isinstance(test_module, ShardedTest)
and test_module.time is not None
else None
)
print_to_stderr(f"Executing {command} ... [{datetime.now()}]")
with ExitStack() as stack:
output = None
if IS_CI:
output = stack.enter_context(open(log_path, "w"))
ret_code, was_rerun = retry_shell(
command,
test_directory,
stdout=output,
stderr=output,
env=env,
timeout=timeout,
retries=2 if should_file_rerun else 0,
)
# Pytest return code 5 means no test is collected. This is needed
# here as we use pytest directly when running C++ tests. Return
# code 4 is ok too as this happens when the binary is not a C++
# test executable. All binary files under build/bin that are not
# C++ test at the time of this writing have been excluded, but we
# can accept code 4 too just in case a new non-test binary file
# comes up in the future.
ret_code = 0 if ret_code == 5 or ret_code == 4 else ret_code
if IS_CI:
handle_log_file(
test_module, log_path, failed=(ret_code != 0), was_rerun=was_rerun
)
return ret_code
def run_test_with_subprocess(test_module, test_directory, options):
return run_test(
test_module, test_directory, options, extra_unittest_args=["--subprocess"]
)
def _test_cpp_extensions_aot(test_directory, options, use_ninja):
if use_ninja:
try:
from torch.utils import cpp_extension
cpp_extension.verify_ninja_availability()
except RuntimeError:
print_to_stderr(CPP_EXTENSIONS_ERROR)
return 1
# Wipe the build folder, if it exists already
cpp_extensions_test_dir = os.path.join(test_directory, "cpp_extensions")
cpp_extensions_test_build_dir = os.path.join(cpp_extensions_test_dir, "build")
if os.path.exists(cpp_extensions_test_build_dir):
shutil.rmtree(cpp_extensions_test_build_dir)
# Build the test cpp extensions modules
shell_env = os.environ.copy()
shell_env["USE_NINJA"] = str(1 if use_ninja else 0)
cmd = [sys.executable, "setup.py", "install", "--root", "./install"]
return_code = shell(cmd, cwd=cpp_extensions_test_dir, env=shell_env)
if return_code != 0:
return return_code
if sys.platform != "win32":
return_code = shell(
cmd,
cwd=os.path.join(cpp_extensions_test_dir, "no_python_abi_suffix_test"),
env=shell_env,
)
if return_code != 0:
return return_code
# "install" the test modules and run tests
python_path = os.environ.get("PYTHONPATH", "")
from shutil import copyfile
os.environ["USE_NINJA"] = shell_env["USE_NINJA"]
test_module = "test_cpp_extensions_aot" + ("_ninja" if use_ninja else "_no_ninja")
copyfile(
test_directory + "/test_cpp_extensions_aot.py",
test_directory + "/" + test_module + ".py",
)
try:
cpp_extensions = os.path.join(test_directory, "cpp_extensions")
install_directory = ""
# install directory is the one that is named site-packages
for root, directories, _ in os.walk(os.path.join(cpp_extensions, "install")):
for directory in directories:
if "-packages" in directory:
install_directory = os.path.join(root, directory)
assert install_directory, "install_directory must not be empty"
os.environ["PYTHONPATH"] = os.pathsep.join([install_directory, python_path])
return run_test(test_module, test_directory, options)
finally:
os.environ["PYTHONPATH"] = python_path
if os.path.exists(test_directory + "/" + test_module + ".py"):
os.remove(test_directory + "/" + test_module + ".py")
os.environ.pop("USE_NINJA")
def test_cpp_extensions_aot_ninja(test_module, test_directory, options):
return _test_cpp_extensions_aot(test_directory, options, use_ninja=True)
def test_cpp_extensions_aot_no_ninja(test_module, test_directory, options):
return _test_cpp_extensions_aot(test_directory, options, use_ninja=False)
def test_distributed(test_module, test_directory, options):
# MPI tests are broken with Python-3.9
mpi_available = subprocess.call(
"command -v mpiexec", shell=True
) == 0 and sys.version_info < (3, 9)
if options.verbose and not mpi_available:
print_to_stderr("MPI not available -- MPI backend tests will be skipped")
config = DISTRIBUTED_TESTS_CONFIG
for backend, env_vars in config.items():
if sys.platform == "win32" and backend != "gloo":
continue
if backend == "mpi" and not mpi_available:
continue
for with_init_file in {True, False}:
if sys.platform == "win32" and not with_init_file:
continue
tmp_dir = tempfile.mkdtemp()
if options.verbose:
init_str = "with {} init_method"
with_init = init_str.format("file" if with_init_file else "env")
print_to_stderr(
f"Running distributed tests for the {backend} backend {with_init}"
)
old_environ = dict(os.environ)
os.environ["TEMP_DIR"] = tmp_dir
os.environ["BACKEND"] = backend
os.environ["INIT_METHOD"] = "env://"
os.environ.update(env_vars)
if with_init_file:
if test_module.name == "test_distributed_spawn":
init_method = f"{FILE_SCHEMA}{tmp_dir}/"
else:
init_method = f"{FILE_SCHEMA}{tmp_dir}/shared_init_file"
os.environ["INIT_METHOD"] = init_method
try:
os.mkdir(os.path.join(tmp_dir, "barrier"))
os.mkdir(os.path.join(tmp_dir, "test_dir"))
if backend == "mpi":
# test mpiexec for --noprefix option
with open(os.devnull, "w") as devnull:
allowrunasroot_opt = (
"--allow-run-as-root"
if subprocess.call(
'mpiexec --allow-run-as-root -n 1 bash -c ""',
shell=True,
stdout=devnull,
stderr=subprocess.STDOUT,
)
== 0
else ""
)
noprefix_opt = (
"--noprefix"
if subprocess.call(
f'mpiexec {allowrunasroot_opt} -n 1 --noprefix bash -c ""',
shell=True,
stdout=devnull,
stderr=subprocess.STDOUT,
)
== 0
else ""
)
mpiexec = ["mpiexec", "-n", "3", noprefix_opt, allowrunasroot_opt]
return_code = run_test(
test_module, test_directory, options, launcher_cmd=mpiexec
)
else:
return_code = run_test(
test_module,
test_directory,
options,
extra_unittest_args=["--subprocess"],
)
if return_code != 0:
return return_code
finally:
shutil.rmtree(tmp_dir)
os.environ.clear()
os.environ.update(old_environ)
return 0
def run_doctests(test_module, test_directory, options):
"""
Assumes the incoming test module is called doctest, and simply executes the
xdoctest runner on the torch library itself.
"""
import pathlib
import xdoctest
pkgpath = pathlib.Path(torch.__file__).parent
exclude_module_list = []
enabled = {
# TODO: expose these options to the user
# For now disable all feature-conditional tests
# 'lapack': 'auto',
# 'cuda': 'auto',
# 'cuda1': 'auto',
# 'qengine': 'auto',
"lapack": 0,
"cuda": 0,
"cuda1": 0,
"qengine": 0,
"autograd_profiler": 0,
"cpp_ext": 0,
"monitor": 0,
"onnx": "auto",
}
# Resolve "auto" based on a test to determine if the feature is available.
if enabled["cuda"] == "auto" and torch.cuda.is_available():
enabled["cuda"] = True
if (
enabled["cuda1"] == "auto"
and torch.cuda.is_available()
and torch.cuda.device_count() > 1
):
enabled["cuda1"] = True
if enabled["lapack"] == "auto" and torch._C.has_lapack:
enabled["lapack"] = True
if enabled["qengine"] == "auto":
try:
# Is there a better check if quantization is enabled?
import torch.ao.nn.quantized as nnq # NOQA: F401
torch.backends.quantized.engine = "qnnpack"
torch.backends.quantized.engine = "fbgemm"
except (ImportError, RuntimeError):
...
else:
enabled["qengine"] = True
if enabled["onnx"] == "auto":
try:
import onnx # NOQA: F401
import onnxruntime # NOQA: F401
import onnxscript # NOQA: F401
except ImportError:
exclude_module_list.append("torch.onnx.*")
enabled["onnx"] = False
else:
enabled["onnx"] = True
# Set doctest environment variables
if enabled["cuda"]:
os.environ["TORCH_DOCTEST_CUDA"] = "1"
if enabled["cuda1"]:
os.environ["TORCH_DOCTEST_CUDA1"] = "1"
if enabled["lapack"]:
os.environ["TORCH_DOCTEST_LAPACK"] = "1"
if enabled["qengine"]:
os.environ["TORCH_DOCTEST_QENGINE"] = "1"
if enabled["autograd_profiler"]:
os.environ["TORCH_DOCTEST_AUTOGRAD_PROFILER"] = "1"
if enabled["cpp_ext"]:
os.environ["TORCH_DOCTEST_CPP_EXT"] = "1"
if enabled["monitor"]:
os.environ["TORCH_DOCTEST_MONITOR"] = "1"
if enabled["onnx"]:
os.environ["TORCH_DOCTEST_ONNX"] = "1"
if 0:
# TODO: could try to enable some of these
os.environ["TORCH_DOCTEST_QUANTIZED_DYNAMIC"] = "1"
os.environ["TORCH_DOCTEST_ANOMALY"] = "1"
os.environ["TORCH_DOCTEST_AUTOGRAD"] = "1"
os.environ["TORCH_DOCTEST_HUB"] = "1"
os.environ["TORCH_DOCTEST_DATALOADER"] = "1"
os.environ["TORCH_DOCTEST_FUTURES"] = "1"
pkgpath = os.path.dirname(torch.__file__)
xdoctest_config = {
"global_exec": r"\n".join(
[
"from torch import nn",
"import torch.nn.functional as F",
"import torch",
]
),
"analysis": "static", # set to "auto" to test doctests in compiled modules
"style": "google",
"options": "+IGNORE_WHITESPACE",
}
xdoctest_verbose = max(1, options.verbose)
run_summary = xdoctest.runner.doctest_module(
os.fspath(pkgpath),
config=xdoctest_config,
verbose=xdoctest_verbose,
command=options.xdoctest_command,
argv=[],
exclude=exclude_module_list,
)
result = 1 if run_summary.get("n_failed", 0) else 0
return result
def sanitize_file_name(file: str):
return file.replace("\\", ".").replace("/", ".").replace(" ", "_")
def handle_log_file(
test: ShardedTest, file_path: str, failed: bool, was_rerun: bool
) -> None:
test = str(test)
with open(file_path, "rb") as f:
full_text = f.read().decode("utf-8", errors="ignore")
if not failed and not was_rerun and "=== RERUNS ===" not in full_text:
# If success + no retries (idk how else to check for test level retries
# other than reparse xml), print only what tests ran, rename the log
# file so it doesn't get printed later, and do not remove logs.
new_file = "test/test-reports/" + sanitize_file_name(
f"{test}_{os.urandom(8).hex()}_.log"
)
os.rename(file_path, REPO_ROOT / new_file)
print_to_stderr(
f"\n{test} was successful, full logs can be found in artifacts with path {new_file}"
)
for line in full_text.splitlines():
if re.search("Running .* items in this shard:", line):
print_to_stderr(line.strip())
print_to_stderr("")
return
# otherwise: print entire file and then remove it
print_to_stderr(f"\nPRINTING LOG FILE of {test} ({file_path})")
print_to_stderr(full_text)
print_to_stderr(f"FINISHED PRINTING LOG FILE of {test} ({file_path})\n")
os.remove(file_path)
def get_pytest_args(
options, stepcurrent_key, is_cpp_test=False, is_distributed_test=False
):
if RERUN_DISABLED_TESTS:
# Distributed tests are too slow, so running them x50 will cause the jobs to timeout after
# 3+ hours. So, let's opt for less number of reruns. We need at least 150 instances of the
# test every 2 weeks to satisfy the Rockset query (15 x 14 = 210). The same logic applies
# to ASAN, which is also slow
count = 15 if is_distributed_test or TEST_WITH_ASAN else 50
# When under rerun-disabled-tests mode, run the same tests multiple times to determine their
# flakiness status. Default to 50 re-runs
rerun_options = ["--flake-finder", f"--flake-runs={count}"]
elif options.continue_through_error:
# If continue through error, don't stop on first failure
rerun_options = ["--reruns=2"]
else:
# When under the normal mode, retry a failed test 2 more times. -x means stop at the first
# failure
rerun_options = ["-x", "--reruns=2"]
pytest_args = [
"-vv",
"-rfEX",
]
if not is_cpp_test:
# C++ tests need to be run with pytest directly, not via python
pytest_args.extend(["-p", "no:xdist", "--use-pytest"])
if not options.continue_through_error and IS_CI:
pytest_args.append(f"--sc={stepcurrent_key}")