Debian Codegraph @

tests/xla_spawn.py

raw
1 # Copyright 2021 The HuggingFace Team. All rights reserved.
2 #
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
6 #
7 # http://www.apache.org/licenses/LICENSE-2.0
8 #
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
14
15 """
16 A simple launcher script for TPU training
17
18 Inspired by https://github.com/pytorch/pytorch/blob/master/torch/distributed/launch.py
19
20 ::
21 >>> python xla_spawn.py --num_cores=NUM_CORES_YOU_HAVE
22 YOUR_TRAINING_SCRIPT.py (--arg1 --arg2 --arg3 and all other
23 arguments of your training script)
24
25 """
26
27 import importlib
28 import sys
29 from argparse import REMAINDER, ArgumentParser
30 from pathlib import Path
31
32 import torch_xla.distributed.xla_multiprocessing as xmp
33 from torch_xla import device_count
34
35
36 def parse_args():
37 """
38 Helper function parsing the command line options
39 @retval ArgumentParser
40 """
41 parser = ArgumentParser(
42 description=(
43 "PyTorch TPU distributed training launch helper utility that will spawn up multiple distributed processes"
44 )
45 )
46
47 # Optional arguments for the launch helper
48 num_devices = device_count()
49 parser.add_argument(
50 "--num_cores",
51 type=int,
52 default=num_devices,
53 help="Number of TPU cores to use (1 or number of available devices).",
54 )
55
56 # positional
57 parser.add_argument(
58 "training_script",
59 type=str,
60 help=(
61 "The full path to the single TPU training "
62 "program/script to be launched in parallel, "
63 "followed by all the arguments for the "
64 "training script"
65 ),
66 )
67
68 # rest from the training program
69 parser.add_argument("training_script_args", nargs=REMAINDER)
70
71 return parser.parse_args()
72
73
74 def main():
75 args = parse_args()
76
77 # Import training_script as a module.
78 script_fpath = Path(args.training_script)
79 sys.path.append(str(script_fpath.parent.resolve()))
80 mod_name = script_fpath.stem
81 mod = importlib.import_module(mod_name)
82
83 # Patch sys.argv
84 sys.argv = [args.training_script] + args.training_script_args
85 num_cores = args.num_cores
86 if num_cores == device_count() and num_cores != 1:
87 # There is an error in xmp.spawn that causes it to fail when num_cores is specified and not 1, so we set it to
88 # None when it matches the number of devices.
89 num_cores = None
90 xmp.spawn(mod._mp_fn, args=(), nprocs=args.num_cores)
91
92
93 if __name__ == "__main__":
94 main()