| 1 |
import contextlib |
| 2 |
import ctypes |
| 3 |
import importlib |
| 4 |
import platform |
| 5 |
import textwrap |
| 6 |
from pathlib import Path |
| 7 |
from typing import TYPE_CHECKING |
| 8 |
|
| 9 |
from .utils import import_module_symbols |
| 10 |
|
| 11 |
|
| 12 |
def _preload_cuda_lib(module_name: str, lib_name: str): |
| 13 |
"""Preload a single library.""" |
| 14 |
try: |
| 15 |
module = importlib.import_module(module_name) |
| 16 |
except ImportError: |
| 17 |
return |
| 18 |
else: |
| 19 |
# TODO: update the logic to handle CUDA 13, |
| 20 |
# using as reference https://github.com/pytorch/pytorch/pull/163661. |
| 21 |
|
| 22 |
# Resolve the library directory robustly |
| 23 |
if module_file_path := getattr(module, "__file__", None): |
| 24 |
lib_dir = Path(module_file_path).parent |
| 25 |
elif paths := getattr(module, "__path__", None): |
| 26 |
# Implicit namespace packages have __path__ but no __file__ |
| 27 |
lib_dir = Path(list(paths)[0]) |
| 28 |
else: |
| 29 |
return |
| 30 |
# Find the first file matching the pattern |
| 31 |
if lib_path := next((lib_dir / "lib").glob(lib_name), None): |
| 32 |
with contextlib.suppress(OSError): |
| 33 |
ctypes.CDLL(str(lib_path)) |
| 34 |
|
| 35 |
|
| 36 |
def _preload_cuda_deps(): |
| 37 |
"""Preloads CUDA dependencies from pip packages on Linux.""" |
| 38 |
if platform.system() != "Linux": |
| 39 |
return |
| 40 |
cuda_libs = { |
| 41 |
"nvidia.cuda_runtime": "libcudart.so.*[0-9]", |
| 42 |
"nvidia.curand": "libcurand.so.*[0-9]", |
| 43 |
} |
| 44 |
for module_name, lib_glob in cuda_libs.items(): |
| 45 |
_preload_cuda_lib(module_name, lib_glob) |
| 46 |
|
| 47 |
|
| 48 |
_preload_cuda_deps() |
| 49 |
|
| 50 |
try: |
| 51 |
from . import _core |
| 52 |
except ImportError as e: |
| 53 |
raise RuntimeError( |
| 54 |
textwrap.dedent(""" |
| 55 |
Cannot import the C++ backend pycolmap._core. |
| 56 |
Make sure that you successfully install the package with |
| 57 |
$ python -m pip install pycolmap/ |
| 58 |
""") |
| 59 |
) from e |
| 60 |
|
| 61 |
# Type checkers cannot deal with dynamic manipulation of globals. |
| 62 |
# Instead, we use the same workaround as PyTorch. |
| 63 |
if TYPE_CHECKING: |
| 64 |
from ._core import * # noqa F403 |
| 65 |
|
| 66 |
__all__ = import_module_symbols( |
| 67 |
globals(), _core, exclude={"cost_functions", "pyceres"} |
| 68 |
) |
| 69 |
__all__.extend(["__version__", "__ceres_version__"]) |
| 70 |
|
| 71 |
__version__ = _core.__version__ |
| 72 |
__ceres_version__ = _core.__ceres_version__ |