|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
from __future__ import annotations |
|
|
|
|
|
import platform |
|
|
from _thread import interrupt_main |
|
|
from contextlib import contextmanager |
|
|
from glob import glob |
|
|
from os import path |
|
|
from threading import Timer |
|
|
from types import ModuleType |
|
|
|
|
|
import torch |
|
|
|
|
|
from monai.utils.module import get_torch_version_tuple, optional_import |
|
|
|
|
|
dir_path = path.dirname(path.realpath(__file__)) |
|
|
|
|
|
|
|
|
@contextmanager |
|
|
def timeout(time, message): |
|
|
timer = None |
|
|
try: |
|
|
timer = Timer(time, interrupt_main) |
|
|
timer.daemon = True |
|
|
timer.start() |
|
|
yield |
|
|
except KeyboardInterrupt as e: |
|
|
if timer is not None and timer.is_alive(): |
|
|
raise e |
|
|
raise TimeoutError(message) from e |
|
|
finally: |
|
|
if timer is not None: |
|
|
try: |
|
|
timer.cancel() |
|
|
finally: |
|
|
pass |
|
|
|
|
|
|
|
|
def load_module( |
|
|
module_name: str, defines: dict | None = None, verbose_build: bool = False, build_timeout: int = 300 |
|
|
) -> ModuleType: |
|
|
""" |
|
|
Handles the loading of c++ extension modules. |
|
|
|
|
|
Args: |
|
|
module_name: Name of the module to load. |
|
|
Must match the name of the relevant source directory in the `_extensions` directory. |
|
|
defines: Dictionary containing names and values of compilation defines. |
|
|
verbose_build: Set to true to enable build logging. |
|
|
build_timeout: Time in seconds before the build will throw an exception to prevent hanging. |
|
|
""" |
|
|
|
|
|
|
|
|
module_dir = path.join(dir_path, module_name) |
|
|
if not path.exists(module_dir): |
|
|
raise ValueError(f"No extension module named {module_name}") |
|
|
|
|
|
platform_str = f"_{platform.system()}_{platform.python_version()}_" |
|
|
platform_str += "".join(f"{v}" for v in get_torch_version_tuple()[:2]) |
|
|
|
|
|
if defines is not None: |
|
|
module_name = "_".join([module_name] + [f"{v}" for v in defines.values()]) |
|
|
|
|
|
|
|
|
source = glob(path.join(module_dir, "**", "*.cpp"), recursive=True) |
|
|
if torch.cuda.is_available(): |
|
|
source += glob(path.join(module_dir, "**", "*.cu"), recursive=True) |
|
|
platform_str += f"_{torch.version.cuda}" |
|
|
|
|
|
|
|
|
define_args = [] if not defines else [f"-D {key}={defines[key]}" for key in defines] |
|
|
|
|
|
|
|
|
|
|
|
with timeout(build_timeout, "Build appears to be blocked. Is there a stopped process building the same extension?"): |
|
|
load, _ = optional_import("torch.utils.cpp_extension", name="load") |
|
|
|
|
|
name = module_name + platform_str.replace(".", "_") |
|
|
module = load( |
|
|
name=name, sources=source, extra_cflags=define_args, extra_cuda_cflags=define_args, verbose=verbose_build |
|
|
) |
|
|
|
|
|
return module |
|
|
|