Skip to content

Kyojin: open-source engine that runs 100 GB-class open models (GLM-5.3, Qwen3.8, DeepSeek V4.1) on one desktop machine. AMD Strix Halo, NVIDIA RTX and Apple Mac. OpenAI API, built on ExLlamaV3.

Find the HIP runtime torch already loaded when torch/lib has none

YanissAmze7a02894347b
diff --git a/exllamav3/modules/attention_fn/qsa_prefill_hip.py b/exllamav3/modules/attention_fn/qsa_prefill_hip.py
index 562fef1..2d0625c 100644
--- a/exllamav3/modules/attention_fn/qsa_prefill_hip.py
+++ b/exllamav3/modules/attention_fn/qsa_prefill_hip.py
@@ -1,7 +1,7 @@
"""Loader for qsa_prefill.hip (one wave per (row, kv head)). Same call shape as qsa_prefill.qsa_prefill_attend (fp16, shared or per-row block table)."""
import ctypes, hashlib, os, re, shutil, subprocess
import torch
-from exllamav3.util.hip_lib import find_hip_runtime
+from exllamav3.util.hip_lib import load_hip_runtime
_SRC = os.path.join(os.path.dirname(os.path.abspath(__file__)), "qsa_prefill.hip")
_state = {}
@@ -50,10 +50,7 @@ def hsaco_stats(path):
def _load(defs = ""):
if defs in _state: return _state[defs]
cache = compile_hsaco(defs, torch.cuda.get_device_properties(0).gcnArchName.split(":")[0])
- p = find_hip_runtime()
- if p is None: # the copy torch already loaded
- p = next(l.split()[-1] for l in open("/proc/self/maps") if "libamdhip64" in l)
- lib = ctypes.CDLL(p)
+ lib = load_hip_runtime()
torch.cuda.init()
mod = ctypes.c_void_p()
if lib.hipModuleLoad(ctypes.byref(mod), cache.encode()) != 0: raise RuntimeError("qsa_prefill_hip: hipModuleLoad failed")
diff --git a/exllamav3/util/hip_lib.py b/exllamav3/util/hip_lib.py
index d6dab64..8eb11bc 100644
--- a/exllamav3/util/hip_lib.py
+++ b/exllamav3/util/hip_lib.py
@@ -11,9 +11,32 @@ def _version_key(path: str):
return tuple(int(x) for x in re.findall(r"\d+", os.path.basename(path)[len(_NAME):]))
-def find_hip_runtime(lib_dir: str | None = None) -> str | None:
- """Path of libamdhip64 inside lib_dir (default: <torch>/lib), or None when there is none."""
- if lib_dir is None:
+def _loaded_hip_runtime(read_maps) -> str | None:
+ """Path of the libamdhip64 this process has already mapped (torch preloads it), or None."""
+ try:
+ lines = read_maps().splitlines()
+ except OSError:
+ return None
+ for line in lines:
+ parts = line.split(None, 5)
+ if len(parts) == 6 and os.path.basename(parts[5]).startswith(_NAME) and os.path.isabs(parts[5]):
+ return parts[5]
+ return None
+
+
+def _read_proc_maps() -> str:
+ with open("/proc/self/maps") as f:
+ return f.read()
+
+
+def find_hip_runtime(lib_dir: str | None = None, read_maps = _read_proc_maps) -> str | None:
+ """Path of libamdhip64 inside lib_dir (default: <torch>/lib), or None when there is none.
+
+ With the default lib_dir, a torch wheel that keeps the library elsewhere (AMD nightly: _rocm_sdk_core/lib,
+ preloaded at import) falls back to the copy this process has already mapped (read_maps: /proc/self/maps text).
+ """
+ default_dir = lib_dir is None
+ if default_dir:
import torch
lib_dir = os.path.join(os.path.dirname(torch.__file__), "lib")
plain = os.path.join(lib_dir, _NAME)
@@ -22,7 +45,12 @@ def find_hip_runtime(lib_dir: str | None = None) -> str | None:
versioned = [p for p in glob.glob(os.path.join(lib_dir, _NAME + ".*")) if os.path.isfile(p)
and re.fullmatch(r"(\.\d+)+", os.path.basename(p)[len(_NAME):])]
if not versioned:
- return None
+ loaded = _loaded_hip_runtime(read_maps) if default_dir else None
+ if loaded and loaded not in _logged:
+ _logged.add(loaded)
+ print(f"hip_lib: {_NAME} not found in {lib_dir}, using the copy torch already loaded: {loaded}",
+ file = sys.stderr, flush = True)
+ return loaded
best = max(versioned, key = _version_key)
if best not in _logged:
_logged.add(best)
diff --git a/tests/test_hip_lib.py b/tests/test_hip_lib.py
index 950a926..f9191a7 100644
--- a/tests/test_hip_lib.py
+++ b/tests/test_hip_lib.py
@@ -46,3 +46,47 @@ def test_none_when_absent_and_load_raises(tmp_path):
pass
else:
raise AssertionError("expected OSError")
+
+
+def _maps(*paths):
+ return "\n".join(f"7f00{i}000-7f00{i}fff r-xp 00000000 08:01 {i} {p}" for i, p in enumerate(paths)) + "\n"
+
+
+def _default_dir_find(maps):
+ import sys, types
+ fake = types.ModuleType("torch")
+ fake.__file__ = "/nonexistent/torch/__init__.py"
+ saved = sys.modules.get("torch")
+ sys.modules["torch"] = fake
+ err = io.StringIO()
+ try:
+ with contextlib.redirect_stderr(err):
+ return hip_lib.find_hip_runtime(read_maps = lambda: maps), err.getvalue()
+ finally:
+ if saved is None:
+ del sys.modules["torch"]
+ else:
+ sys.modules["torch"] = saved
+
+
+def test_default_dir_falls_back_to_the_mapped_library_and_logs_once():
+ hip_lib._logged.clear()
+ maps = _maps("/usr/lib/libc.so.6", "/venv/_rocm_sdk_core/lib/libamdhip64.so.7")
+ path, log = _default_dir_find(maps)
+ assert path == "/venv/_rocm_sdk_core/lib/libamdhip64.so.7"
+ assert log.count("\n") == 1 and "already loaded" in log
+ assert _default_dir_find(maps)[1] == ""
+
+
+def test_default_dir_none_when_nothing_is_mapped_or_maps_unreadable():
+ hip_lib._logged.clear()
+ assert _default_dir_find(_maps("/usr/lib/libc.so.6"))[0] is None
+
+ def boom():
+ raise OSError("no /proc")
+ assert hip_lib._loaded_hip_runtime(boom) is None
+
+
+def test_explicit_dir_never_uses_the_mapped_library(tmp_path):
+ hip_lib._logged.clear()
+ assert hip_lib.find_hip_runtime(str(tmp_path), read_maps = lambda: _maps("/x/libamdhip64.so.7")) is None