common_distributed.py 49 KB

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