common_distributed.py 44 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275
  1. import faulthandler
  2. import logging
  3. import multiprocessing
  4. import os
  5. import queue
  6. import subprocess
  7. import sys
  8. import tempfile
  9. import threading
  10. import time
  11. import traceback
  12. import types
  13. import unittest
  14. from contextlib import contextmanager
  15. from dataclasses import dataclass
  16. from datetime import timedelta
  17. from enum import Enum
  18. from functools import partial, reduce, wraps
  19. from io import StringIO
  20. from typing import Dict, NamedTuple, Optional, Union
  21. from unittest.mock import patch
  22. import torch
  23. import torch._dynamo.test_case
  24. import torch.cuda.nccl
  25. import torch.distributed as c10d
  26. import torch.nn as nn
  27. from torch.testing._internal.common_utils import (
  28. FILE_SCHEMA,
  29. find_free_port,
  30. IS_SANDCASTLE,
  31. retry_on_connect_failures,
  32. sandcastle_skip,
  33. sandcastle_skip_if,
  34. TEST_WITH_ROCM,
  35. TEST_WITH_TSAN,
  36. TestCase,
  37. )
  38. from torch.testing._internal.distributed.multi_threaded_pg import (
  39. _install_threaded_pg,
  40. _uninstall_threaded_pg,
  41. ProcessLocalGroup,
  42. )
  43. logging.basicConfig(level=logging.INFO)
  44. logger = logging.getLogger(__name__)
  45. class TestSkip(NamedTuple):
  46. exit_code: int
  47. message: str
  48. TEST_SKIPS = {
  49. "backend_unavailable": TestSkip(
  50. 72, "Skipped because distributed backend is not available."
  51. ),
  52. "small_worldsize": TestSkip(73, "Skipped due to small world size."),
  53. "odd_worldsize": TestSkip(87, "Skipped due to odd world size."),
  54. "no_cuda": TestSkip(74, "CUDA is not available."),
  55. "multi-gpu-1": TestSkip(75, "Need at least 1 CUDA device"),
  56. "multi-gpu-2": TestSkip(77, "Need at least 2 CUDA devices"),
  57. "multi-gpu-3": TestSkip(80, "Need at least 3 CUDA devices"),
  58. "multi-gpu-4": TestSkip(81, "Need at least 4 CUDA devices"),
  59. "multi-gpu-5": TestSkip(82, "Need at least 5 CUDA devices"),
  60. "multi-gpu-6": TestSkip(83, "Need at least 6 CUDA devices"),
  61. "multi-gpu-7": TestSkip(84, "Need at least 7 CUDA devices"),
  62. "multi-gpu-8": TestSkip(85, "Need at least 8 CUDA devices"),
  63. "nccl": TestSkip(76, "c10d not compiled with NCCL support"),
  64. "skipIfRocm": TestSkip(78, "Test skipped for ROCm"),
  65. "no_peer_access": TestSkip(79, "Test skipped because no GPU peer access"),
  66. "generic": TestSkip(
  67. 86, "Test skipped at subprocess level, look at subprocess log for skip reason"
  68. ),
  69. "importerror": TestSkip(88, "Test skipped due to missing import"),
  70. }
  71. @dataclass
  72. class DistTestCases:
  73. # Backends that do not support a specific collective
  74. skip_collective = {}
  75. skip_collective["allgather_coalesced"] = {"nccl", "mpi", "ucc"}
  76. skip_collective["reduce"] = set()
  77. skip_collective["sendrecv anysource"] = {"nccl", "ucc"}
  78. skip_collective["cpu barrier"] = {"nccl", "ucc"}
  79. # Sets showing that something is implemented
  80. backend_feature = {}
  81. backend_feature["gpu"] = {"nccl", "gloo", "ucc"}
  82. backend_feature["cuda"] = {"nccl", "gloo", "ucc"}
  83. backend_feature["ddp"] = {"nccl", "gloo", "ucc"}
  84. backend_feature["subgroup"] = {"nccl", "gloo", "ucc"}
  85. backend_feature["plugin"] = set()
  86. def skip_if_no_gpu(func):
  87. """Skips if the world size exceeds the number of GPUs, ensuring that if the
  88. test is run, each rank has its own GPU via ``torch.cuda.device(rank)``."""
  89. @wraps(func)
  90. def wrapper(*args, **kwargs):
  91. if not torch.cuda.is_available():
  92. sys.exit(TEST_SKIPS["no_cuda"].exit_code)
  93. world_size = int(os.environ["WORLD_SIZE"])
  94. if torch.cuda.device_count() < world_size:
  95. sys.exit(TEST_SKIPS[f"multi-gpu-{world_size}"].exit_code)
  96. return func(*args, **kwargs)
  97. return wrapper
  98. def skip_if_small_worldsize(func):
  99. @wraps(func)
  100. def wrapper(*args, **kwargs):
  101. if (os.environ["BACKEND"] != "mpi") and int(os.environ["WORLD_SIZE"]) <= 2:
  102. sys.exit(TEST_SKIPS["small_worldsize"].exit_code)
  103. return func(*args, **kwargs)
  104. return wrapper
  105. def skip_if_odd_worldsize(func):
  106. @wraps(func)
  107. def wrapper(*args, **kwargs):
  108. if (os.environ["BACKEND"] != "mpi") and int(os.environ["WORLD_SIZE"]) % 2 == 1:
  109. sys.exit(TEST_SKIPS["odd_worldsize"].exit_code)
  110. return func(*args, **kwargs)
  111. return wrapper
  112. def require_n_gpus_for_nccl_backend(n, backend):
  113. def decorator(func):
  114. @wraps(func)
  115. def wrapper(*args, **kwargs):
  116. if backend == "nccl" and torch.cuda.device_count() < n:
  117. sys.exit(TEST_SKIPS[f"multi-gpu-{n}"].exit_code)
  118. else:
  119. return func(*args, **kwargs)
  120. return wrapper
  121. return decorator
  122. def import_transformers_or_skip():
  123. def decorator(func):
  124. @wraps(func)
  125. def wrapper(*args, **kwargs):
  126. try:
  127. from transformers import ( # noqa: Unused
  128. AutoModelForMaskedLM,
  129. BertConfig,
  130. )
  131. return func(*args, **kwargs)
  132. except ImportError:
  133. sys.exit(TEST_SKIPS["importerror"].exit_code)
  134. return wrapper
  135. return decorator
  136. def skip_if_lt_x_gpu(x):
  137. def decorator(func):
  138. @wraps(func)
  139. def wrapper(*args, **kwargs):
  140. if torch.cuda.is_available() and torch.cuda.device_count() >= x:
  141. return func(*args, **kwargs)
  142. sys.exit(TEST_SKIPS[f"multi-gpu-{x}"].exit_code)
  143. return wrapper
  144. return decorator
  145. # This decorator helps avoiding initializing cuda while testing other backends
  146. def nccl_skip_if_lt_x_gpu(backend, x):
  147. def decorator(func):
  148. @wraps(func)
  149. def wrapper(*args, **kwargs):
  150. if backend != "nccl":
  151. return func(*args, **kwargs)
  152. if torch.cuda.is_available() and torch.cuda.device_count() >= x:
  153. return func(*args, **kwargs)
  154. sys.exit(TEST_SKIPS[f"multi-gpu-{x}"].exit_code)
  155. return wrapper
  156. return decorator
  157. def verify_ddp_error_logged(model_DDP, err_substr):
  158. # Verify error was logged in ddp_logging_data.
  159. ddp_logging_data = model_DDP._get_ddp_logging_data()
  160. assert "iteration" in ddp_logging_data
  161. assert "has_error" in ddp_logging_data
  162. assert "error" in ddp_logging_data
  163. logging_err = ddp_logging_data["error"]
  164. # Remove C++ stacktrace if needed.
  165. actual = (
  166. err_substr
  167. if err_substr.find("\nException raised from ") == -1
  168. else err_substr.split("\nException raised from ")[0]
  169. )
  170. assert (
  171. actual in logging_err
  172. ), f"Did not find expected {actual} in ddp logging data error: {logging_err}"
  173. def with_nccl_blocking_wait(func):
  174. """
  175. Convenience decorator to set/unset NCCL_BLOCKING_WAIT flag. Note that use of
  176. this decorator will override the setting of NCCL_ASYNC_ERROR_HANDLING for
  177. the particular test. After the test, both NCCL_BLOCKING_WAIT and
  178. NCCL_ASYNC_ERROR_HANDLING will be restored to their original values.
  179. """
  180. @wraps(func)
  181. def wrapper(*args, **kwargs):
  182. # Save and unset NCCL_ASYNC_ERROR_HANDLING
  183. try:
  184. cached_nccl_async_error_handling: Union[str, None] = os.environ[
  185. "NCCL_ASYNC_ERROR_HANDLING"
  186. ]
  187. del os.environ["NCCL_ASYNC_ERROR_HANDLING"]
  188. except KeyError:
  189. # NCCL_ASYNC_ERROR_HANDLING was unset
  190. cached_nccl_async_error_handling = None
  191. # Save val of NCCL_BLOCKING_WAIT and set it.
  192. try:
  193. cached_nccl_blocking_wait: Union[str, None] = os.environ[
  194. "NCCL_BLOCKING_WAIT"
  195. ]
  196. except KeyError:
  197. cached_nccl_blocking_wait = None
  198. finally:
  199. os.environ["NCCL_BLOCKING_WAIT"] = "1"
  200. try:
  201. ret = func(*args, **kwargs)
  202. return ret
  203. finally:
  204. # restore old values.
  205. if cached_nccl_async_error_handling is not None:
  206. os.environ[
  207. "NCCL_ASYNC_ERROR_HANDLING"
  208. ] = cached_nccl_async_error_handling
  209. if cached_nccl_blocking_wait is not None:
  210. os.environ["NCCL_BLOCKING_WAIT"] = cached_nccl_blocking_wait
  211. return wrapper
  212. def with_dist_debug_levels(levels):
  213. """
  214. Runs a test for each distributed debug level specified in levels.
  215. """
  216. def decorator(func):
  217. @wraps(func)
  218. def wrapper(*args, **kwargs):
  219. old_level = os.environ.get("TORCH_DISTRIBUTED_DEBUG", None)
  220. for level in levels:
  221. os.environ["TORCH_DISTRIBUTED_DEBUG"] = level
  222. c10d.set_debug_level_from_env()
  223. ret = func(*args, **kwargs)
  224. c10d.barrier()
  225. if old_level is not None:
  226. os.environ["TORCH_DISTRIBUTED_DEBUG"] = old_level
  227. # Only returns test return for last test, but since these are
  228. # unittests the return value is not really used and earlier tests
  229. # would've raised had they failed.
  230. return ret
  231. return wrapper
  232. return decorator
  233. def requires_gloo():
  234. return sandcastle_skip_if(
  235. not c10d.is_gloo_available(),
  236. "c10d was not compiled with the Gloo backend",
  237. )
  238. def requires_nccl_version(version, msg):
  239. if not c10d.is_nccl_available():
  240. return sandcastle_skip(
  241. "c10d was not compiled with the NCCL backend",
  242. )
  243. else:
  244. return sandcastle_skip_if(
  245. torch.cuda.nccl.version() < version,
  246. "Requires NCCL version greater than or equal to: {}, found: {}, reason: {}".format(
  247. version, torch.cuda.nccl.version(), msg
  248. ),
  249. )
  250. def requires_nccl():
  251. return sandcastle_skip_if(
  252. not c10d.is_nccl_available(),
  253. "c10d was not compiled with the NCCL backend",
  254. )
  255. def requires_ucc():
  256. return sandcastle_skip_if(
  257. not c10d.is_ucc_available(),
  258. "c10d was not compiled with the UCC backend",
  259. )
  260. def requires_mpi():
  261. return sandcastle_skip_if(
  262. not c10d.is_mpi_available(),
  263. "c10d was not compiled with the MPI backend",
  264. )
  265. def skip_if_rocm(func):
  266. """Skips a test for ROCm"""
  267. func.skip_if_rocm = True
  268. @wraps(func)
  269. def wrapper(*args, **kwargs):
  270. if not TEST_WITH_ROCM:
  271. return func(*args, **kwargs)
  272. sys.exit(TEST_SKIPS["skipIfRocm"].exit_code)
  273. return wrapper
  274. def skip_if_win32():
  275. return sandcastle_skip_if(
  276. sys.platform == "win32",
  277. "This unit test case is not supported on Windows platform",
  278. )
  279. @retry_on_connect_failures
  280. def create_tcp_store(
  281. addr="localhost",
  282. world_size=1,
  283. is_master=True,
  284. timeout=timedelta(minutes=5),
  285. wait_for_workers=True,
  286. jit_class=False,
  287. ):
  288. """
  289. Creates a TCP store. Retries if the chosen port is already in use.
  290. """
  291. port = find_free_port()
  292. if jit_class:
  293. timeout_millisecond = int(timeout / timedelta(milliseconds=1))
  294. return torch.classes.dist_c10d.TCPStore(
  295. addr, port, world_size, is_master, timeout_millisecond
  296. )
  297. else:
  298. return c10d.TCPStore(
  299. addr, port, world_size, is_master, wait_for_workers=wait_for_workers
  300. )
  301. if TEST_WITH_TSAN:
  302. # TSAN runs much slower.
  303. TIMEOUT_DEFAULT = 500
  304. else:
  305. TIMEOUT_DEFAULT = int(os.getenv('DISTRIBUTED_TESTS_DEFAULT_TIMEOUT', '300'))
  306. TIMEOUT_OVERRIDE = {"test_ddp_uneven_inputs": 400}
  307. # https://github.com/pytorch/pytorch/issues/75665
  308. if TEST_WITH_ROCM:
  309. TIMEOUT_OVERRIDE["test_join_kwargs"] = 200
  310. def create_device(interface=None):
  311. if sys.platform == "win32" or interface is None:
  312. return c10d.ProcessGroupGloo.create_device(hostname="127.0.0.1")
  313. else:
  314. return c10d.ProcessGroupGloo.create_device(interface=interface)
  315. def get_timeout(test_id) -> int:
  316. return TIMEOUT_OVERRIDE.get(test_id.split(".")[-1], TIMEOUT_DEFAULT)
  317. @contextmanager
  318. def captured_output():
  319. new_out, new_err = StringIO(), StringIO()
  320. old_out, old_err = sys.stdout, sys.stderr
  321. try:
  322. sys.stdout, sys.stderr = new_out, new_err
  323. yield sys.stdout, sys.stderr
  324. finally:
  325. sys.stdout, sys.stderr = old_out, old_err
  326. def simple_sparse_reduce_tests(rank: int, world_size: int, num_inputs: int = 1):
  327. """
  328. Generate a number of basic test cases for sparse reduction.
  329. These cover tensors with a varying number of sparse dimensions and a varying
  330. number of dense dimensions. The only reduction operation we support is sum.
  331. """
  332. def generate(rank: int, world_size: int, sparse_dims: int = 1, dense_dims: int = 0):
  333. # First sparse dimension is [0..rank].
  334. # Subsequent dimensions are always 0, so we know there is
  335. # a non-empty intersection between any two sparse tensors.
  336. indices = torch.reshape(torch.arange(rank + 1), (1, rank + 1))
  337. shape = [world_size] + [2 for _ in range(dense_dims)]
  338. for _ in range(sparse_dims - 1):
  339. indices = torch.cat((indices, torch.zeros(1, rank + 1)))
  340. shape.append(world_size)
  341. values = torch.ones([rank + 1] + [2 for _ in range(dense_dims)])
  342. return torch.sparse_coo_tensor(indices, values, shape)
  343. def compute_sum(fn, world_size: int):
  344. return reduce(
  345. lambda a, b: a + b, [fn(rank, world_size) for rank in range(world_size)]
  346. )
  347. return [
  348. (
  349. [
  350. fn(num_inputs * rank + i, num_inputs * world_size)
  351. for i in range(num_inputs)
  352. ],
  353. [compute_sum(fn, num_inputs * world_size) for i in range(num_inputs)],
  354. )
  355. for fn in [
  356. partial(generate, sparse_dims=1),
  357. partial(generate, sparse_dims=2),
  358. partial(generate, sparse_dims=3),
  359. partial(generate, dense_dims=1),
  360. partial(generate, dense_dims=2),
  361. partial(generate, dense_dims=3),
  362. ]
  363. ]
  364. # HELPER FOR MULTIGPU TESTS
  365. def init_multigpu_helper(world_size: int, backend: str):
  366. """Multigpu tests are designed to simulate the multi nodes with multi
  367. GPUs on each node. Nccl backend requires equal #GPUs in each process.
  368. On a single node, all visible GPUs are evenly
  369. divided to subsets, each process only uses a subset.
  370. """
  371. nGPUs = torch.cuda.device_count()
  372. visible_devices = range(nGPUs)
  373. if backend == "nccl":
  374. # This is a hack for a known NCCL issue using multiprocess
  375. # in conjunction with multiple threads to manage different GPUs which
  376. # may cause ncclCommInitRank to fail.
  377. # http://docs.nvidia.com/deeplearning/sdk/nccl-release-notes/rel_2.1.4.html#rel_2.1.4
  378. # It slows down the performance of collective operations.
  379. # Without this setting NCCL might throw unhandled error.
  380. os.environ["NCCL_MAX_NRINGS"] = "1"
  381. # If rank is less than or equal to number of available GPU's
  382. # then each rank can be mapped to corresponding GPU.
  383. nGPUs_per_process = 1
  384. if world_size > nGPUs:
  385. nGPUs_per_process = nGPUs // world_size
  386. rank_to_GPU = {
  387. i: list(visible_devices[i * nGPUs_per_process : (i + 1) * nGPUs_per_process])
  388. for i in range(world_size)
  389. }
  390. return rank_to_GPU
  391. tmp_dir: Optional[tempfile.TemporaryDirectory] = None
  392. def initialize_temp_directories(init_method: Optional[str] = None) -> None:
  393. global tmp_dir
  394. tmp_dir = tempfile.TemporaryDirectory()
  395. os.environ["TEMP_DIR"] = tmp_dir.name
  396. os.mkdir(os.path.join(tmp_dir.name, "barrier"))
  397. os.mkdir(os.path.join(tmp_dir.name, "test_dir"))
  398. init_dir_path = os.path.join(tmp_dir.name, "init_dir")
  399. os.mkdir(init_dir_path)
  400. # Set init method if specified.
  401. if init_method is not None:
  402. os.environ["INIT_METHOD"] = init_method
  403. else:
  404. os.environ["INIT_METHOD"] = FILE_SCHEMA + os.path.join(
  405. init_dir_path, "shared_init_file"
  406. )
  407. def cleanup_temp_dir() -> None:
  408. if tmp_dir is not None:
  409. tmp_dir.cleanup()
  410. # Most tests operate with this worldsize
  411. DEFAULT_WORLD_SIZE = 4
  412. # [How does MultiProcessTestCase work?]
  413. # Each MultiProcessTestCase instance uses 1 + `world_size()` processes, by
  414. # default `world_size()` returns 4. Let's take `test_rpc_spawn.py` as an
  415. # example which inherits from this class. Its `Setup()` methods calls into
  416. # `MultiProcessTestCase._spawn_processes()` which spawns `world_size()`
  417. # subprocesses. During the spawn, the main process passes the test name to
  418. # subprocesses, and the name is acquired from self.id(). The subprocesses
  419. # then use the provided test function name to retrieve the function attribute
  420. # from the test instance and run it. The main process simply waits for all
  421. # subprocesses to join.
  422. class MultiProcessTestCase(TestCase):
  423. MAIN_PROCESS_RANK = -1
  424. # This exit code is used to indicate that the test code had an error and
  425. # exited abnormally. There are certain tests that might use sys.exit() to
  426. # simulate failures and in those cases, we can't have an exit code of 0,
  427. # but we still want to ensure we didn't run into any other errors.
  428. TEST_ERROR_EXIT_CODE = 10
  429. # do not early terminate for distributed tests.
  430. def _should_stop_test_suite(self) -> bool:
  431. return False
  432. @property
  433. def world_size(self) -> int:
  434. return DEFAULT_WORLD_SIZE
  435. def join_or_run(self, fn):
  436. @wraps(fn)
  437. def wrapper(self):
  438. if self.rank == self.MAIN_PROCESS_RANK:
  439. self._join_processes(fn)
  440. else:
  441. fn()
  442. return types.MethodType(wrapper, self)
  443. # The main process spawns N subprocesses that run the test.
  444. # Constructor patches current instance test method to
  445. # assume the role of the main process and join its subprocesses,
  446. # or run the underlying test function.
  447. def __init__(self, method_name: str = "runTest") -> None:
  448. super().__init__(method_name)
  449. fn = getattr(self, method_name)
  450. setattr(self, method_name, self.join_or_run(fn))
  451. def setUp(self) -> None:
  452. super().setUp()
  453. self.skip_return_code_checks = [] # type: ignore[var-annotated]
  454. self.processes = [] # type: ignore[var-annotated]
  455. self.rank = self.MAIN_PROCESS_RANK
  456. self.file_name = tempfile.NamedTemporaryFile(delete=False).name
  457. # pid to pipe consisting of error message from process.
  458. self.pid_to_pipe = {} # type: ignore[var-annotated]
  459. def tearDown(self) -> None:
  460. super().tearDown()
  461. for p in self.processes:
  462. p.terminate()
  463. # Each Process instance holds a few open file descriptors. The unittest
  464. # runner creates a new TestCase instance for each test method and keeps
  465. # it alive until the end of the entire suite. We must thus reset the
  466. # processes to prevent an effective file descriptor leak.
  467. self.processes = []
  468. def _current_test_name(self) -> str:
  469. # self.id() == e.g. '__main__.TestDistributed.TestAdditive.test_get_rank'
  470. return self.id().split(".")[-1]
  471. def _start_processes(self, proc) -> None:
  472. self.processes = []
  473. for rank in range(int(self.world_size)):
  474. parent_conn, child_conn = torch.multiprocessing.Pipe()
  475. process = proc(
  476. target=self.__class__._run,
  477. name="process " + str(rank),
  478. args=(rank, self._current_test_name(), self.file_name, child_conn),
  479. )
  480. process.start()
  481. logger.info(f"Started process {rank} with pid {process.pid}")
  482. self.pid_to_pipe[process.pid] = parent_conn
  483. self.processes.append(process)
  484. def _spawn_processes(self) -> None:
  485. proc = torch.multiprocessing.get_context("spawn").Process
  486. self._start_processes(proc)
  487. class Event(Enum):
  488. GET_TRACEBACK = 1
  489. @staticmethod
  490. def _event_listener(parent_pipe, signal_pipe, rank: int):
  491. logger.info(f"Starting event listener thread for rank {rank}")
  492. while True:
  493. ready_pipes = multiprocessing.connection.wait([parent_pipe, signal_pipe])
  494. if parent_pipe in ready_pipes:
  495. if parent_pipe.closed:
  496. logger.info(
  497. f"Pipe closed for process {rank}, stopping event listener thread"
  498. )
  499. return
  500. event = parent_pipe.recv()
  501. logger.info(f"Received event {event} on process {rank}")
  502. if event == MultiProcessTestCase.Event.GET_TRACEBACK:
  503. # Return traceback to the parent process.
  504. with tempfile.NamedTemporaryFile(mode="r+") as tmp_file:
  505. faulthandler.dump_traceback(tmp_file)
  506. # Flush buffers and seek to read from the beginning
  507. tmp_file.flush()
  508. tmp_file.seek(0)
  509. parent_pipe.send(tmp_file.read())
  510. logger.info(f"Process {rank} sent traceback")
  511. if signal_pipe in ready_pipes:
  512. return
  513. @classmethod
  514. def _run(cls, rank: int, test_name: str, file_name: str, parent_pipe) -> None:
  515. # Enable DDP + ReplicatedTensor
  516. from torch.nn.parallel._replicated_tensor_ddp_utils import (
  517. _set_ddp_with_replicated_tensor,
  518. )
  519. _set_ddp_with_replicated_tensor(True)
  520. self = cls(test_name)
  521. self.rank = rank
  522. self.file_name = file_name
  523. self.run_test(test_name, parent_pipe)
  524. def run_test(self, test_name: str, parent_pipe) -> None:
  525. # Start event listener thread.
  526. signal_recv_pipe, signal_send_pipe = torch.multiprocessing.Pipe(duplex=False)
  527. event_listener_thread = threading.Thread(
  528. target=MultiProcessTestCase._event_listener,
  529. args=(parent_pipe, signal_recv_pipe, self.rank),
  530. daemon=True,
  531. )
  532. event_listener_thread.start()
  533. if sys.platform != "win32" and sys.platform != "darwin":
  534. # Register signal handler to dump stack traces on FATALs.
  535. # Windows and MacOS do not support the signal handlers.
  536. torch._C._set_print_stack_traces_on_fatal_signal(True)
  537. # Show full C++ stacktraces when a Python error originating from C++ is raised.
  538. os.environ["TORCH_SHOW_CPP_STACKTRACES"] = "1"
  539. # self.id() == e.g. '__main__.TestDistributed.test_get_rank'
  540. # We're retrieving a corresponding test and executing it.
  541. try:
  542. getattr(self, test_name)()
  543. except unittest.SkipTest as se:
  544. logger.info(
  545. f"Process {self.rank} skipping test {test_name} for following reason: {str(se)}"
  546. )
  547. sys.exit(TEST_SKIPS["generic"].exit_code)
  548. except Exception as e:
  549. logger.error(
  550. f"Caught exception: \n{traceback.format_exc()} exiting "
  551. f"process {self.rank} with exit code: {MultiProcessTestCase.TEST_ERROR_EXIT_CODE}"
  552. )
  553. # Send error to parent process.
  554. parent_pipe.send(traceback.format_exc())
  555. sys.exit(MultiProcessTestCase.TEST_ERROR_EXIT_CODE)
  556. finally:
  557. if signal_send_pipe is not None:
  558. signal_send_pipe.send(None)
  559. assert event_listener_thread is not None
  560. event_listener_thread.join()
  561. # Close pipe after done with test.
  562. parent_pipe.close()
  563. def _get_timedout_process_traceback(self) -> None:
  564. pipes = []
  565. for i, process in enumerate(self.processes):
  566. if process.exitcode is None:
  567. pipe = self.pid_to_pipe[process.pid]
  568. try:
  569. pipe.send(MultiProcessTestCase.Event.GET_TRACEBACK)
  570. pipes.append((i, pipe))
  571. except ConnectionError as e:
  572. logger.error(
  573. f"Encountered error while trying to get traceback for process {i}: {e}"
  574. )
  575. # Wait for results.
  576. for rank, pipe in pipes:
  577. try:
  578. # Wait for traceback
  579. if pipe.poll(5):
  580. if pipe.closed:
  581. logger.info(
  582. f"Pipe closed for process {rank}, cannot retrieve traceback"
  583. )
  584. continue
  585. traceback = pipe.recv()
  586. logger.error(
  587. f"Process {rank} timed out with traceback: \n\n{traceback}"
  588. )
  589. else:
  590. logger.error(
  591. f"Could not retrieve traceback for timed out process: {rank}"
  592. )
  593. except ConnectionError as e:
  594. logger.error(
  595. f"Encountered error while trying to get traceback for process {rank}: {e}"
  596. )
  597. def _join_processes(self, fn) -> None:
  598. timeout = get_timeout(self.id())
  599. start_time = time.time()
  600. subprocess_error = False
  601. try:
  602. while True:
  603. # check to see if any subprocess exited with an error early.
  604. for (i, p) in enumerate(self.processes):
  605. # This is the exit code processes exit with if they
  606. # encountered an exception.
  607. if p.exitcode == MultiProcessTestCase.TEST_ERROR_EXIT_CODE:
  608. print(
  609. f"Process {i} terminated with exit code {p.exitcode}, terminating remaining processes."
  610. )
  611. active_children = torch.multiprocessing.active_children()
  612. for ac in active_children:
  613. ac.terminate()
  614. subprocess_error = True
  615. break
  616. if subprocess_error:
  617. break
  618. # All processes have joined cleanly if they all a valid exitcode
  619. if all([p.exitcode is not None for p in self.processes]):
  620. break
  621. # Check if we should time out the test. If so, we terminate each process.
  622. elapsed = time.time() - start_time
  623. if elapsed > timeout:
  624. self._get_timedout_process_traceback()
  625. print(
  626. f"Timing out after {timeout} seconds and killing subprocesses."
  627. )
  628. for p in self.processes:
  629. p.terminate()
  630. break
  631. # Sleep to avoid excessive busy polling.
  632. time.sleep(0.1)
  633. elapsed_time = time.time() - start_time
  634. if fn in self.skip_return_code_checks:
  635. self._check_no_test_errors(elapsed_time)
  636. else:
  637. self._check_return_codes(elapsed_time)
  638. finally:
  639. # Close all pipes
  640. for pid, pipe in self.pid_to_pipe.items():
  641. pipe.close()
  642. def _check_no_test_errors(self, elapsed_time) -> None:
  643. """
  644. Checks that we didn't have any errors thrown in the child processes.
  645. """
  646. for i, p in enumerate(self.processes):
  647. if p.exitcode is None:
  648. raise RuntimeError(
  649. "Process {} timed out after {} seconds".format(i, elapsed_time)
  650. )
  651. self.assertNotEqual(self.TEST_ERROR_EXIT_CODE, p.exitcode)
  652. def _check_return_codes(self, elapsed_time) -> None:
  653. """
  654. Checks that the return codes of all spawned processes match, and skips
  655. tests if they returned a return code indicating a skipping condition.
  656. """
  657. first_process = self.processes[0]
  658. # first, we check if there are errors in actual processes
  659. # (via TEST_ERROR_EXIT CODE), and raise an exception for those.
  660. # the reason we do this is to attempt to raise a more helpful error
  661. # message than "Process x terminated/timed out"
  662. # TODO: we should pipe the exception of the failed subprocess here.
  663. # Currently, the actual exception is displayed as a logging output.
  664. errored_processes = [
  665. (i, p)
  666. for i, p in enumerate(self.processes)
  667. if p.exitcode == MultiProcessTestCase.TEST_ERROR_EXIT_CODE
  668. ]
  669. if errored_processes:
  670. error = ""
  671. for i, process in errored_processes:
  672. # Get error from pipe.
  673. error_message = self.pid_to_pipe[process.pid].recv()
  674. error += (
  675. "Process {} exited with error code {} and exception:\n{}\n".format(
  676. i, MultiProcessTestCase.TEST_ERROR_EXIT_CODE, error_message
  677. )
  678. )
  679. raise RuntimeError(error)
  680. # If no process exited uncleanly, we check for timeouts, and then ensure
  681. # each process exited cleanly.
  682. for i, p in enumerate(self.processes):
  683. if p.exitcode is None:
  684. raise RuntimeError(
  685. "Process {} terminated or timed out after {} seconds".format(
  686. i, elapsed_time
  687. )
  688. )
  689. self.assertEqual(
  690. p.exitcode,
  691. first_process.exitcode,
  692. msg="Expect process {} exit code to match Process 0 exit code of {}, but got {}".format(
  693. i, first_process.exitcode, p.exitcode
  694. ),
  695. )
  696. for skip in TEST_SKIPS.values():
  697. if first_process.exitcode == skip.exit_code:
  698. if IS_SANDCASTLE:
  699. # Don't use unittest.skip to skip the test on sandcastle
  700. # since it creates tasks for skipped tests assuming there
  701. # is some follow-up needed. Instead just "pass" the test
  702. # with an appropriate message.
  703. logger.info(
  704. f"Skipping {self.id()} on sandcastle for the following reason: {skip.message}"
  705. )
  706. return
  707. else:
  708. raise unittest.SkipTest(skip.message)
  709. self.assertEqual(
  710. first_process.exitcode,
  711. 0,
  712. msg="Expected zero exit code but got {} for pid: {}".format(
  713. first_process.exitcode, first_process.pid
  714. ),
  715. )
  716. @property
  717. def is_master(self) -> bool:
  718. return self.rank == 0
  719. # Cannot use functools.cache as it requires python 3.9
  720. EFA_PROBE_RESULT = None
  721. def has_efa() -> bool:
  722. """
  723. If shell command `fi_info -p efa -t FI_EP_RDM` returns exit code 0 then we assume that the machine has
  724. Libfabric EFA interfaces and EFA software components installed,
  725. see https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/efa-start.html.
  726. """
  727. global EFA_PROBE_RESULT
  728. if EFA_PROBE_RESULT is not None:
  729. return EFA_PROBE_RESULT
  730. try:
  731. EFA_PROBE_RESULT = (
  732. subprocess.run(["fi_info", "-p", "efa", "-t", "FI_EP_RDM"]).returncode == 0
  733. )
  734. except FileNotFoundError:
  735. EFA_PROBE_RESULT = False
  736. return EFA_PROBE_RESULT
  737. def tp_transports():
  738. """
  739. If the machine has Libfabric EFA interfaces and EFA software components installed it may cause
  740. 'RuntimeError: In operator() at tensorpipe/common/ibv.h:172 "": Operation not supported' if tensorpipe
  741. uses InfiniBand transport, so we exclude it from tensorpipe transports,
  742. see https://github.com/pytorch/pytorch/issues/73885 and https://github.com/pytorch/pytorch/issues/65022
  743. """
  744. return ["shm", "uv"] if has_efa() else None
  745. def spawn_threads_and_init_comms(
  746. func=None, timeout=TIMEOUT_DEFAULT, world_size=DEFAULT_WORLD_SIZE
  747. ):
  748. """
  749. Wrapper to use with a test method
  750. """
  751. if func is None:
  752. return partial(
  753. spawn_threads_and_init_comms, timeout=timeout, world_size=world_size
  754. )
  755. def _run_test_method_with_multi_threads(world_size, callback):
  756. world = _install_threaded_pg()
  757. global_store = c10d.HashStore()
  758. def world_is_valid():
  759. return world == c10d.distributed_c10d._world
  760. def worker(rank, world_pg, store):
  761. c10d.init_process_group(
  762. backend="threaded", rank=rank, world_size=world_size, store=store
  763. )
  764. try:
  765. callback()
  766. except BaseException as ex:
  767. # Exceptions are handled in MultiThreadedTestCase
  768. MultiThreadedTestCase.exception_queue.put((rank, sys.exc_info()))
  769. ProcessLocalGroup.exception_handle(ex) # trigger _terminate event and awaken worker threads
  770. finally:
  771. if world_is_valid():
  772. c10d.destroy_process_group()
  773. threads = []
  774. for rank in range(world_size):
  775. t = threading.Thread(target=worker, args=(rank, world, global_store))
  776. t.start()
  777. threads.append(t)
  778. return threads
  779. @wraps(func)
  780. def wrapper(self, *args, **kwargs):
  781. # TODO: get test name from kwargs
  782. threads = _run_test_method_with_multi_threads(world_size, lambda: func(self, *args, **kwargs))
  783. # join and error handling
  784. MultiThreadedTestCase._join_threads(threads, func)
  785. return wrapper
  786. class MultiThreadedTestCase(TestCase):
  787. """
  788. Test runner that runs all tests with the in-proc process group using
  789. multiple threads with the threaded process group.
  790. Each test spawns world_size threads and run the test method in each thread.
  791. Difference from regular MultiProcess test runner:
  792. Must explicitly defines SetUp and call self._spawn_threads() to run the tests.
  793. Cannot use setUp / tearDown (must use perThreadSetup / perThreadShutdown)
  794. to set up / tear down each thread when running each test.
  795. No global state possible
  796. How bad of a limitation is this?
  797. """
  798. exception_queue = queue.Queue()
  799. MAIN_THREAD_RANK = -1
  800. def join_or_run(self, fn):
  801. @wraps(fn)
  802. def wrapper(self):
  803. if self.rank == self.MAIN_THREAD_RANK:
  804. self._join_threads(self.threads, fn)
  805. else:
  806. fn()
  807. return types.MethodType(wrapper, self)
  808. def __init__(self, method_name: str = "runTest") -> None:
  809. super().__init__(method_name)
  810. test_fn = getattr(self, method_name, None)
  811. setattr(self, method_name, self.join_or_run(test_fn))
  812. def perThreadSetUp(self):
  813. # super().setUp() # TestCase.setUp() calls torch.manual_seed()
  814. pass
  815. def perThreadTearDown(self):
  816. pass
  817. def setUp(self) -> None:
  818. """
  819. setUp only set up things in the main thread, if you want to configure things
  820. in the spawned threads, use perThreadSetUp
  821. """
  822. super().setUp()
  823. self.rank = self.MAIN_THREAD_RANK
  824. self.threads = []
  825. # Show full C++ stacktraces when a Python error originating from C++ is raised.
  826. os.environ["TORCH_SHOW_CPP_STACKTRACES"] = "1"
  827. def tearDown(self):
  828. """
  829. tearDown only set up things in the main thread, if you want to configure things
  830. in the spawned threads, use perThreadTearDown
  831. """
  832. super().tearDown()
  833. self.threads = []
  834. def _spawn_threads(self):
  835. """
  836. class method to spawn threads and run test, use this method in the SetUp of your TestCase
  837. """
  838. test_name = self._current_test_name
  839. # for each test case, we need to create thread local world, and a global store
  840. world = _install_threaded_pg()
  841. self.__class__.global_store = c10d.HashStore()
  842. def world_is_valid():
  843. return world == c10d.distributed_c10d._world
  844. if not world_is_valid():
  845. raise RuntimeError("Invalid world")
  846. for rank in range(self.world_size):
  847. t = threading.Thread(target=self.__class__._run, args=(test_name, rank, self.world_size))
  848. t.start()
  849. self.threads.append(t)
  850. @classmethod
  851. def _run(cls, test_name, rank, world_size):
  852. self = cls(test_name)
  853. self.rank = rank
  854. # precision/rel_tol is a thread-local setting since it may be overridden per test, need to make
  855. # every thread have the same value. This would be relevant when we use op db tests, where it
  856. # needs those states to be set i.e. using instantiate_device_type_tests()
  857. # TODO: figure out a better way to do this
  858. if hasattr(self, "_tls"):
  859. self._tls = threading.local()
  860. self._tls.precision = TestCase._precision
  861. self._tls.rel_tol = TestCase._rel_tol
  862. self.run_test_with_threaded_pg(test_name, rank, world_size)
  863. def run_test_with_threaded_pg(self, test_name, rank, world_size):
  864. """
  865. Run the current test associated with `test_name` using the threaded process group.
  866. """
  867. c10d.init_process_group(
  868. backend="threaded", rank=rank, world_size=world_size, store=self.__class__.global_store
  869. )
  870. self.perThreadSetUp()
  871. try:
  872. getattr(self, test_name)()
  873. except BaseException as ex:
  874. self.exception_queue.put((rank, sys.exc_info()))
  875. ProcessLocalGroup.exception_handle(ex) # trigger _terminate event and awaken worker threads
  876. finally:
  877. c10d.destroy_process_group()
  878. self.perThreadTearDown()
  879. @classmethod
  880. def _join_threads(cls, threads, fn):
  881. timeout = TIMEOUT_DEFAULT
  882. try:
  883. for idx, thread in enumerate(threads):
  884. thread.join(max(0, timeout))
  885. if thread.is_alive():
  886. MultiThreadedTestCase.exception_queue.put(
  887. (
  888. idx,
  889. (
  890. TimeoutError,
  891. TimeoutError(
  892. f"Rank failed to join in under {timeout} seconds"
  893. ),
  894. None,
  895. ),
  896. )
  897. )
  898. ProcessLocalGroup.reset()
  899. failed_ranks = []
  900. while not cls.exception_queue.empty():
  901. failure = cls.exception_queue.get()
  902. failed_ranks.append(failure)
  903. finally:
  904. _uninstall_threaded_pg()
  905. cls._check_return_codes(failed_ranks, timeout, fn)
  906. @classmethod
  907. def _check_return_codes(cls, failed_ranks, timeout, fn):
  908. # Print based on exceptions raised from threads
  909. # SkipTest: print info for each thread
  910. # TimeoutError: raise RuntimeError for any timed out thread
  911. # Normal Exception: print error for each thread that raises exception
  912. # and raise a RuntimeError
  913. error_msg = ""
  914. skip_code = -1
  915. for rank, exc_info in failed_ranks:
  916. exc = exc_info[1]
  917. if isinstance(exc, unittest.SkipTest):
  918. logger.info(
  919. f"Thread {rank} skipping test {fn} for following reason: {str(exc)}"
  920. )
  921. if skip_code < 0:
  922. skip_code = TEST_SKIPS["generic"].exit_code
  923. elif isinstance(exc, TimeoutError):
  924. msg = "Thread {} terminated or timed out after {} seconds\n".format(
  925. rank, timeout
  926. )
  927. logger.error(msg)
  928. raise RuntimeError(msg)
  929. elif isinstance(exc, Exception):
  930. msg = "".join(traceback.format_exception(*exc_info))
  931. logger.error(
  932. f"Caught exception: \n{msg} exiting thread {rank}"
  933. )
  934. error_msg += (
  935. "Thread {} exited with exception:\n{}\n".format(rank, msg)
  936. )
  937. elif isinstance(exc, SystemExit):
  938. if type(exc.code) == int and skip_code < 0:
  939. skip_code = exc.code
  940. # check exceptions
  941. if len(error_msg) > 0:
  942. raise RuntimeError(error_msg)
  943. # check skip
  944. if skip_code > 0:
  945. for skip in TEST_SKIPS.values():
  946. if skip_code == skip.exit_code:
  947. if IS_SANDCASTLE:
  948. # "pass" the test with an appropriate message.
  949. logger.info(
  950. f"Skipping {fn} on sandcastle for the following reason: {skip.message}"
  951. )
  952. return
  953. else:
  954. raise unittest.SkipTest(skip.message)
  955. @property
  956. def world_size(self) -> int:
  957. return DEFAULT_WORLD_SIZE
  958. @property
  959. def _current_test_name(self) -> str:
  960. # self.id() == e.g. '__main__.TestDistributed.TestAdditive.test_get_rank'
  961. return self.id().split(".")[-1]
  962. def assertEqualOnRank(self, x, y, msg=None, *, rank=0):
  963. """
  964. The reason why we have this util function instead of
  965. self.assertEqual is all threads are sharing one CPU RNG
  966. so the assertion result is only reliable on rank 0
  967. """
  968. if self.rank == rank:
  969. self.assertEqual(x, y, msg)
  970. def assertNotEqualOnRank(self, x, y, msg=None, *, rank=0):
  971. if self.rank == rank:
  972. self.assertNotEqual(x, y)
  973. class SaveForwardInputsModule(nn.Module):
  974. def __init__(
  975. self,
  976. forward_inputs: Dict[nn.Module, torch.Tensor],
  977. cast_forward_inputs: bool,
  978. ) -> None:
  979. super().__init__()
  980. self.l = nn.Linear(100, 100)
  981. self.forward_inputs = forward_inputs
  982. self.cast_forward_inputs = cast_forward_inputs
  983. def forward(self, x: torch.Tensor) -> torch.Tensor:
  984. self.forward_inputs[self] = x
  985. return self.l(x.to(self.l.weight.dtype) if self.cast_forward_inputs else x)
  986. class SaveForwardInputsModel(nn.Module):
  987. def __init__(
  988. self,
  989. forward_inputs: Dict[nn.Module, torch.Tensor],
  990. cast_forward_inputs: bool,
  991. ) -> None:
  992. super().__init__()
  993. self.c1 = SaveForwardInputsModule(forward_inputs, cast_forward_inputs)
  994. self.c2 = SaveForwardInputsModule(forward_inputs, cast_forward_inputs)
  995. self.forward_inputs = forward_inputs
  996. def forward(self, x: torch.Tensor) -> torch.Tensor:
  997. self.forward_inputs[self] = x
  998. return self.c2(self.c1(x))
  999. @contextmanager
  1000. def _dynamo_dist_per_rank_init(rank, world_size, init_pg=True):
  1001. # To avoid multiple inheritance from _dynamo.test_case.TestCase and MultiProcessTestCase,
  1002. # Just manually implement the most important part of the dynamo behavior to reset/clear.
  1003. torch.cuda.set_device(rank)
  1004. os.environ['MASTER_ADDR'] = 'localhost'
  1005. os.environ['MASTER_PORT'] = '6789'
  1006. if init_pg:
  1007. c10d.init_process_group("nccl", rank=rank, world_size=world_size)
  1008. torch._dynamo.reset()
  1009. torch._dynamo.utils.counters.clear()
  1010. yield
  1011. torch._dynamo.reset()
  1012. torch._dynamo.utils.counters.clear()
  1013. if init_pg:
  1014. c10d.destroy_process_group()
  1015. class DynamoDistributedSingleProcTestCase(torch._dynamo.test_case.TestCase):
  1016. """
  1017. Test harness for single-process dynamo distributed tests,
  1018. initializes dist process group.
  1019. Prefer this for simple tests, as it's easier to debug.
  1020. """
  1021. @classmethod
  1022. def setUpClass(cls):
  1023. super().setUpClass()
  1024. # _exit_stack is set up in TestCase
  1025. cls._exit_stack.enter_context(
  1026. patch.dict(
  1027. os.environ,
  1028. {
  1029. "MASTER_ADDR": "localhost",
  1030. "MASTER_PORT": "12355",
  1031. },
  1032. )
  1033. )
  1034. cls.rank = 0
  1035. cls.device = f"cuda:{cls.rank}"
  1036. cls.device_ids = None if "cuda" in cls.device else [cls.rank]
  1037. c10d.init_process_group("nccl", rank=cls.rank, world_size=1)
  1038. @classmethod
  1039. def tearDownClass(cls):
  1040. c10d.destroy_process_group()
  1041. super().tearDownClass()
  1042. class DynamoDistributedMultiProcTestCase(MultiProcessTestCase):
  1043. """
  1044. Use this for tests that actually run on multiple GPUs.
  1045. Decorate tests with @skip_if_lt_x_gpu(ngpu)
  1046. Note: MultiProcTestCase spawns processes per test and is slow.
  1047. Prefer MultiThreadedTestCase for most tests. Perhaps use this one
  1048. sparingly for integration tests.
  1049. """
  1050. def setUp(self):
  1051. super().setUp()
  1052. self._spawn_processes()
  1053. def tearDown(self):
  1054. super().tearDown()
  1055. try:
  1056. os.remove(self.file_name)
  1057. except OSError:
  1058. pass
  1059. @property
  1060. def world_size(self) -> int:
  1061. return torch.cuda.device_count()
  1062. @classmethod
  1063. def _run(cls, rank: int, test_name: str, file_name: str, parent_pipe) -> None:
  1064. # Don't enable DDP + ReplicatedTensor, as that breaks Dynamo+DDP
  1065. # TODO(whc) why is ReplicatedTensor defaulted=True in MultiProcessTestCase, and should we support it?
  1066. # from torch.nn.parallel._replicated_tensor_ddp_utils import _set_ddp_with_replicated_tensor
  1067. # _set_ddp_with_replicated_tensor(True)
  1068. # The rest is copypasta from MultiProcessTestCase._run
  1069. self = cls(test_name)
  1070. self.rank = rank
  1071. self.file_name = file_name
  1072. self.run_test(test_name, parent_pipe)