|
| 1 | +# SPDX-License-Identifier: LGPL-3.0-or-later |
| 2 | +import os |
| 3 | +import site |
| 4 | +from functools import ( |
| 5 | + lru_cache, |
| 6 | +) |
| 7 | +from importlib.machinery import ( |
| 8 | + FileFinder, |
| 9 | +) |
| 10 | +from importlib.util import ( |
| 11 | + find_spec, |
| 12 | +) |
| 13 | +from pathlib import ( |
| 14 | + Path, |
| 15 | +) |
| 16 | +from sysconfig import ( |
| 17 | + get_path, |
| 18 | +) |
| 19 | +from typing import ( |
| 20 | + Optional, |
| 21 | +) |
| 22 | + |
| 23 | + |
| 24 | +@lru_cache |
| 25 | +def find_pytorch() -> Optional[str]: |
| 26 | + """Find PyTorch library. |
| 27 | +
|
| 28 | + Tries to find PyTorch in the order of: |
| 29 | +
|
| 30 | + 1. Environment variable `PYTORCH_ROOT` if set |
| 31 | + 2. The current Python environment. |
| 32 | + 3. user site packages directory if enabled |
| 33 | + 4. system site packages directory (purelib) |
| 34 | +
|
| 35 | + Considering the default PyTorch package still uses old CXX11 ABI, we |
| 36 | + cannot install it automatically. |
| 37 | +
|
| 38 | + Returns |
| 39 | + ------- |
| 40 | + str, optional |
| 41 | + PyTorch library path if found. |
| 42 | + """ |
| 43 | + if os.environ.get("DP_ENABLE_PYTORCH", "0") == "0": |
| 44 | + return None |
| 45 | + pt_spec = None |
| 46 | + |
| 47 | + if (pt_spec is None or not pt_spec) and os.environ.get("PYTORCH_ROOT") is not None: |
| 48 | + site_packages = Path(os.environ.get("PYTORCH_ROOT")).parent.absolute() |
| 49 | + pt_spec = FileFinder(str(site_packages)).find_spec("torch") |
| 50 | + |
| 51 | + # get pytorch spec |
| 52 | + # note: isolated build will not work for backend |
| 53 | + if pt_spec is None or not pt_spec: |
| 54 | + pt_spec = find_spec("torch") |
| 55 | + |
| 56 | + if not pt_spec and site.ENABLE_USER_SITE: |
| 57 | + # first search TF from user site-packages before global site-packages |
| 58 | + site_packages = site.getusersitepackages() |
| 59 | + if site_packages: |
| 60 | + pt_spec = FileFinder(site_packages).find_spec("torch") |
| 61 | + |
| 62 | + if not pt_spec: |
| 63 | + # purelib gets site-packages path |
| 64 | + site_packages = get_path("purelib") |
| 65 | + if site_packages: |
| 66 | + pt_spec = FileFinder(site_packages).find_spec("torch") |
| 67 | + |
| 68 | + # get install dir from spec |
| 69 | + try: |
| 70 | + pt_install_dir = pt_spec.submodule_search_locations[0] # type: ignore |
| 71 | + # AttributeError if ft_spec is None |
| 72 | + # TypeError if submodule_search_locations are None |
| 73 | + # IndexError if submodule_search_locations is an empty list |
| 74 | + except (AttributeError, TypeError, IndexError): |
| 75 | + pt_install_dir = None |
| 76 | + return pt_install_dir |
0 commit comments