|
4 | 4 | """ |
5 | 5 |
|
6 | 6 | import ctypes |
7 | | -import glob |
8 | | -import os |
9 | | -import sys |
10 | 7 | from dataclasses import dataclass |
11 | 8 | from typing import Any, Dict, List, Optional |
12 | 9 |
|
@@ -36,24 +33,25 @@ class Function: |
36 | 33 | argtypes: List[Any] |
37 | 34 |
|
38 | 35 |
|
39 | | -def get_pytorch_default_cudart_library_path() -> str: |
40 | | - # code borrowed from https://github.com/pytorch/pytorch/blob/1cae60a87e5bdda8bcf55724a862eeed98a9747e/torch/__init__.py#L284 # noqa |
41 | | - lib_folder = "cuda_runtime" |
42 | | - lib_name = "libcudart.so.*[0-9]" |
43 | | - lib_path = None |
44 | | - for path in sys.path: |
45 | | - nvidia_path = os.path.join(path, "nvidia") |
46 | | - if not os.path.exists(nvidia_path): |
47 | | - continue |
48 | | - candidate_lib_paths = glob.glob( |
49 | | - os.path.join(nvidia_path, lib_folder, "lib", lib_name)) |
50 | | - if candidate_lib_paths and not lib_path: |
51 | | - lib_path = candidate_lib_paths[0] |
52 | | - if lib_path: |
53 | | - break |
54 | | - if not lib_path: |
55 | | - raise ValueError(f"{lib_name} not found in the system path {sys.path}") |
56 | | - return lib_path |
| 36 | +def find_loaded_library(lib_name) -> Optional[str]: |
| 37 | + """ |
| 38 | + According to according to https://man7.org/linux/man-pages/man5/proc_pid_maps.5.html, |
| 39 | + the file `/proc/self/maps` contains the memory maps of the process, which includes the |
| 40 | + shared libraries loaded by the process. We can use this file to find the path of the |
| 41 | + a loaded library. |
| 42 | + """ # noqa |
| 43 | + found = False |
| 44 | + with open("/proc/self/maps") as f: |
| 45 | + for line in f: |
| 46 | + if lib_name in line: |
| 47 | + found = True |
| 48 | + break |
| 49 | + if not found: |
| 50 | + # the library is not loaded in the current process |
| 51 | + return None |
| 52 | + start = line.index("/") |
| 53 | + path = line[start:].strip() |
| 54 | + return path |
57 | 55 |
|
58 | 56 |
|
59 | 57 | class CudaRTLibrary: |
@@ -100,7 +98,9 @@ class CudaRTLibrary: |
100 | 98 |
|
101 | 99 | def __init__(self, so_file: Optional[str] = None): |
102 | 100 | if so_file is None: |
103 | | - so_file = get_pytorch_default_cudart_library_path() |
| 101 | + so_file = find_loaded_library("libcudart.so") |
| 102 | + assert so_file is not None, \ |
| 103 | + "libcudart.so is not loaded in the current process" |
104 | 104 | if so_file not in CudaRTLibrary.path_to_library_cache: |
105 | 105 | lib = ctypes.CDLL(so_file) |
106 | 106 | CudaRTLibrary.path_to_library_cache[so_file] = lib |
|
0 commit comments