runner.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596
  1. # Copyright (c) Microsoft Corporation.
  2. # SPDX-License-Identifier: Apache-2.0
  3. # DeepSpeed Team
  4. """
  5. DeepSpeed runner is the main front-end to launching multi-worker
  6. training jobs with DeepSpeed. By default this uses pdsh to parallel
  7. ssh into multiple worker nodes and launch all the necessary processes
  8. per rank for training.
  9. """
  10. import os
  11. import re
  12. import sys
  13. import shlex
  14. import json
  15. import base64
  16. import argparse
  17. import subprocess
  18. import collections
  19. from copy import deepcopy
  20. import signal
  21. import time
  22. from .multinode_runner import PDSHRunner, OpenMPIRunner, MVAPICHRunner, SlurmRunner, MPICHRunner, IMPIRunner
  23. from .constants import PDSH_LAUNCHER, OPENMPI_LAUNCHER, MVAPICH_LAUNCHER, SLURM_LAUNCHER, MPICH_LAUNCHER, IMPI_LAUNCHER
  24. from ..constants import TORCH_DISTRIBUTED_DEFAULT_PORT
  25. from ..nebula.constants import NEBULA_EXPORT_ENVS
  26. from ..utils import logger
  27. from ..autotuning import Autotuner
  28. from deepspeed.accelerator import get_accelerator
  29. DLTS_HOSTFILE = "/job/hostfile"
  30. EXPORT_ENVS = ['MLFLOW', 'NCCL', 'PYTHON', 'MV2', 'UCX']
  31. EXPORT_ENVS += NEBULA_EXPORT_ENVS
  32. DEEPSPEED_ENVIRONMENT_NAME = os.getenv("DS_ENV_FILE", ".deepspeed_env")
  33. DEEPSPEED_ENVIRONMENT_PATHS = [os.path.expanduser("~"), '.']
  34. PDSH_MAX_FAN_OUT = 1024
  35. # On AISC compute, each node sets environment variables independently, want to prevent
  36. # exporting rank-0 env variables in case of heterogeneous compute.
  37. EXCLUDE_ENVS = {'AISC_JOB_NAME': ['NCCL_IB_HCA', 'UCX_NET_DEVICES']}
  38. def parse_args(args=None):
  39. parser = argparse.ArgumentParser(description="DeepSpeed runner to help launch distributed "
  40. "multi-node/multi-gpu training jobs.",
  41. formatter_class=argparse.ArgumentDefaultsHelpFormatter)
  42. parser.add_argument("-H",
  43. "--hostfile",
  44. type=str,
  45. default=DLTS_HOSTFILE,
  46. help="Hostfile path (in MPI style) that defines the "
  47. "resource pool available to the job (e.g., "
  48. "worker-0 slots=4)")
  49. parser.add_argument("-i",
  50. "--include",
  51. type=str,
  52. default="",
  53. help='''Specify hardware resources to use during execution.
  54. String format is
  55. NODE_SPEC[@NODE_SPEC ...],
  56. where
  57. NODE_SPEC=NAME[:SLOT[,SLOT ...]].
  58. If :SLOT is omitted, include all slots on that host.
  59. Example: -i "worker-0@worker-1:0,2" will use all slots
  60. on worker-0 and slots [0, 2] on worker-1.
  61. ''')
  62. parser.add_argument("-e",
  63. "--exclude",
  64. type=str,
  65. default="",
  66. help='''Specify hardware resources to NOT use during execution.
  67. Mutually exclusive with --include. Resource formatting
  68. is the same as --include.
  69. Example: -e "worker-1:0" will use all available
  70. resources except slot 0 on worker-1.
  71. ''')
  72. parser.add_argument("--num_nodes",
  73. type=int,
  74. default=-1,
  75. help="Total number of worker nodes to run on, this will use "
  76. "the top N hosts from the given hostfile.")
  77. parser.add_argument("--min_elastic_nodes",
  78. type=int,
  79. default=-1,
  80. help="Minimum number of nodes to run elastic training on. "
  81. "Default is 1 when elastic training is enabled")
  82. parser.add_argument("--max_elastic_nodes",
  83. type=int,
  84. default=-1,
  85. help="Maximum number of nodes to run elastic training on. "
  86. "Default is num_nodes when elastic training is enabled")
  87. parser.add_argument("--num_gpus",
  88. "--num_accelerators",
  89. type=int,
  90. default=-1,
  91. help="Max number of GPUs to use on each node, will use "
  92. "[0:N) GPU ids on each node.")
  93. parser.add_argument("--master_port",
  94. default=TORCH_DISTRIBUTED_DEFAULT_PORT,
  95. type=int,
  96. help="(optional) Port used by PyTorch distributed for "
  97. "communication during training.")
  98. parser.add_argument("--master_addr",
  99. default="",
  100. type=str,
  101. help="(optional) IP address of node 0, will be "
  102. "inferred via 'hostname -I' if not specified.")
  103. parser.add_argument("--launcher",
  104. default=PDSH_LAUNCHER,
  105. type=str,
  106. help="(optional) choose launcher backend for multi-node "
  107. "training. Options currently include PDSH, OpenMPI, MVAPICH, SLURM, MPICH, IMPI.")
  108. parser.add_argument("--launcher_args",
  109. default="",
  110. type=str,
  111. help="(optional) pass launcher specific arguments as a "
  112. "single quoted argument.")
  113. parser.add_argument("--module",
  114. action="store_true",
  115. help="Change each process to interpret the launch "
  116. "script as a Python module, executing with the same "
  117. "behavior as 'python -m'.")
  118. parser.add_argument("--no_python",
  119. action="store_true",
  120. help="Skip prepending the training script with "
  121. "'python' - just execute it directly.")
  122. parser.add_argument("--no_local_rank",
  123. action="store_true",
  124. help="Do not pass local_rank as an argument when calling "
  125. "the user's training script.")
  126. parser.add_argument("--no_ssh_check",
  127. action="store_true",
  128. help="Do not perform ssh check in multi-node launcher model")
  129. parser.add_argument("--force_multi",
  130. action="store_true",
  131. help="Force multi-node launcher mode, helps in cases where user "
  132. "wants to launch on single remote node.")
  133. parser.add_argument("--save_pid",
  134. action="store_true",
  135. help="Save file containing launcher process id (pid) at /tmp/<main-pid>.ds, "
  136. "where <main-pid> is the pid of the first process that invoked `deepspeed`. "
  137. "Useful when launching deepspeed processes programmatically.")
  138. parser.add_argument("--enable_each_rank_log",
  139. default="None",
  140. type=str,
  141. help="redirect the stdout and stderr from each rank into different log files")
  142. parser.add_argument("--autotuning",
  143. default="",
  144. choices=["tune", "run"],
  145. type=str,
  146. help="Run DeepSpeed autotuner to discover optimal configuration parameters "
  147. "before running job.")
  148. parser.add_argument("--elastic_training",
  149. action="store_true",
  150. help="Enable elastic training support in DeepSpeed.")
  151. parser.add_argument("user_script", type=str, help="User script to launch, followed by any required "
  152. "arguments.")
  153. parser.add_argument('user_args', nargs=argparse.REMAINDER)
  154. parser.add_argument("--bind_cores_to_rank",
  155. action="store_true",
  156. help="Bind each rank to different cores of the host")
  157. parser.add_argument("--bind_core_list",
  158. type=str,
  159. default=None,
  160. help="List of cores to bind to with comma separated list of "
  161. "numbers and range. i.e. 1,3-5,7 => [1,3,4,5,7]. When not "
  162. "specified, all cores on system would be used rank binding")
  163. parser.add_argument("--ssh_port", type=int, default=None, help="SSH port to use for remote connections")
  164. return parser.parse_args(args=args)
  165. def fetch_hostfile(hostfile_path):
  166. if not os.path.isfile(hostfile_path):
  167. logger.warning("Unable to find hostfile, will proceed with training "
  168. "with local resources only.")
  169. return None
  170. # e.g., worker-0 slots=16
  171. with open(hostfile_path, 'r') as fd:
  172. hostfile_text = fd.readlines()
  173. return _parse_hostfile(hostfile_text)
  174. def _parse_hostfile(hostfile_lines):
  175. # Regex matches one or more non-whitespace characters (\S+) at the start of
  176. # the line, followed by one or more whitespace characters (\s+), followed
  177. # by the string "slots=", followed by one or more digits (\d+).
  178. pattern = r'^(\S+)\s+slots=(\d+)'
  179. resource_pool = collections.OrderedDict()
  180. for line in hostfile_lines:
  181. line = line.strip()
  182. match = re.search(pattern, line)
  183. if line.startswith("#") or line == "":
  184. # hostfile comment or empty line, ignore
  185. continue
  186. elif match:
  187. host = match.group(1)
  188. num_slots = int(match.group(2))
  189. if host in resource_pool:
  190. logger.error(f"Bad hostfile text: {hostfile_lines}")
  191. raise ValueError(f"Hostfile contains multiple entries for {host}, unable to proceed with launching")
  192. resource_pool[host] = num_slots
  193. else:
  194. logger.error(f"Bad hostfile text: {hostfile_lines}")
  195. raise ValueError(f"Hostfile contains a bad entry: {line}, unable to proceed with launching")
  196. if len(resource_pool) == 0:
  197. logger.error(f"Bad hostfile text: {hostfile_lines}")
  198. raise ValueError("Hostfile is empty or not formatted correctly, unable to proceed with launching.")
  199. return resource_pool
  200. def _stable_remove_duplicates(data):
  201. # Create a new list in the same order as original but with duplicates
  202. # removed, should never be more than ~16 elements so simple is best
  203. new_list = []
  204. for x in data:
  205. if x not in new_list:
  206. new_list.append(x)
  207. return new_list
  208. def parse_resource_filter(host_info, include_str="", exclude_str=""):
  209. '''Parse an inclusion or exclusion string and filter a hostfile dictionary.
  210. String format is NODE_SPEC[@NODE_SPEC ...], where
  211. NODE_SPEC = NAME[:SLOT[,SLOT ...]].
  212. If :SLOT is omitted, include/exclude all slots on that host.
  213. Examples:
  214. include_str="worker-0@worker-1:0,2" will use all slots on worker-0 and
  215. slots [0, 2] on worker-1.
  216. exclude_str="worker-1:0" will use all available resources except
  217. slot 0 on worker-1.
  218. '''
  219. # Constants that define our syntax
  220. NODE_SEP = '@'
  221. SLOT_LIST_START = ':'
  222. SLOT_SEP = ','
  223. # Ensure include/exclude are mutually exclusive
  224. if (include_str != "") and (exclude_str != ""):
  225. raise ValueError('include_str and exclude_str are mutually exclusive.')
  226. # no-op
  227. if (include_str == "") and (exclude_str == ""):
  228. return host_info
  229. # Either build from scratch or remove items
  230. filtered_hosts = dict()
  231. if include_str:
  232. parse_str = include_str
  233. if exclude_str != "":
  234. filtered_hosts = deepcopy(host_info)
  235. parse_str = exclude_str
  236. # foreach node in the list
  237. for node_config in parse_str.split(NODE_SEP):
  238. # Node can either be alone or node:slot,slot,slot
  239. if SLOT_LIST_START in node_config:
  240. hostname, slots = node_config.split(SLOT_LIST_START)
  241. slots = [int(x) for x in slots.split(SLOT_SEP)]
  242. # sanity checks
  243. if hostname not in host_info:
  244. raise ValueError(f"Hostname '{hostname}' not found in hostfile")
  245. for slot in slots:
  246. if slot not in host_info[hostname]:
  247. raise ValueError(f"No slot '{slot}' specified on host '{hostname}'")
  248. # If include string, build the list from here
  249. if include_str:
  250. filtered_hosts[hostname] = slots
  251. elif exclude_str:
  252. for slot in slots:
  253. logger.info(f'removing {slot} from {hostname}')
  254. filtered_hosts[hostname].remove(slot)
  255. # User just specified the whole node
  256. else:
  257. hostname = node_config
  258. # sanity check hostname
  259. if hostname not in host_info:
  260. raise ValueError(f"Hostname '{hostname}' not found in hostfile")
  261. if include_str:
  262. filtered_hosts[hostname] = host_info[hostname]
  263. elif exclude_str:
  264. filtered_hosts[hostname] = []
  265. # Post-processing to remove duplicates and empty nodes
  266. del_keys = []
  267. for hostname in filtered_hosts:
  268. # Remove duplicates
  269. filtered_hosts[hostname] = _stable_remove_duplicates(filtered_hosts[hostname])
  270. # Remove empty hosts
  271. if len(filtered_hosts[hostname]) == 0:
  272. del_keys.append(hostname)
  273. for name in del_keys:
  274. del filtered_hosts[name]
  275. # Lastly, go over filtered_hosts and convert to a OrderedDict() to ensure
  276. # we map ranks to nodes correctly by maintaining host_info ordering.
  277. ordered_hosts = collections.OrderedDict()
  278. for host in host_info:
  279. if host in filtered_hosts:
  280. ordered_hosts[host] = filtered_hosts[host]
  281. return ordered_hosts
  282. def parse_inclusion_exclusion(resource_pool, inclusion, exclusion):
  283. active_resources = collections.OrderedDict()
  284. for hostname, slots in resource_pool.items():
  285. active_resources[hostname] = list(range(slots))
  286. return parse_resource_filter(active_resources, include_str=inclusion, exclude_str=exclusion)
  287. def encode_world_info(world_info):
  288. world_info_json = json.dumps(world_info).encode('utf-8')
  289. world_info_base64 = base64.urlsafe_b64encode(world_info_json).decode('utf-8')
  290. return world_info_base64
  291. def run_autotuning(args, active_resources):
  292. tuner = Autotuner(args, active_resources)
  293. logger.info("[Start] Running autotuning")
  294. tuner.tune()
  295. tuner.print_tuning_results()
  296. logger.info("[End] Running autotuning")
  297. tuner.write_optimal_config()
  298. if args.autotuning == "run":
  299. tuner.run_after_tuning()
  300. def parse_num_nodes(str_num_nodes: str, elastic_training: bool):
  301. node_list = str_num_nodes.split(":")
  302. if len(node_list) == 1:
  303. min_nodes, max_nodes = int(node_list[0]), -1
  304. elif len(node_list) == 2 and elastic_training:
  305. min_nodes, max_nodes = int(node_list[0]), int(node_list[1])
  306. elif len(node_list) == 2 and not elastic_training:
  307. raise RuntimeError("MIN:MAX format is only supported in elastic training")
  308. else:
  309. raise RuntimeError("num_nodes {} is not in MIN:MAX format".format(str_num_nodes))
  310. return min_nodes, max_nodes
  311. def main(args=None):
  312. args = parse_args(args)
  313. # For when argparse interprets remaining args as a single string
  314. args.user_args = shlex.split(" ".join(args.user_args))
  315. if args.elastic_training:
  316. assert args.master_addr != "", "Master Addr is required when elastic training is enabled"
  317. resource_pool = fetch_hostfile(args.hostfile)
  318. # respect CUDA_VISIBLE_DEVICES for a single node and no explicit resource filters
  319. cuda_visible_devices = os.environ.get("CUDA_VISIBLE_DEVICES", "")
  320. if not resource_pool and len(cuda_visible_devices):
  321. detected_str = f"Detected CUDA_VISIBLE_DEVICES={cuda_visible_devices}"
  322. if len(args.include) or len(args.exclude) or args.num_nodes > 1 or args.num_gpus > 0:
  323. print(
  324. f"{detected_str} but ignoring it because one or several of --include/--exclude/--num_gpus/--num_nodes cl args were used. If you want to use CUDA_VISIBLE_DEVICES don't pass any of these arguments to deepspeed."
  325. )
  326. else:
  327. args.include = f"localhost:{cuda_visible_devices}"
  328. print(f"{detected_str}: setting --include={args.include}")
  329. del os.environ["CUDA_VISIBLE_DEVICES"]
  330. if args.num_nodes >= 0 or args.num_gpus >= 0:
  331. if args.include != "" or args.exclude != "":
  332. raise ValueError("Cannot specify num_nodes/gpus with include/exclude")
  333. multi_node_exec = True
  334. if not resource_pool:
  335. resource_pool = {}
  336. device_count = get_accelerator().device_count()
  337. if device_count == 0:
  338. raise RuntimeError("Unable to proceed, no GPU resources available")
  339. resource_pool['localhost'] = device_count
  340. args.master_addr = "127.0.0.1"
  341. multi_node_exec = False
  342. if not multi_node_exec and args.num_nodes > 1:
  343. raise ValueError("Num nodes is >1 but no extra nodes available via hostfile")
  344. active_resources = parse_inclusion_exclusion(resource_pool, args.include, args.exclude)
  345. env = os.environ.copy()
  346. # validate that passwordless-ssh is workly properly with this hostfile
  347. if multi_node_exec and not args.no_ssh_check:
  348. first_host = list(active_resources.keys())[0]
  349. try:
  350. ssh_check_cmd = "ssh -o PasswordAuthentication=no "
  351. if args.ssh_port is not None:
  352. ssh_check_cmd += f"-p {args.ssh_port} "
  353. ssh_check_cmd += f"{first_host} hostname"
  354. subprocess.check_call(ssh_check_cmd, stderr=subprocess.DEVNULL, stdout=subprocess.DEVNULL, shell=True)
  355. except subprocess.CalledProcessError:
  356. raise RuntimeError(
  357. f"Using hostfile at {args.hostfile} but host={first_host} was not reachable via ssh. If you are running with a single node please remove {args.hostfile} or setup passwordless ssh."
  358. )
  359. if not args.master_addr:
  360. assert multi_node_exec
  361. first_host = list(active_resources.keys())[0]
  362. hostname_cmd = [f"ssh {first_host} hostname -I"]
  363. try:
  364. result = subprocess.check_output(hostname_cmd, shell=True)
  365. except subprocess.CalledProcessError as err:
  366. logger.error(
  367. "Unable to detect suitable master address via `hostname -I`, please manually specify one via --master_addr"
  368. )
  369. raise err
  370. args.master_addr = result.decode('utf-8').split()[0]
  371. if not args.master_addr:
  372. raise RuntimeError(
  373. f"Unable to detect suitable master address via `hostname -I`, please manually specify one via --master_addr"
  374. )
  375. logger.info(f"Using IP address of {args.master_addr} for node {first_host}")
  376. if args.autotuning != "":
  377. run_autotuning(args, active_resources)
  378. return
  379. if args.num_nodes > 0:
  380. updated_active_resources = collections.OrderedDict()
  381. for count, hostname in enumerate(active_resources.keys()):
  382. if args.num_nodes == count:
  383. break
  384. updated_active_resources[hostname] = active_resources[hostname]
  385. active_resources = updated_active_resources
  386. if args.num_gpus > 0:
  387. updated_active_resources = collections.OrderedDict()
  388. for hostname in active_resources.keys():
  389. updated_active_resources[hostname] = list(range(args.num_gpus))
  390. active_resources = updated_active_resources
  391. if args.elastic_training:
  392. assert not args.no_local_rank, "--no_local_rank argument is not supported in Elastic training"
  393. # encode world info as base64 to make it easier to pass via command line
  394. world_info_base64 = encode_world_info(active_resources)
  395. multi_node_exec = args.force_multi or len(active_resources) > 1
  396. if not multi_node_exec:
  397. deepspeed_launch = [
  398. sys.executable, "-u", "-m", "deepspeed.launcher.launch", f"--world_info={world_info_base64}",
  399. f"--master_addr={args.master_addr}", f"--master_port={args.master_port}"
  400. ]
  401. if args.no_python:
  402. deepspeed_launch.append("--no_python")
  403. if args.module:
  404. deepspeed_launch.append("--module")
  405. if args.no_local_rank:
  406. deepspeed_launch.append("--no_local_rank")
  407. if args.save_pid:
  408. deepspeed_launch += ["--save_pid", f"{os.getpid()}"]
  409. if args.enable_each_rank_log:
  410. deepspeed_launch.append(f"--enable_each_rank_log={args.enable_each_rank_log}")
  411. if args.elastic_training:
  412. deepspeed_launch.append("--enable_elastic_training")
  413. deepspeed_launch.append(f"--max_elastic_nodes={args.max_elastic_nodes}")
  414. deepspeed_launch.append(f"--min_elastic_nodes={args.min_elastic_nodes}")
  415. if args.bind_cores_to_rank:
  416. deepspeed_launch.append("--bind_cores_to_rank")
  417. if args.bind_core_list is not None:
  418. deepspeed_launch.append(f"--bind_core_list={args.bind_core_list}")
  419. cmd = deepspeed_launch + [args.user_script] + args.user_args
  420. else:
  421. args.launcher = args.launcher.lower()
  422. if args.launcher == PDSH_LAUNCHER:
  423. runner = PDSHRunner(args, world_info_base64)
  424. elif args.launcher == OPENMPI_LAUNCHER:
  425. runner = OpenMPIRunner(args, world_info_base64, resource_pool)
  426. elif args.launcher == MPICH_LAUNCHER:
  427. runner = MPICHRunner(args, world_info_base64, resource_pool)
  428. elif args.launcher == IMPI_LAUNCHER:
  429. runner = IMPIRunner(args, world_info_base64, resource_pool)
  430. elif args.launcher == MVAPICH_LAUNCHER:
  431. runner = MVAPICHRunner(args, world_info_base64, resource_pool)
  432. elif args.launcher == SLURM_LAUNCHER:
  433. runner = SlurmRunner(args, world_info_base64, resource_pool)
  434. else:
  435. raise NotImplementedError(f"Unknown launcher {args.launcher}")
  436. if not runner.backend_exists():
  437. raise RuntimeError(f"launcher '{args.launcher}' not installed.")
  438. curr_path = os.path.abspath('.')
  439. if 'PYTHONPATH' in env:
  440. env['PYTHONPATH'] = curr_path + ":" + env['PYTHONPATH']
  441. else:
  442. env['PYTHONPATH'] = curr_path
  443. excluded_vars = []
  444. for exclude_key, var_list in EXCLUDE_ENVS.items():
  445. if exclude_key in env.keys():
  446. # key exists in launcher env -> var list should be used
  447. excluded_vars += var_list
  448. exports = ""
  449. for var in env.keys():
  450. if any([var.startswith(name) for name in EXPORT_ENVS]):
  451. if not any([var == name for name in excluded_vars]):
  452. runner.add_export(var, env[var])
  453. for environ_path in DEEPSPEED_ENVIRONMENT_PATHS:
  454. environ_file = DEEPSPEED_ENVIRONMENT_NAME
  455. # handle if users to enter path for `DS_ENV_FILE`
  456. if not os.path.isfile(environ_file):
  457. environ_file = os.path.join(environ_path, DEEPSPEED_ENVIRONMENT_NAME)
  458. if os.path.isfile(environ_file):
  459. logger.info(f"deepspeed_env file = {environ_file}")
  460. with open(environ_file, 'r') as fd:
  461. for var in fd.readlines():
  462. key, val = var.split('=', maxsplit=1)
  463. runner.add_export(key, val)
  464. if args.launcher == PDSH_LAUNCHER:
  465. cmd, kill_cmd, env = runner.get_cmd(env, active_resources)
  466. else:
  467. cmd = runner.get_cmd(env, active_resources)
  468. logger.info(f"cmd = {' '.join(cmd)}")
  469. result = subprocess.Popen(cmd, env=env)
  470. def sigkill_handler(signum, frame):
  471. result.send_signal(signal.SIGINT)
  472. time.sleep(0.1)
  473. result.send_signal(signal.SIGTERM)
  474. result_kill = subprocess.Popen(kill_cmd, env=env)
  475. result_kill.wait()
  476. time.sleep(1)
  477. sys.exit(1)
  478. if args.launcher == PDSH_LAUNCHER and multi_node_exec:
  479. signal.signal(signal.SIGINT, sigkill_handler)
  480. signal.signal(signal.SIGTERM, sigkill_handler)
  481. result.wait()
  482. # In case of failure must propagate the error-condition back to the caller (usually shell). The
  483. # actual error and traceback should have been printed in the subprocess, so in order to avoid
  484. # unnecessary noise we just quietly exit here with the same code as the subprocess
  485. if result.returncode > 0:
  486. sys.exit(result.returncode)
  487. if __name__ == "__main__":
  488. main()