TPU.py 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. # Copyright 2020 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. A simple launcher script for TPU training
  16. Inspired by https://github.com/pytorch/pytorch/blob/master/torch/distributed/launch.py
  17. ::
  18. >>> python xla_spawn.py --num_cores=NUM_CORES_YOU_HAVE
  19. YOUR_TRAINING_SCRIPT.py (--arg1 --arg2 --arg3 and all other
  20. arguments of your training script)
  21. """
  22. import importlib
  23. import sys
  24. from argparse import REMAINDER, ArgumentParser
  25. from pathlib import Path
  26. import torch_xla.distributed.xla_multiprocessing as xmp
  27. def parse_args():
  28. """
  29. Helper function parsing the command line options
  30. @retval ArgumentParser
  31. """
  32. parser = ArgumentParser(
  33. description=(
  34. "PyTorch TPU distributed training launch "
  35. "helper utility that will spawn up "
  36. "multiple distributed processes"
  37. )
  38. )
  39. # Optional arguments for the launch helper
  40. parser.add_argument("--num_cores", type=int, default=1, help="Number of TPU cores to use (1 or 8).")
  41. # positional
  42. parser.add_argument(
  43. "training_script",
  44. type=str,
  45. help=(
  46. "The full path to the single TPU training "
  47. "program/script to be launched in parallel, "
  48. "followed by all the arguments for the "
  49. "training script"
  50. ),
  51. )
  52. # rest from the training program
  53. parser.add_argument("training_script_args", nargs=REMAINDER)
  54. return parser.parse_args()
  55. def main():
  56. args = parse_args()
  57. # Import training_script as a module.
  58. script_fpath = Path(args.training_script)
  59. sys.path.append(str(script_fpath.parent.resolve()))
  60. mod_name = script_fpath.stem
  61. mod = importlib.import_module(mod_name)
  62. # Patch sys.argv
  63. sys.argv = [args.training_script] + args.training_script_args + ["--tpu_num_cores", str(args.num_cores)]
  64. xmp.spawn(mod._mp_fn, args=(), nprocs=args.num_cores)
  65. if __name__ == "__main__":
  66. main()