torch_xla.py 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. # Copyright 2022 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. import importlib.metadata
  15. import subprocess
  16. import sys
  17. def install_xla(upgrade: bool = False):
  18. """
  19. Helper function to install appropriate xla wheels based on the `torch` version in Google Colaboratory.
  20. Args:
  21. upgrade (`bool`, *optional*, defaults to `False`):
  22. Whether to upgrade `torch` and install the latest `torch_xla` wheels.
  23. Example:
  24. ```python
  25. >>> from accelerate.utils import install_xla
  26. >>> install_xla(upgrade=True)
  27. ```
  28. """
  29. in_colab = False
  30. if "IPython" in sys.modules:
  31. in_colab = "google.colab" in str(sys.modules["IPython"].get_ipython())
  32. if in_colab:
  33. if upgrade:
  34. torch_install_cmd = ["pip", "install", "-U", "torch"]
  35. subprocess.run(torch_install_cmd, check=True)
  36. # get the current version of torch
  37. torch_version = importlib.metadata.version("torch")
  38. torch_version_trunc = torch_version[: torch_version.rindex(".")]
  39. xla_wheel = f"https://storage.googleapis.com/tpu-pytorch/wheels/colab/torch_xla-{torch_version_trunc}-cp37-cp37m-linux_x86_64.whl"
  40. xla_install_cmd = ["pip", "install", xla_wheel]
  41. subprocess.run(xla_install_cmd, check=True)
  42. else:
  43. raise RuntimeError("`install_xla` utility works only on google colab.")