launch.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358
  1. # Copyright 2020 The Microsoft DeepSpeed Team
  2. """
  3. DeepSpeed launcher, this is similar to torch's distributed.launch but supports
  4. additional features such as arbitrary gpu exclusion.
  5. deepspeed.launcher.launch is intended to be run on a single worker node and
  6. will spawn several worker sub-processes depending on how many devices/ranks
  7. are on the worker.
  8. """
  9. import sys
  10. import subprocess
  11. import os
  12. import json
  13. import base64
  14. import time
  15. import signal
  16. import psutil
  17. from collections import defaultdict
  18. from typing import Dict
  19. from argparse import ArgumentParser, REMAINDER
  20. from ..constants import TORCH_DISTRIBUTED_DEFAULT_PORT
  21. from ..nebula.constants import DLTS_POD_ENV_PATH
  22. from ..utils import logger
  23. from ..elasticity import is_torch_elastic_compatible
  24. from .constants import ELASTIC_TRAINING_ID_DEFAULT
  25. PID_FILE_BASEPATH = "/tmp"
  26. def parse_args():
  27. parser = ArgumentParser(description="DeepSpeed distributed training launch"
  28. " utility that creates multiple distributed"
  29. " processes on a single node")
  30. # Optional arguments for the launch helper
  31. parser.add_argument("--node_rank",
  32. type=int,
  33. default=0,
  34. help="The rank of the node for multi-node distributed "
  35. "training")
  36. parser.add_argument("--master_addr",
  37. default="127.0.0.1",
  38. type=str,
  39. help="Master node (rank 0)'s address, should be either"
  40. " the IP address or the hostname of node 0, for"
  41. " single node multi-proc training, the"
  42. " --master_addr can simply be 127.0.0.1")
  43. parser.add_argument("--master_port",
  44. default=TORCH_DISTRIBUTED_DEFAULT_PORT,
  45. type=int,
  46. help="Master node (rank 0)'s free port that needs to "
  47. "be used for communication during distributed "
  48. "training")
  49. parser.add_argument("--world_info",
  50. default="None",
  51. type=str,
  52. help="world info base64 encoded dictionary")
  53. parser.add_argument("--module",
  54. action="store_true",
  55. help="Change each process to interpret the launch "
  56. "script as a Python module, executing with the same "
  57. "behavior as 'python -m'.")
  58. parser.add_argument("--no_python",
  59. action="store_true",
  60. help="Skip prepending the training script with "
  61. "'python' - just execute it directly.")
  62. parser.add_argument("--enable_elastic_training",
  63. action="store_true",
  64. help="Enable elastic training support.")
  65. parser.add_argument("--min_elastic_nodes",
  66. type=int,
  67. default=-1,
  68. help="Min number of nodes in elastic training.")
  69. parser.add_argument("--max_elastic_nodes",
  70. type=int,
  71. default=-1,
  72. help="Max number of nodes in elastic training.")
  73. parser.add_argument("--no_local_rank",
  74. action="store_true",
  75. help="Do not pass local_rank as an argument when calling "
  76. "the user's training script.")
  77. parser.add_argument("--save_pid",
  78. type=int,
  79. default=0,
  80. help="main launching process pid, for internal pid tracking")
  81. parser.add_argument(
  82. "--enable_each_rank_log",
  83. default="None",
  84. type=str,
  85. help="redirect the stdout and stderr from each rank into different log files")
  86. # positional
  87. parser.add_argument("training_script",
  88. type=str,
  89. help="The full path to the single GPU training "
  90. "program/script to be launched in parallel, "
  91. "followed by all the arguments for the "
  92. "training script")
  93. # rest from the training program
  94. parser.add_argument('training_script_args', nargs=REMAINDER)
  95. return parser.parse_args()
  96. # Adapted from https://psutil.readthedocs.io/en/latest/#kill-process-tree
  97. def terminate_process_tree(pid):
  98. process = psutil.Process(pid)
  99. children = process.children(recursive=True)
  100. children.append(process)
  101. for child in children:
  102. try:
  103. child.terminate()
  104. except psutil.NoSuchProcess:
  105. pass
  106. gone, alive = psutil.wait_procs(children, timeout=30)
  107. for p in alive:
  108. p.kill()
  109. def main():
  110. args = parse_args()
  111. current_env = os.environ.copy()
  112. for k in current_env.keys():
  113. if "NCCL" in k:
  114. logger.info(f"{args.node_rank} {k}={current_env[k]}")
  115. if args.world_info == "None":
  116. raise ValueError("world_info can not be None")
  117. world_info = base64.urlsafe_b64decode(args.world_info)
  118. world_info = json.loads(world_info)
  119. logger.info(f"WORLD INFO DICT: {world_info}")
  120. node_list = list(world_info.keys())
  121. args.nnodes = len(node_list)
  122. local_node = node_list[args.node_rank]
  123. local_gpu_ids = world_info[local_node]
  124. num_local_procs = len(local_gpu_ids)
  125. logger.info(
  126. f"nnodes={args.nnodes}, num_local_procs={num_local_procs}, node_rank={args.node_rank}"
  127. )
  128. global_rank_mapping = defaultdict(list)
  129. curr_global_rank = 0
  130. dist_world_size = 0
  131. for node_id in node_list:
  132. gids = world_info[node_id]
  133. dist_world_size += len(gids)
  134. for gid in gids:
  135. global_rank_mapping[node_id].append(curr_global_rank)
  136. curr_global_rank += 1
  137. logger.info(f"global_rank_mapping={global_rank_mapping}")
  138. logger.info(f"dist_world_size={dist_world_size}")
  139. current_env["CUDA_VISIBLE_DEVICES"] = ",".join(map(str, local_gpu_ids))
  140. logger.info(f"Setting CUDA_VISIBLE_DEVICES={current_env['CUDA_VISIBLE_DEVICES']}")
  141. # set PyTorch distributed related environmental variables
  142. current_env["MASTER_ADDR"] = args.master_addr
  143. current_env["MASTER_PORT"] = str(args.master_port)
  144. current_env["WORLD_SIZE"] = str(dist_world_size)
  145. current_env["CROSS_RANK"] = str(args.node_rank)
  146. current_env["CROSS_SIZE"] = str(args.nnodes)
  147. current_env["LOCAL_SIZE"] = str(num_local_procs)
  148. if args.save_pid:
  149. print(f"launcher pid: {os.getpid()}")
  150. pid_file = None
  151. if args.save_pid:
  152. launcher_pid = os.getpid()
  153. pid_file = os.path.join(PID_FILE_BASEPATH, f"{args.save_pid}.deepspeed")
  154. assert not os.path.isfile(pid_file), "pid file exists but shouldn't"
  155. with open(pid_file, 'w') as fd:
  156. fd.write(f"{launcher_pid}")
  157. if not is_torch_elastic_compatible():
  158. if args.enable_elastic_training:
  159. logger.info(f"Disabling elastic training support as \
  160. PyTorch version should be greater than 1.11.x")
  161. args.enable_elastic_training = False
  162. if os.path.exists(DLTS_POD_ENV_PATH):
  163. with open(DLTS_POD_ENV_PATH) as file:
  164. lines = file.readlines()
  165. lines = [line.rstrip() for line in lines]
  166. for line in lines:
  167. if line.startswith('export FC_TASKROLE_NAME') or line.startswith(
  168. 'export FC_TASK_INDEX'):
  169. key_val = line.split()[1]
  170. key, val = key_val.split('=')
  171. current_env[key] = val
  172. processes = []
  173. cmd = []
  174. if not args.enable_elastic_training:
  175. if args.enable_each_rank_log != "None":
  176. # prepare the log path and the file name prefix
  177. if os.path.isfile(args.enable_each_rank_log):
  178. raise ValueError(
  179. f"{args.enable_each_rank_log} should not be a file, it should be a directory."
  180. )
  181. if not os.path.exists(args.enable_each_rank_log):
  182. try:
  183. os.makedirs(args.enable_each_rank_log)
  184. except Exception as e:
  185. print(e)
  186. raise ValueError(
  187. f"unable to create directory {args.enable_each_rank_log} for each rank log."
  188. )
  189. log_name_prefix = time.strftime("%Y%m%d%H%M%S", time.localtime())
  190. for local_rank in range(0, num_local_procs):
  191. # each process's rank
  192. dist_rank = global_rank_mapping[local_node][local_rank]
  193. current_env["RANK"] = str(dist_rank)
  194. current_env["LOCAL_RANK"] = str(local_rank)
  195. # spawn the processes
  196. cmd = []
  197. if not args.no_python:
  198. cmd = [sys.executable, "-u"]
  199. if args.module:
  200. cmd.append("-m")
  201. else:
  202. if args.module:
  203. raise ValueError("Don't use both the '--no_python' flag"
  204. " and the '--module' flag at the same time.")
  205. cmd.append(args.training_script)
  206. # A user may not want to pass local_rank as a keyword arg so we make this optional.
  207. if not args.no_local_rank:
  208. cmd.append(f"--local_rank={local_rank}")
  209. cmd += args.training_script_args
  210. if args.enable_each_rank_log != "None":
  211. log_file = os.path.join(args.enable_each_rank_log,
  212. f"{log_name_prefix}_rank{dist_rank}.log")
  213. log_fd = open(log_file, 'w')
  214. process = subprocess.Popen(cmd,
  215. env=current_env,
  216. stdout=log_fd,
  217. stderr=log_fd)
  218. else:
  219. process = subprocess.Popen(cmd, env=current_env)
  220. processes.append(process)
  221. else:
  222. from ..elasticity import DSElasticAgent
  223. from torch.distributed.elastic.rendezvous import RendezvousParameters
  224. from torch.distributed.elastic.agent.server.api import WorkerSpec
  225. import torch.distributed.elastic.rendezvous.registry as rdzv_registry
  226. from torch.distributed.elastic.multiprocessing import Std
  227. if args.min_elastic_nodes == -1:
  228. args.min_elastic_nodes = 1
  229. if args.max_elastic_nodes == -1:
  230. args.max_elastic_nodes = args.nnodes
  231. assert args.max_elastic_nodes > 0 and args.min_elastic_nodes > 0 , "Max and Min nodes should be positive"
  232. current_env["NCCL_ASYNC_ERROR_HANDLING"] = str(1)
  233. # Get config and arguments
  234. cmd = []
  235. if not args.no_python:
  236. cmd = [sys.executable, "-u"]
  237. if args.module:
  238. cmd.append("-m")
  239. else:
  240. if args.module:
  241. raise ValueError("Don't use both the '--no_python' flag"
  242. " and the '--module' flag at the same time.")
  243. cmd.append(args.training_script)
  244. cmd += args.training_script_args
  245. cmd_args = cmd[1:]
  246. rdzv_configs: Dict[str, str] = {'timeout': 100}
  247. run_id = os.environ.get("ELASTIC_RUN_ID", ELASTIC_TRAINING_ID_DEFAULT)
  248. # Creating config for rendezvous class
  249. rdzv_parameters = RendezvousParameters(backend='c10d',
  250. endpoint=args.master_addr + ":" +
  251. str(args.master_port),
  252. run_id=run_id,
  253. min_nodes=args.min_elastic_nodes,
  254. max_nodes=args.max_elastic_nodes,
  255. **rdzv_configs)
  256. spec = WorkerSpec(
  257. role='trainer',
  258. local_world_size=num_local_procs,
  259. entrypoint=cmd[0],
  260. args=cmd[1:],
  261. rdzv_handler=rdzv_registry.get_rendezvous_handler(rdzv_parameters),
  262. max_restarts=100,
  263. monitor_interval=5,
  264. redirects=Std.from_str("0"),
  265. tee=Std.from_str("0"),
  266. master_addr=None,
  267. master_port=None,
  268. )
  269. agent = DSElasticAgent(spec, current_env)
  270. agent.run()
  271. sig_names = {2: "SIGINT", 15: "SIGTERM"}
  272. last_return_code = None
  273. def sigkill_handler(signum, frame):
  274. for process in processes:
  275. logger.info(f"Killing subprocess {process.pid}")
  276. try:
  277. terminate_process_tree(process.pid)
  278. except Exception:
  279. pass
  280. if last_return_code is not None:
  281. logger.error(f"{cmd} exits with return code = {last_return_code}")
  282. sys.exit(last_return_code)
  283. if signum in sig_names:
  284. logger.info(f"Main process received {sig_names[signum]}, exiting")
  285. if args.save_pid:
  286. if os.path.isfile(pid_file):
  287. os.remove(pid_file)
  288. sys.exit(1)
  289. # pass SIGINT/SIGTERM to children if the parent is being terminated
  290. signal.signal(signal.SIGINT, sigkill_handler)
  291. signal.signal(signal.SIGTERM, sigkill_handler)
  292. alive_processes = set(processes)
  293. while len(alive_processes):
  294. finished_processes = []
  295. for process in alive_processes:
  296. if process.poll() is None:
  297. # the process is still running
  298. continue
  299. else:
  300. if process.returncode != 0:
  301. last_return_code = process.returncode # for sigkill_handler
  302. sigkill_handler(signal.SIGTERM, None) # not coming back
  303. else:
  304. # exited cleanly
  305. logger.info(f"Process {process.pid} exits successfully.")
  306. finished_processes.append(process)
  307. alive_processes = set(alive_processes) - set(finished_processes)
  308. time.sleep(1)
  309. if __name__ == "__main__":
  310. main()