distributed_utils.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380
  1. # Copyright ESPnet (https://github.com/espnet/espnet). All Rights Reserved.
  2. # Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
  3. import dataclasses
  4. import logging
  5. import os
  6. import socket
  7. from typing import Optional
  8. import torch
  9. import torch.distributed
  10. @dataclasses.dataclass
  11. class DistributedOption:
  12. # Enable distributed Training
  13. distributed: bool = False
  14. # torch.distributed.Backend: "nccl", "mpi", "gloo", or "tcp"
  15. dist_backend: str = "nccl"
  16. # if init_method="env://",
  17. # env values of "MASTER_PORT", "MASTER_ADDR", "WORLD_SIZE", and "RANK" are referred.
  18. dist_init_method: str = "env://"
  19. dist_world_size: Optional[int] = None
  20. dist_rank: Optional[int] = None
  21. local_rank: Optional[int] = None
  22. ngpu: int = 0
  23. dist_master_addr: Optional[str] = None
  24. dist_master_port: Optional[int] = None
  25. dist_launcher: Optional[str] = None
  26. multiprocessing_distributed: bool = True
  27. def init_options(self):
  28. if self.distributed:
  29. if self.dist_init_method == "env://":
  30. if get_master_addr(self.dist_master_addr, self.dist_launcher) is None:
  31. raise RuntimeError(
  32. "--dist_master_addr or MASTER_ADDR must be set "
  33. "if --dist_init_method == 'env://'"
  34. )
  35. if get_master_port(self.dist_master_port) is None:
  36. raise RuntimeError(
  37. "--dist_master_port or MASTER_PORT must be set "
  38. "if --dist_init_port == 'env://'"
  39. )
  40. def init_torch_distributed(self, args):
  41. if self.distributed:
  42. # See:
  43. # https://docs.nvidia.com/deeplearning/sdk/nccl-developer-guide/docs/env.html
  44. os.environ.setdefault("NCCL_DEBUG", "INFO")
  45. # See:
  46. # https://pytorch.org/docs/stable/distributed.html#torch.distributed.init_process_group
  47. os.environ.setdefault("NCCL_BLOCKING_WAIT", "1")
  48. torch.distributed.init_process_group(backend=self.dist_backend,
  49. init_method=self.dist_init_method,
  50. world_size=args.dist_world_size,
  51. rank=args.dist_rank)
  52. self.dist_rank = torch.distributed.get_rank()
  53. self.dist_world_size = torch.distributed.get_world_size()
  54. self.local_rank = args.local_rank
  55. def init_options_pai(self):
  56. if self.distributed:
  57. if self.dist_init_method == "env://":
  58. if get_master_addr(self.dist_master_addr, self.dist_launcher) is None:
  59. raise RuntimeError(
  60. "--dist_master_addr or MASTER_ADDR must be set "
  61. "if --dist_init_method == 'env://'"
  62. )
  63. if get_master_port(self.dist_master_port) is None:
  64. raise RuntimeError(
  65. "--dist_master_port or MASTER_PORT must be set "
  66. "if --dist_init_port == 'env://'"
  67. )
  68. self.dist_rank = get_rank(self.dist_rank, self.dist_launcher)
  69. self.dist_world_size = get_world_size(
  70. self.dist_world_size, self.dist_launcher
  71. )
  72. self.local_rank = get_local_rank(self.local_rank, self.dist_launcher)
  73. if (
  74. self.dist_rank is not None
  75. and self.dist_world_size is not None
  76. and self.dist_rank >= self.dist_world_size
  77. ):
  78. raise RuntimeError(
  79. f"RANK >= WORLD_SIZE: {self.dist_rank} >= {self.dist_world_size}"
  80. )
  81. if self.dist_init_method == "env://":
  82. self.dist_master_addr = get_master_addr(
  83. self.dist_master_addr, self.dist_launcher
  84. )
  85. self.dist_master_port = get_master_port(self.dist_master_port)
  86. if (
  87. self.dist_master_addr is not None
  88. and self.dist_master_port is not None
  89. ):
  90. self.dist_init_method = (
  91. f"tcp://{self.dist_master_addr}:{self.dist_master_port}"
  92. )
  93. def init_torch_distributed_pai(self, args):
  94. if self.distributed:
  95. # See:
  96. # https://docs.nvidia.com/deeplearning/sdk/nccl-developer-guide/docs/env.html
  97. os.environ.setdefault("NCCL_DEBUG", "INFO")
  98. # See:
  99. # https://pytorch.org/docs/stable/distributed.html#torch.distributed.init_process_group
  100. os.environ.setdefault("NCCL_BLOCKING_WAIT", "1")
  101. torch.distributed.init_process_group(backend=self.dist_backend, init_method='env://')
  102. self.dist_rank = torch.distributed.get_rank()
  103. self.dist_world_size = torch.distributed.get_world_size()
  104. self.local_rank = args.local_rank
  105. def resolve_distributed_mode(args):
  106. # Note that args.distributed is set by only this function.
  107. # and ArgumentParser doesn't have such option
  108. if args.multiprocessing_distributed:
  109. num_nodes = get_num_nodes(args.dist_world_size, args.dist_launcher)
  110. # a. multi-node
  111. if num_nodes > 1:
  112. args.distributed = True
  113. # b. single-node and multi-gpu with multiprocessing_distributed mode
  114. elif args.ngpu > 1:
  115. args.distributed = True
  116. # c. single-node and single-gpu
  117. else:
  118. args.distributed = False
  119. if args.ngpu <= 1:
  120. # Disable multiprocessing_distributed mode if 1process per node or cpu mode
  121. args.multiprocessing_distributed = False
  122. if args.ngpu == 1:
  123. # If the number of GPUs equals to 1 with multiprocessing_distributed mode,
  124. # LOCAL_RANK is always 0
  125. args.local_rank = 0
  126. if num_nodes > 1 and get_node_rank(args.dist_rank, args.dist_launcher) is None:
  127. raise RuntimeError(
  128. "--dist_rank or RANK must be set "
  129. "if --multiprocessing_distributed == true"
  130. )
  131. # Note that RANK, LOCAL_RANK, and WORLD_SIZE is automatically set,
  132. # so we don't need to check here
  133. else:
  134. # d. multiprocess and multi-gpu with external launcher
  135. # e.g. torch.distributed.launch
  136. if get_world_size(args.dist_world_size, args.dist_launcher) > 1:
  137. args.distributed = True
  138. # e. single-process
  139. else:
  140. args.distributed = False
  141. if args.distributed and args.ngpu > 0:
  142. if get_local_rank(args.local_rank, args.dist_launcher) is None:
  143. raise RuntimeError(
  144. "--local_rank or LOCAL_RANK must be set "
  145. "if --multiprocessing_distributed == false"
  146. )
  147. if args.distributed:
  148. if get_node_rank(args.dist_rank, args.dist_launcher) is None:
  149. raise RuntimeError(
  150. "--dist_rank or RANK must be set "
  151. "if --multiprocessing_distributed == false"
  152. )
  153. if args.distributed and args.dist_launcher == "slurm" and not is_in_slurm_step():
  154. raise RuntimeError("Launch by 'srun' command if --dist_launcher='slurm'")
  155. def is_in_slurm_job() -> bool:
  156. return "SLURM_PROCID" in os.environ and "SLURM_NTASKS" in os.environ
  157. def is_in_slurm_step() -> bool:
  158. return (
  159. is_in_slurm_job()
  160. and "SLURM_STEP_NUM_NODES" in os.environ
  161. and "SLURM_STEP_NODELIST" in os.environ
  162. )
  163. def _int_or_none(x: Optional[str]) -> Optional[int]:
  164. if x is None:
  165. return x
  166. return int(x)
  167. def free_port():
  168. """Find free port using bind().
  169. There are some interval between finding this port and using it
  170. and the other process might catch the port by that time.
  171. Thus it is not guaranteed that the port is really empty.
  172. """
  173. with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
  174. sock.bind(("", 0))
  175. return sock.getsockname()[1]
  176. def get_rank(prior=None, launcher: str = None) -> Optional[int]:
  177. if prior is None:
  178. if launcher == "slurm":
  179. if not is_in_slurm_step():
  180. raise RuntimeError("This process seems not to be launched by 'srun'")
  181. prior = os.environ["SLURM_PROCID"]
  182. elif launcher == "mpi":
  183. raise RuntimeError(
  184. "launcher=mpi is used for 'multiprocessing-distributed' mode"
  185. )
  186. elif launcher is not None:
  187. raise RuntimeError(f"launcher='{launcher}' is not supported")
  188. if prior is not None:
  189. return int(prior)
  190. else:
  191. # prior is None and RANK is None -> RANK = None
  192. return _int_or_none(os.environ.get("RANK"))
  193. def get_world_size(prior=None, launcher: str = None) -> int:
  194. if prior is None:
  195. if launcher == "slurm":
  196. if not is_in_slurm_step():
  197. raise RuntimeError("This process seems not to be launched by 'srun'")
  198. prior = int(os.environ["SLURM_NTASKS"])
  199. elif launcher == "mpi":
  200. raise RuntimeError(
  201. "launcher=mpi is used for 'multiprocessing-distributed' mode"
  202. )
  203. elif launcher is not None:
  204. raise RuntimeError(f"launcher='{launcher}' is not supported")
  205. if prior is not None:
  206. return int(prior)
  207. else:
  208. # prior is None and WORLD_SIZE is None -> WORLD_SIZE = 1
  209. return int(os.environ.get("WORLD_SIZE", "1"))
  210. def get_local_rank(prior=None, launcher: str = None) -> Optional[int]:
  211. # LOCAL_RANK is same as GPU device id
  212. if prior is None:
  213. if launcher == "slurm":
  214. if not is_in_slurm_step():
  215. raise RuntimeError("This process seems not to be launched by 'srun'")
  216. prior = int(os.environ["SLURM_LOCALID"])
  217. elif launcher == "mpi":
  218. raise RuntimeError(
  219. "launcher=mpi is used for 'multiprocessing-distributed' mode"
  220. )
  221. elif launcher is not None:
  222. raise RuntimeError(f"launcher='{launcher}' is not supported")
  223. if prior is not None:
  224. return int(prior)
  225. elif "LOCAL_RANK" in os.environ:
  226. return int(os.environ["LOCAL_RANK"])
  227. elif "CUDA_VISIBLE_DEVICES" in os.environ:
  228. # There are two possibility:
  229. # - "CUDA_VISIBLE_DEVICES" is set to multiple GPU ids. e.g. "0.1,2"
  230. # => This intends to specify multiple devices to to be used exactly
  231. # and local_rank information is possibly insufficient.
  232. # - "CUDA_VISIBLE_DEVICES" is set to an id. e.g. "1"
  233. # => This could be used for LOCAL_RANK
  234. cvd = os.environ["CUDA_VISIBLE_DEVICES"].split(",")
  235. if len(cvd) == 1 and "LOCAL_RANK" not in os.environ:
  236. # If CUDA_VISIBLE_DEVICES is set and LOCAL_RANK is not set,
  237. # then use it as LOCAL_RANK.
  238. # Unset CUDA_VISIBLE_DEVICES
  239. # because the other device must be visible to communicate
  240. return int(os.environ.pop("CUDA_VISIBLE_DEVICES"))
  241. else:
  242. return None
  243. else:
  244. return None
  245. def get_master_addr(prior=None, launcher: str = None) -> Optional[str]:
  246. if prior is None:
  247. if launcher == "slurm":
  248. if not is_in_slurm_step():
  249. raise RuntimeError("This process seems not to be launched by 'srun'")
  250. # e.g nodelist = foo[1-10],bar[3-8] or foo4,bar[2-10]
  251. nodelist = os.environ["SLURM_STEP_NODELIST"]
  252. prior = nodelist.split(",")[0].split("-")[0].replace("[", "")
  253. if prior is not None:
  254. return str(prior)
  255. else:
  256. return os.environ.get("MASTER_ADDR")
  257. def get_master_port(prior=None) -> Optional[int]:
  258. if prior is not None:
  259. return prior
  260. else:
  261. return _int_or_none(os.environ.get("MASTER_PORT"))
  262. def get_node_rank(prior=None, launcher: str = None) -> Optional[int]:
  263. """Get Node Rank.
  264. Use for "multiprocessing distributed" mode.
  265. The initial RANK equals to the Node id in this case and
  266. the real Rank is set as (nGPU * NodeID) + LOCAL_RANK in torch.distributed.
  267. """
  268. if prior is not None:
  269. return prior
  270. elif launcher == "slurm":
  271. if not is_in_slurm_step():
  272. raise RuntimeError("This process seems not to be launched by 'srun'")
  273. # Assume ntasks_per_node == 1
  274. if os.environ["SLURM_STEP_NUM_NODES"] != os.environ["SLURM_NTASKS"]:
  275. raise RuntimeError(
  276. "Run with --ntasks_per_node=1 if mutliprocessing_distributed=true"
  277. )
  278. return int(os.environ["SLURM_NODEID"])
  279. elif launcher == "mpi":
  280. # Use mpi4py only for initialization and not using for communication
  281. from mpi4py import MPI
  282. comm = MPI.COMM_WORLD
  283. # Assume ntasks_per_node == 1 (We can't check whether it is or not)
  284. return comm.Get_rank()
  285. elif launcher is not None:
  286. raise RuntimeError(f"launcher='{launcher}' is not supported")
  287. else:
  288. return _int_or_none(os.environ.get("RANK"))
  289. def get_num_nodes(prior=None, launcher: str = None) -> Optional[int]:
  290. """Get the number of nodes.
  291. Use for "multiprocessing distributed" mode.
  292. RANK equals to the Node id in this case and
  293. the real Rank is set as (nGPU * NodeID) + LOCAL_RANK in torch.distributed.
  294. """
  295. if prior is not None:
  296. return prior
  297. elif launcher == "slurm":
  298. if not is_in_slurm_step():
  299. raise RuntimeError("This process seems not to be launched by 'srun'")
  300. # Assume ntasks_per_node == 1
  301. if os.environ["SLURM_STEP_NUM_NODES"] != os.environ["SLURM_NTASKS"]:
  302. raise RuntimeError(
  303. "Run with --ntasks_per_node=1 if mutliprocessing_distributed=true"
  304. )
  305. return int(os.environ["SLURM_STEP_NUM_NODES"])
  306. elif launcher == "mpi":
  307. # Use mpi4py only for initialization and not using for communication
  308. from mpi4py import MPI
  309. comm = MPI.COMM_WORLD
  310. # Assume ntasks_per_node == 1 (We can't check whether it is or not)
  311. return comm.Get_size()
  312. elif launcher is not None:
  313. raise RuntimeError(f"launcher='{launcher}' is not supported")
  314. else:
  315. # prior is None -> NUM_NODES = 1
  316. return int(os.environ.get("WORLD_SIZE", 1))