runner.py 24 KB

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