Source code for monai_physio.warp_cudss_factor

"""Sparse direct factorization on the GPU with NVIDIA cuDSS, for Warp solvers.

:class:`WarpCuDssFactor` factors a SciPy CSR matrix once on the current Warp
stream and solves in place on Warp arrays. The cuDSS shared library is loaded
at run time; :meth:`WarpCuDssFactor.find_library` locates it.
"""

from __future__ import annotations

import ctypes
import ctypes.util
import os
import site
import sys
from pathlib import Path
from typing import Any, ClassVar

import numpy as np
import warp as wp
from scipy import sparse


[docs] class WarpCuDssFactor: """Sparse direct factorization on the GPU with NVIDIA cuDSS. The CSR matrix is analyzed and factored once on the current Warp stream. Each :meth:`solve` overwrites the persistent ``solution`` array from the persistent ``rhs`` array, so callers can fill and read them in place. Values, ``rhs`` and ``solution`` use ``dtype`` (Warp float32 or float64). """ MATRIX_TYPES: ClassVar[dict[str, int]] = {"general": 0, "symmetric": 1, "spd": 3} ANALYSIS, FACTORIZATION, SOLVE = 3, 4, 1008 VALUE_TYPES: ClassVar[dict[Any, int]] = {wp.float32: 0, wp.float64: 1}
[docs] @staticmethod def find_library() -> Path: """Locate the NVIDIA cuDSS shared library. ``CUDSS_LIBRARY`` names the library file explicitly. Otherwise the NVIDIA cuDSS Python wheels in site-packages and then the system library search path are used. Raises: RuntimeError: If cuDSS cannot be found. """ explicit = os.environ.get("CUDSS_LIBRARY") if explicit: if not Path(explicit).is_file(): raise RuntimeError(f"CUDSS_LIBRARY is not a file: {explicit}") return Path(explicit) pattern = "cudss64_*.dll" if os.name == "nt" else "libcudss.so*" for root in [*site.getsitepackages(), site.getusersitepackages()]: matches = sorted(Path(root, "nvidia").glob(f"**/{pattern}")) if matches: return matches[-1] found = ctypes.util.find_library("cudss64_1" if os.name == "nt" else "cudss") if found: return Path(found) import torch # NVIDIA publishes cuDSS wheels for CUDA 12 and 13 only. major = (torch.version.cuda or "").split(".")[0] if major in ("12", "13"): install = ( "Install the cuDSS wheel matching the CUDA version of the " f"installed torch (pip install nvidia-cudss-cu{major})" ) else: install = ( "cuDSS wheels (nvidia-cudss-cu12, nvidia-cudss-cu13) exist only " "for CUDA 12 and 13, and the installed torch is built for " f"{'CUDA ' + torch.version.cuda if torch.version.cuda else 'CPU'}; " "install a CUDA 12 or 13 torch build and the matching wheel" ) raise RuntimeError( f"NVIDIA cuDSS was not found. {install}, or set CUDSS_LIBRARY to the " "cuDSS shared library." )
[docs] def __init__( self, matrix: sparse.csr_matrix, matrix_type: str = "spd", dtype: Any = wp.float64, ) -> None: """Upload ``matrix`` and factor it. Args: matrix: Square CSR matrix with 32-bit indices. matrix_type: "general", "symmetric" or "spd". dtype: Value type, ``wp.float32`` or ``wp.float64``. """ library = self.find_library() self._directories: list[Any] = [] if sys.platform == "win32": folders = [library.parent] cuda = os.environ.get("CUDA_PATH") if cuda: folders += [Path(cuda, "bin"), Path(cuda, "bin", "x64")] for root in site.getsitepackages(): folders += [ p.parent for p in Path(root, "nvidia").glob("*/bin/**/*.dll") ] self._directories = [ os.add_dll_directory(str(folder)) for folder in dict.fromkeys(folders) if folder.is_dir() ] self.lib: Any = ctypes.CDLL(str(library)) p, i, q, z = ctypes.c_void_p, ctypes.c_int, ctypes.c_int64, ctypes.c_size_t signatures = { "cudssCreate": [ctypes.POINTER(p)], "cudssDestroy": [p], "cudssConfigCreate": [ctypes.POINTER(p)], "cudssConfigDestroy": [p], "cudssDataCreate": [p, ctypes.POINTER(p)], "cudssDataDestroy": [p, p], "cudssSetStream": [p, p], "cudssMatrixCreateCsr": [ctypes.POINTER(p), q, q, q, p, p, p, p] + [i] * 6, # offset/index/value types, matrix type, view, base "cudssMatrixCreateDn": [ctypes.POINTER(p), q, q, q, p, i, i], "cudssMatrixDestroy": [p], "cudssExecute": [p, i, p, p, p, p, p], "cudssDataGet": [p, p, i, p, z, ctypes.POINTER(z)], } for name, arguments in signatures.items(): getattr(self.lib, name).argtypes = arguments getattr(self.lib, name).restype = i self.handle, self.config, self.data = p(), p(), p() self.a, self.b, self.x = p(), p(), p() matrix = matrix.tocsr() self.n = int(matrix.shape[0]) self.offsets: Any = wp.array(matrix.indptr.astype(np.int32), dtype=wp.int32) self.columns: Any = wp.array(matrix.indices.astype(np.int32), dtype=wp.int32) self.values: Any = wp.array(matrix.data, dtype=dtype) self.rhs = wp.zeros(self.n, dtype=dtype) self.solution = wp.zeros(self.n, dtype=dtype) try: self._check("cudssCreate", ctypes.byref(self.handle)) self._check("cudssSetStream", self.handle, p(wp.get_stream().cuda_stream)) self._check("cudssConfigCreate", ctypes.byref(self.config)) self._check("cudssDataCreate", self.handle, ctypes.byref(self.data)) # Offsets and columns CUDA_R_32I=10, values CUDA_R_32F=0 or # CUDA_R_64F=1, full (not triangular) view, zero index base. self._check( "cudssMatrixCreateCsr", ctypes.byref(self.a), self.n, self.n, int(matrix.nnz), p(self.offsets.ptr), None, p(self.columns.ptr), p(self.values.ptr), 10, 10, self.VALUE_TYPES[dtype], self.MATRIX_TYPES[matrix_type], 0, 0, ) for handle, array in ((self.b, self.rhs), (self.x, self.solution)): self._check( "cudssMatrixCreateDn", ctypes.byref(handle), self.n, 1, self.n, p(array.ptr), self.VALUE_TYPES[dtype], 0, ) self._execute(self.ANALYSIS) self._execute(self.FACTORIZATION) wp.synchronize_device() self.check_info() except BaseException: self.close() raise
def _check(self, name: str, *arguments: Any) -> None: status = int(getattr(self.lib, name)(*arguments)) if status: raise RuntimeError(f"{name} failed with cuDSS status {status}") def _execute(self, phase: int) -> None: self._check( "cudssExecute", self.handle, phase, self.config, self.data, self.a, self.x, self.b, )
[docs] def solve(self) -> None: """Enqueue ``solution = A^-1 rhs`` on the current Warp stream.""" self._execute(self.SOLVE)
[docs] def check_info(self) -> None: """Raise if cuDSS reported a numerical error (call after synchronizing).""" info, written = ctypes.c_int(), ctypes.c_size_t() self._check( "cudssDataGet", self.handle, self.data, 0, ctypes.byref(info), ctypes.sizeof(info), ctypes.byref(written), ) if info.value: raise RuntimeError(f"cuDSS numerical info={info.value}")
[docs] def close(self) -> None: """Release native objects before their GPU buffers.""" for matrix in (self.x, self.b, self.a): if matrix.value: self.lib.cudssMatrixDestroy(matrix) matrix.value = None if self.data.value: self.lib.cudssDataDestroy(self.handle, self.data) self.data.value = None if self.config.value: self.lib.cudssConfigDestroy(self.config) self.config.value = None if self.handle.value: self.lib.cudssDestroy(self.handle) self.handle.value = None for directory in self._directories: directory.close() self._directories = []