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.

Pick the rocm-sdk hipcc for JIT kernels by itself, key the kernel cache by compiler version, report the compiler at start-up

YanissAmz42b56f4a0a1f
diff --git a/doc/install.md b/doc/install.md
index 52460e8..cb65c6a 100644
--- a/doc/install.md
+++ b/doc/install.md
@@ -17,7 +17,7 @@ hf download yamz-labs/GLM-5.3-Flash-EXL3-Yamz --local-dir ./glm-pack
python tools/glm/serve.py --model ./glm-pack --port 8000 -c 131072 --num-draft 2
curl http://localhost:8000/v1/models
```
-In every new shell, before serving: activate the venv, run `export EXL3_ROCM_SDK=$(rocm-sdk path --root)` again, then `source tools/strix_halo/env.sh`. Without the export, `env.sh` falls back to a system ROCm that may not match the wheel (`undefined symbol: hsa_ext_image_create_v2`).
+In every new shell, before serving: activate the venv, run `export EXL3_ROCM_SDK=$(rocm-sdk path --root)` again, then `source tools/strix_halo/env.sh`. The engine builds some of its GPU kernels on first use, and the server prints at start which compiler it used. The SDK compiler from the export is the fast one; the server also finds it by itself when `rocm-sdk` is installed in the same venv, but the export is the safe way. If the log shows a warning that the system compiler is in use, prefill can be about 20 % slower, so export the line above and restart. Without the export, `env.sh` falls back to a system ROCm that may not match the wheel (`undefined symbol: hsa_ext_image_create_v2`).
If a step fails, see [troubleshooting.md](troubleshooting.md).
Status: build and MiMo serving were verified from a fresh clone on a second Strix Halo machine (build in 8 to 10 minutes). Both published packs were checked there against `SHA256SUMS` and served (one chat request each); `env.sh --check` has not been run there yet. The first request after a build is slow while the kernels warm up.
diff --git a/doc/troubleshooting.md b/doc/troubleshooting.md
index c6c88f2..ad553ea 100644
--- a/doc/troubleshooting.md
+++ b/doc/troubleshooting.md
@@ -26,6 +26,10 @@ To use another copy of the runtime, set `EXL3_HSA_LIB` to its path before sourci
If `env.sh` prints `[env.sh] WARNING: no libhsa-runtime64.so.1 found`, none of its candidates exist: set `EXL3_ROCM_SDK` or `EXL3_HSA_LIB` as above.
+## Prefill is about 20 % slower than the published figures
+
+The server prints one line at start, `[kyojin] HIP kernel compiler: ...`, and `/health` shows the same text (field `hip_compiler`). If it points to `/opt/rocm` or another system compiler and a `WARNING` line follows, the engine built its kernels with the system ROCm instead of the SDK compiler. Run `export EXL3_ROCM_SDK=$(rocm-sdk path --root)` and restart. The kernel cache is keyed by compiler version, so the new start rebuilds the kernels once; the old files stay in `~/.cache/exllamav3` and can be deleted by hand. Please include that line in a performance report.
+
## `HIP error: invalid device function` on every kernel
Cause: ROCm 6.4 or older. It has no code object for gfx1151.
diff --git a/exllamav3/modules/attention_fn/qsa_prefill_hip.py b/exllamav3/modules/attention_fn/qsa_prefill_hip.py
index 2d0625c..5f583f7 100644
--- a/exllamav3/modules/attention_fn/qsa_prefill_hip.py
+++ b/exllamav3/modules/attention_fn/qsa_prefill_hip.py
@@ -1,15 +1,13 @@
"""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 import hip_compiler
from exllamav3.util.hip_lib import load_hip_runtime
_SRC = os.path.join(os.path.dirname(os.path.abspath(__file__)), "qsa_prefill.hip")
_state = {}
def _hipcc():
- for p in (os.environ.get("EXL3_HIPCC"), os.path.join(os.environ.get("EXL3_ROCM_SDK", ""), "bin", "hipcc"),
- shutil.which("hipcc"), "/opt/rocm/bin/hipcc"):
- if p and os.path.isfile(p): return p
- raise RuntimeError("qsa_prefill_hip: hipcc not found (set EXL3_HIPCC)")
+ return hip_compiler.hipcc()
def proof_tag(src_path, defs):
return hashlib.sha1((open(src_path).read() + "\0" + " ".join(sorted(defs.split()))).encode()).hexdigest()[:16]
@@ -27,7 +25,7 @@ def compile_hsaco(defs = "", arch = "gfx1151", src_path = None, extra = ()):
flags = ["--genco", f"--offload-arch={arch}", "-O3", "-ffp-contract=off", "--no-gpu-bundle-output"] + list(extra) + [x if x.startswith("-") else f"-D{x}" for x in defs.split()]
gcc = os.environ.get("EXL3_GCC_INSTALL_DIR", "/usr/lib/gcc/x86_64-linux-gnu/13")
if os.path.isdir(gcc): flags.append(f"--gcc-install-dir={gcc}")
- tag = hashlib.sha1(src + " ".join(flags).encode()).hexdigest()[:16]
+ tag = hashlib.sha1(src + " ".join(flags).encode() + b"\0" + hip_compiler.key().encode()).hexdigest()[:16]
cache = os.path.join(os.path.expanduser("~/.cache/exllamav3"), f"qsa_pf_{arch}_{tag}.hsaco")
if not os.path.isfile(cache):
os.makedirs(os.path.dirname(cache), exist_ok = True)
diff --git a/exllamav3/modules/ple_fn/ple_hip.py b/exllamav3/modules/ple_fn/ple_hip.py
index 5f57e9b..368ff56 100644
--- a/exllamav3/modules/ple_fn/ple_hip.py
+++ b/exllamav3/modules/ple_fn/ple_hip.py
@@ -2,6 +2,7 @@
# hipcc genco (cached by source hash), launched through torch's libamdhip64 on the current stream.
import ctypes, hashlib, os, shutil, subprocess
import torch
+from exllamav3.util import hip_compiler
from exllamav3.util.hip_lib import load_hip_runtime
_SRC = os.path.join(os.path.dirname(os.path.abspath(__file__)), "ple_hip.hip")
@@ -11,13 +12,7 @@ _FUNCS = ("ple_rs", "ple_gate", "ple_norm_conv", "ple_copy_state", "ple_conv_out
def _hipcc():
- for p in (os.environ.get("EXL3_HIPCC"), os.path.join(os.environ.get("EXL3_ROCM_SDK", ""), "bin", "hipcc"),
- "$EXL3_ROOT",
- "$EXL3_ROOT",
- shutil.which("hipcc"), "/opt/rocm/bin/hipcc"):
- if p and os.path.isfile(p):
- return p
- raise RuntimeError("ple_hip: hipcc not found (set EXL3_HIPCC)")
+ return hip_compiler.hipcc()
def compile_hsaco(arch="gfx1151", src_path=None):
@@ -27,7 +22,7 @@ def compile_hsaco(arch="gfx1151", src_path=None):
gcc = os.environ.get("EXL3_GCC_INSTALL_DIR", "/usr/lib/gcc/x86_64-linux-gnu/13")
if os.path.isdir(gcc):
flags.append(f"--gcc-install-dir={gcc}")
- tag = hashlib.sha1(src + " ".join(flags).encode()).hexdigest()[:16]
+ tag = hashlib.sha1(src + " ".join(flags).encode() + b"\0" + hip_compiler.key().encode()).hexdigest()[:16]
cache = os.path.join(os.path.expanduser("~/.cache/exllamav3"), f"ple_{arch}_{tag}.hsaco")
if not os.path.isfile(cache):
os.makedirs(os.path.dirname(cache), exist_ok=True)
diff --git a/exllamav3/util/hip_compiler.py b/exllamav3/util/hip_compiler.py
new file mode 100644
index 0000000..a4cef7f
--- /dev/null
+++ b/exllamav3/util/hip_compiler.py
@@ -0,0 +1,111 @@
+"""One resolver for the hipcc that builds every JIT HIP kernel (qsa_pf, gr_mix, gdn_fused_h, kda_fused_h, ple).
+
+Order: $EXL3_HIPCC, $EXL3_ROCM_SDK/bin/hipcc, the rocm-sdk pip package of the running interpreter (found without any
+environment variable), hipcc on PATH, /opt/rocm/bin/hipcc. The SDK compiler (clang 23) builds prefill kernels about
+20 % faster than the system ROCm 7.2.4 compiler (clang 22), so a user who forgot the export must not silently get
+the slow build. The path and `--version` string are recorded once per process; `key()` is a short hash of the
+version string that the kernel cache names include, so a binary built by another compiler is never reused.
+No torch import here.
+"""
+import hashlib, os, shutil, subprocess, sys, sysconfig
+
+FIX_LINE = "export EXL3_ROCM_SDK=$(rocm-sdk path --root)"
+SLOW_COST = "prefill can be about 20 % slower"
+_info = {}
+
+
+def _sdk_from_package():
+ """Root of the rocm-sdk devel tree installed next to the running interpreter, or None. Cheap, never raises."""
+ try:
+ roots = {sysconfig.get_paths().get(k) for k in ("purelib", "platlib")}
+ roots |= {p for p in sys.path if p.endswith("site-packages")}
+ for r in sorted(x for x in roots if x):
+ d = os.path.join(r, "_rocm_sdk_devel")
+ if os.path.isfile(os.path.join(d, "bin", "hipcc")):
+ return d
+ tool = os.path.join(os.path.dirname(sys.executable), "rocm-sdk")
+ if os.path.isfile(tool):
+ out = subprocess.run([tool, "path", "--root"], capture_output=True, text=True, timeout=20).stdout.strip()
+ if out and os.path.isfile(os.path.join(out, "bin", "hipcc")):
+ return out
+ except Exception: # noqa: BLE001
+ pass
+ return None
+
+
+def _inside(path, root):
+ if not path or not root:
+ return False
+ p, r = os.path.realpath(path), os.path.realpath(root)
+ return p == r or p.startswith(r + os.sep)
+
+
+def _version(path):
+ try:
+ r = subprocess.run([path, "--version"], capture_output=True, text=True, timeout=30)
+ return " ".join((r.stdout or r.stderr).split())
+ except Exception as e: # noqa: BLE001
+ return f"unknown ({type(e).__name__})"
+
+
+def resolve():
+ """dict(path, version, key, sdk, sdk_ok, source), or path None when no hipcc exists. Cached per process."""
+ if _info:
+ return _info
+ env_sdk = os.environ.get("EXL3_ROCM_SDK")
+ found_sdk = _sdk_from_package()
+ cands = [("EXL3_HIPCC", os.environ.get("EXL3_HIPCC")),
+ ("EXL3_ROCM_SDK", os.path.join(env_sdk, "bin", "hipcc") if env_sdk else None),
+ ("rocm-sdk package", os.path.join(found_sdk, "bin", "hipcc") if found_sdk else None),
+ ("PATH", shutil.which("hipcc")), ("/opt/rocm", "/opt/rocm/bin/hipcc")]
+ path, source = None, None
+ for src, p in cands:
+ if p and os.path.isfile(p):
+ path, source = p, src
+ break
+ sdk = env_sdk if env_sdk and os.path.isdir(env_sdk) else found_sdk
+ ver = _version(path) if path else ""
+ _info.update(path=path, source=source, version=ver, sdk=sdk,
+ sdk_ok=bool(path) and (_inside(path, found_sdk) or _inside(path, env_sdk)),
+ key=hashlib.sha1(ver.encode()).hexdigest()[:8] if path else "nocc")
+ return _info
+
+
+def hipcc():
+ p = resolve()["path"]
+ if not p:
+ raise RuntimeError("hipcc not found (set EXL3_HIPCC, or: " + FIX_LINE + ")")
+ return p
+
+
+def key():
+ """Short hash of the compiler version string, for kernel cache keys."""
+ return resolve()["key"]
+
+
+def describe():
+ i = resolve()
+ if not i["path"]:
+ return "HIP kernel compiler: none found"
+ return f"HIP kernel compiler: {i['path']} (from {i['source']}): {i['version'][:160]}"
+
+
+def warning():
+ """One line when the kernels are not built by the rocm-sdk compiler the install guide names, else None."""
+ i = resolve()
+ if i["sdk_ok"]:
+ return None
+ what = "no hipcc found" if not i["path"] else f"kernels are built with {i['path']}, not the rocm-sdk compiler"
+ return f"WARNING: {what}; {SLOW_COST}. Fix: {FIX_LINE} (then restart)"
+
+
+def report(log=print):
+ """Start-up lines for the servers and bench: the compiler, plus the warning when it is the slow one."""
+ log("[kyojin] " + describe())
+ w = warning()
+ if w:
+ log("[kyojin] " + w)
+
+
+def reset():
+ _info.clear()
diff --git a/exllamav3/vendor/fla/hip/gdn_fused_h_hip.py b/exllamav3/vendor/fla/hip/gdn_fused_h_hip.py
index f8fbad3..1336b1b 100644
--- a/exllamav3/vendor/fla/hip/gdn_fused_h_hip.py
+++ b/exllamav3/vendor/fla/hip/gdn_fused_h_hip.py
@@ -4,6 +4,7 @@
import ctypes, hashlib, os, shutil, subprocess
import torch
+from exllamav3.util import hip_compiler
from exllamav3.util.hip_lib import load_hip_runtime
_SRC = os.path.join(os.path.dirname(os.path.abspath(__file__)), "gdn_fused_h.hip")
@@ -11,13 +12,7 @@ _state = {}
def _hipcc():
- for p in (os.environ.get("EXL3_HIPCC"),
- os.path.join(os.environ.get("EXL3_ROCM_SDK", ""), "bin", "hipcc"),
- "$EXL3_ROOT",
- shutil.which("hipcc"), "/opt/rocm/bin/hipcc"):
- if p and os.path.isfile(p):
- return p
- raise RuntimeError("gdn_fused_h_hip: hipcc not found (set EXL3_HIPCC)")
+ return hip_compiler.hipcc()
def _compile(defs, arch):
@@ -27,7 +22,7 @@ def _compile(defs, arch):
gcc = os.environ.get("EXL3_GCC_INSTALL_DIR", "/usr/lib/gcc/x86_64-linux-gnu/13")
if os.path.isdir(gcc):
flags.append(f"--gcc-install-dir={gcc}")
- tag = hashlib.sha1(src + " ".join(flags).encode()).hexdigest()[:16]
+ tag = hashlib.sha1(src + " ".join(flags).encode() + b"\0" + hip_compiler.key().encode()).hexdigest()[:16]
cache = os.path.join(os.path.expanduser("~/.cache/exllamav3"), f"gdn_fused_h_{arch}_{tag}.hsaco")
if not os.path.isfile(cache):
os.makedirs(os.path.dirname(cache), exist_ok=True)
diff --git a/exllamav3/vendor/fla/hip/kda_fused_h_hip.py b/exllamav3/vendor/fla/hip/kda_fused_h_hip.py
index 0494f47..4bcedcb 100644
--- a/exllamav3/vendor/fla/hip/kda_fused_h_hip.py
+++ b/exllamav3/vendor/fla/hip/kda_fused_h_hip.py
@@ -4,6 +4,7 @@
import ctypes, hashlib, os, shutil, subprocess
import torch
+from exllamav3.util import hip_compiler
from exllamav3.util.hip_lib import load_hip_runtime
_SRC = os.path.join(os.path.dirname(os.path.abspath(__file__)), "kda_fused_h.hip")
@@ -11,13 +12,7 @@ _state = {}
def _hipcc():
- for p in (os.environ.get("EXL3_HIPCC"),
- os.path.join(os.environ.get("EXL3_ROCM_SDK", ""), "bin", "hipcc"),
- "$EXL3_ROOT",
- shutil.which("hipcc"), "/opt/rocm/bin/hipcc"):
- if p and os.path.isfile(p):
- return p
- raise RuntimeError("kda_fused_h_hip: hipcc not found (set EXL3_HIPCC)")
+ return hip_compiler.hipcc()
def _compile(defs, arch):
@@ -27,7 +22,7 @@ def _compile(defs, arch):
gcc = os.environ.get("EXL3_GCC_INSTALL_DIR", "/usr/lib/gcc/x86_64-linux-gnu/13")
if os.path.isdir(gcc):
flags.append(f"--gcc-install-dir={gcc}")
- tag = hashlib.sha1(src + " ".join(flags).encode()).hexdigest()[:16]
+ tag = hashlib.sha1(src + " ".join(flags).encode() + b"\0" + hip_compiler.key().encode()).hexdigest()[:16]
cache = os.path.join(os.path.expanduser("~/.cache/exllamav3"), f"kda_fused_h_{arch}_{tag}.hsaco")
if not os.path.isfile(cache):
os.makedirs(os.path.dirname(cache), exist_ok=True)
diff --git a/gr/gr_mix_hip.py b/gr/gr_mix_hip.py
index f911bea..d392875 100644
--- a/gr/gr_mix_hip.py
+++ b/gr/gr_mix_hip.py
@@ -2,6 +2,7 @@
# launched through torch's libamdhip64 on the current stream (same method as gdn_fused_h_hip.py).
import ctypes, hashlib, os, shutil, subprocess
import torch
+from exllamav3.util import hip_compiler
from exllamav3.util.hip_lib import load_hip_runtime
_SRC = os.path.join(os.path.dirname(os.path.abspath(__file__)), "gr_mix.hip")
@@ -9,10 +10,7 @@ _state = {}
H, DD, RANK, NTOT, K1 = 4, 2560, 320, 324, 10240
def _hipcc():
- for p in (os.environ.get("EXL3_HIPCC"), os.path.join(os.environ.get("EXL3_ROCM_SDK", ""), "bin", "hipcc"),
- shutil.which("hipcc"), "/opt/rocm/bin/hipcc"):
- if p and os.path.isfile(p): return p
- raise RuntimeError("gr_mix_hip: hipcc not found (set EXL3_HIPCC)")
+ return hip_compiler.hipcc()
def compile_hsaco(defs="", arch="gfx1151", src_path=None):
src_path = src_path or _SRC
@@ -20,7 +18,7 @@ def compile_hsaco(defs="", arch="gfx1151", src_path=None):
flags = ["--genco", f"--offload-arch={arch}", "-O3", "-ffp-contract=off"] + [x if x.startswith("-") else f"-D{x}" for x in defs.split()]
gcc = os.environ.get("EXL3_GCC_INSTALL_DIR", "/usr/lib/gcc/x86_64-linux-gnu/13")
if os.path.isdir(gcc): flags.append(f"--gcc-install-dir={gcc}")
- tag = hashlib.sha1(src + " ".join(flags).encode()).hexdigest()[:16]
+ tag = hashlib.sha1(src + " ".join(flags).encode() + b"\0" + hip_compiler.key().encode()).hexdigest()[:16]
cache = os.path.join(os.path.expanduser("~/.cache/exllamav3"), f"gr_mix_{arch}_{tag}.hsaco")
if not os.path.isfile(cache):
os.makedirs(os.path.dirname(cache), exist_ok=True)
diff --git a/tests/test_hip_compiler_cpu.py b/tests/test_hip_compiler_cpu.py
new file mode 100644
index 0000000..3568c32
--- /dev/null
+++ b/tests/test_hip_compiler_cpu.py
@@ -0,0 +1,194 @@
+"""CPU tests of the shared JIT compiler resolver (exllamav3/util/hip_compiler.py) and of its use by the HIP loaders.
+Fake hipcc scripts on a temp tree; no GPU, no ROCm, no built extension (the package __init__ files are bypassed
+with empty namespace stubs while the modules are imported, then removed)."""
+import importlib, os, stat, sys, types
+from pathlib import Path
+import pytest
+
+ROOT = Path(__file__).resolve().parent.parent
+_PKGS = ["exllamav3", "exllamav3.util", "exllamav3.vendor", "exllamav3.vendor.fla", "exllamav3.vendor.fla.hip",
+ "exllamav3.modules", "exllamav3.modules.ple_fn", "gr"]
+_added = []
+for _n in _PKGS:
+ if _n not in sys.modules:
+ _m = types.ModuleType(_n); _m.__path__ = [str(ROOT.joinpath(*_n.split(".")))]
+ sys.modules[_n] = _m; _added.append(_n)
+try:
+ hip_compiler = importlib.import_module("exllamav3.util.hip_compiler")
+ LOADERS = {n: importlib.import_module(n) for n in (
+ "gr.gr_mix_hip", "exllamav3.vendor.fla.hip.gdn_fused_h_hip", "exllamav3.vendor.fla.hip.kda_fused_h_hip",
+ "exllamav3.modules.ple_fn.ple_hip")}
+finally:
+ for _n in _added:
+ sys.modules.pop(_n, None)
+_REAL_SDK_FROM_PACKAGE = hip_compiler._sdk_from_package
+
+
+def fake_hipcc(path: Path, version: str, log: Path | None = None) -> Path:
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_text(
+ "#!/bin/bash\n"
+ f'if [ "$1" = "--version" ]; then echo "{version}"; exit 0; fi\n'
+ + (f'echo "$0" >> {log}\n' if log else "")
+ + 'while [ $# -gt 0 ]; do if [ "$1" = "-o" ]; then echo built > "$2"; fi; shift; done\n')
+ path.chmod(path.stat().st_mode | stat.S_IEXEC)
+ return path
+
+
+def env(tmp_path, monkeypatch):
+ for k in ("EXL3_HIPCC", "EXL3_ROCM_SDK"):
+ monkeypatch.delenv(k, raising=False)
+ monkeypatch.setenv("HOME", str(tmp_path / "home"))
+ monkeypatch.setenv("PATH", str(tmp_path / "emptybin"))
+ monkeypatch.setattr(hip_compiler, "_sdk_from_package", lambda: None)
+ hip_compiler.reset()
+ yield tmp_path
+ hip_compiler.reset()
+
+
+def test_order_env_hipcc_first(env, monkeypatch):
+ a = fake_hipcc(env / "a" / "hipcc", "clang A")
+ sdk = env / "sdk"; fake_hipcc(sdk / "bin" / "hipcc", "clang SDK")
+ pkg = env / "pkg"; fake_hipcc(pkg / "bin" / "hipcc", "clang PKG")
+ fake_hipcc(env / "pathbin" / "hipcc", "clang PATH")
+ monkeypatch.setenv("PATH", str(env / "pathbin"))
+ monkeypatch.setattr(hip_compiler, "_sdk_from_package", lambda: str(pkg))
+ monkeypatch.setenv("EXL3_HIPCC", str(a)); monkeypatch.setenv("EXL3_ROCM_SDK", str(sdk))
+ assert hip_compiler.resolve()["path"] == str(a)
+ hip_compiler.reset(); monkeypatch.delenv("EXL3_HIPCC")
+ assert hip_compiler.resolve()["path"] == str(sdk / "bin" / "hipcc")
+ hip_compiler.reset(); monkeypatch.delenv("EXL3_ROCM_SDK")
+ r = hip_compiler.resolve()
+ assert r["path"] == str(pkg / "bin" / "hipcc") and r["source"] == "rocm-sdk package" and r["sdk_ok"]
+ hip_compiler.reset(); monkeypatch.setattr(hip_compiler, "_sdk_from_package", lambda: None)
+ r = hip_compiler.resolve()
+ assert r["path"] == str(env / "pathbin" / "hipcc") and r["source"] == "PATH" and not r["sdk_ok"]
+
+
+def test_package_sdk_found_without_env(env, monkeypatch):
+ # a fake site-packages with _rocm_sdk_devel next to the interpreter's purelib
+ sp = env / "site-packages"; fake_hipcc(sp / "_rocm_sdk_devel" / "bin" / "hipcc", "clang SDK")
+ monkeypatch.setattr(hip_compiler, "_sdk_from_package", _REAL_SDK_FROM_PACKAGE)
+ import sysconfig
+ monkeypatch.setattr(sysconfig, "get_paths", lambda *a, **k: {"purelib": str(sp), "platlib": str(sp)})
+ monkeypatch.setattr(sys, "path", [str(sp)] + sys.path)
+ hip_compiler.reset()
+ if True:
+ assert hip_compiler.resolve()["path"] == str(sp / "_rocm_sdk_devel" / "bin" / "hipcc")
+ assert hip_compiler.warning() is None
+
+
+def test_none_found_is_safe(env, monkeypatch):
+ monkeypatch.setattr(os.path, "isfile", lambda p: False)
+ assert hip_compiler.resolve()["path"] is None
+ assert "no hipcc found" in hip_compiler.warning()
+ with pytest.raises(RuntimeError, match="hipcc not found"):
+ hip_compiler.hipcc()
+
+
+def test_key_depends_on_version(env, monkeypatch):
+ a = fake_hipcc(env / "a" / "hipcc", "clang version 22")
+ b = fake_hipcc(env / "b" / "hipcc", "clang version 23")
+ monkeypatch.setenv("EXL3_HIPCC", str(a)); ka = hip_compiler.key()
+ hip_compiler.reset(); monkeypatch.setenv("EXL3_HIPCC", str(b)); kb = hip_compiler.key()
+ assert ka != kb and len(ka) == len(kb) == 8
+ assert "clang version 23" in hip_compiler.describe() and str(b) in hip_compiler.describe()
+
+
+def test_version_recorded_once(env, monkeypatch):
+ log = env / "calls.log"
+ a = fake_hipcc(env / "a" / "hipcc", "clang X")
+ a.write_text(a.read_text().replace('echo "clang X"', f'echo called >> {log}; echo "clang X"'))
+ monkeypatch.setenv("EXL3_HIPCC", str(a))
+ for _ in range(3):
+ hip_compiler.key(); hip_compiler.describe(); hip_compiler.warning()
+ assert log.read_text().count("called") == 1
+
+
+def test_warning_text(env, monkeypatch):
+ sdk = env / "sdk"
+ fake_hipcc(sdk / "bin" / "hipcc", "clang 23")
+ sysc = fake_hipcc(env / "opt" / "bin" / "hipcc", "clang 22")
+ monkeypatch.setenv("EXL3_ROCM_SDK", str(sdk))
+ assert hip_compiler.warning() is None
+ hip_compiler.reset(); monkeypatch.delenv("EXL3_ROCM_SDK"); monkeypatch.setenv("EXL3_HIPCC", str(sysc))
+ w = hip_compiler.warning()
+ assert w.count("\n") == 0 and "export EXL3_ROCM_SDK=$(rocm-sdk path --root)" in w and "about 20 % slower" in w
+ lines = []
+ hip_compiler.report(lines.append)
+ assert len(lines) == 2 and "HIP kernel compiler" in lines[0] and "WARNING" in lines[1]
+
+
[email protected]("modname,call", [
+ ("gr.gr_mix_hip", lambda m: m.compile_hsaco()),
+ ("exllamav3.vendor.fla.hip.gdn_fused_h_hip", lambda m: m._compile("", "gfx1151")),
+ ("exllamav3.vendor.fla.hip.kda_fused_h_hip", lambda m: m._compile("", "gfx1151")),
+ ("exllamav3.modules.ple_fn.ple_hip", lambda m: m.compile_hsaco()),
+])
+def test_cache_key_includes_compiler(env, monkeypatch, modname, call):
+ m = LOADERS[modname]
+ log = env / "calls.log"
+ a = fake_hipcc(env / "a" / "hipcc", "clang version 22", log)
+ b = fake_hipcc(env / "b" / "hipcc", "clang version 23", log)
+ monkeypatch.setenv("EXL3_HIPCC", str(a))
+ pa = call(m)
+ assert os.path.isfile(pa) and log.read_text().count("\n") == 1
+ call(m) # same compiler: cache hit, no second build
+ assert log.read_text().count("\n") == 1
+ # an "old" cache file (name without the compiler hash) is never reused: it is not the file the loader asks for
+ hip_compiler.reset(); monkeypatch.setenv("EXL3_HIPCC", str(b))
+ pb = call(m)
+ assert pb != pa and log.read_text().count("\n") == 2 and open(pa).read() == "built\n"
+ assert os.path.isfile(pa), "old files are not deleted"
+
+
+def test_old_cache_name_not_reused(env, monkeypatch):
+ import hashlib
+ m = LOADERS["gr.gr_mix_hip"]
+ log = env / "calls.log"
+ a = fake_hipcc(env / "a" / "hipcc", "clang version 22", log)
+ monkeypatch.setenv("EXL3_HIPCC", str(a))
+ # recompute the pre-fix name (no compiler hash) and plant a stale slow binary there
+ src = open(m._SRC, "rb").read()
+ flags = ["--genco", "--offload-arch=gfx1151", "-O3", "-ffp-contract=off"]
+ gcc = os.environ.get("EXL3_GCC_INSTALL_DIR", "/usr/lib/gcc/x86_64-linux-gnu/13")
+ if os.path.isdir(gcc): flags.append(f"--gcc-install-dir={gcc}")
+ old = Path(os.path.expanduser("~/.cache/exllamav3")) / f"gr_mix_gfx1151_{hashlib.sha1(src + ' '.join(flags).encode()).hexdigest()[:16]}.hsaco"
+ old.parent.mkdir(parents=True); old.write_text("slow")
+ got = m.compile_hsaco()
+ assert Path(got) != old and log.exists() and old.read_text() == "slow"
+
+
+def test_servers_wired():
+ for f in ("qwen", "glm", "mimo"):
+ s = (ROOT / "tools" / f / "serve.py").read_text()
+ assert "startup_health.report_compiler()" in s and "startup_health.compiler_health()" in s, f
+ assert "hip_compiler.report" in (ROOT / "tools/strix_halo/env.sh").read_text()
+ assert "Kernel compiler" in (ROOT / "tools/bench.py").read_text()
+
+
+def test_compiler_health_fields(env, monkeypatch):
+ sys.path.insert(0, str(ROOT / "tools"))
+ import startup_health
+ for n in ("exllamav3", "exllamav3.util"):
+ m = types.ModuleType(n); m.__path__ = [str(ROOT.joinpath(*n.split(".")))]
+ monkeypatch.setitem(sys.modules, n, m)
+ monkeypatch.setitem(sys.modules, "exllamav3.util.hip_compiler", hip_compiler)
+ monkeypatch.setattr(sys.modules["exllamav3.util"], "hip_compiler", hip_compiler, raising=False)
+ sysc = fake_hipcc(env / "opt" / "bin" / "hipcc", "clang 22")
+ monkeypatch.setenv("EXL3_HIPCC", str(sysc))
+ h = startup_health.compiler_health()
+ assert "clang 22" in h["hip_compiler"] and "20 %" in h["hip_compiler_warning"]
+
+
+def test_every_jit_site_uses_the_resolver():
+ sites = ["gr/gr_mix_hip.py", "exllamav3/vendor/fla/hip/gdn_fused_h_hip.py", "exllamav3/vendor/fla/hip/kda_fused_h_hip.py",
+ "exllamav3/modules/ple_fn/ple_hip.py", "exllamav3/modules/attention_fn/qsa_prefill_hip.py"]
+ for f in sites:
+ s = (ROOT / f).read_text()
+ assert "hip_compiler.hipcc()" in s and "hip_compiler.key()" in s and "EXL3_ROCM_SDK" not in s, f
+ import subprocess
+ out = subprocess.run(["grep", "-rl", "--include=*.py", "-e", "--genco", str(ROOT / "exllamav3"), str(ROOT / "gr")],
+ capture_output=True, text=True).stdout.split()
+ assert sorted(Path(o).relative_to(ROOT).as_posix() for o in out) == sorted(sites)
diff --git a/tools/bench.py b/tools/bench.py
index 4fdef7d..28e7ded 100755
--- a/tools/bench.py
+++ b/tools/bench.py
@@ -135,6 +135,16 @@ def ram_gib():
return "unknown"
+def server_compiler(base):
+ """(compiler line, warning or None) the server reports on /health (the server root, one level above /v1)."""
+ root = re.sub(r"/v1$", "", base)
+ try:
+ h = json.load(urllib.request.urlopen(root + "/health", timeout=10))
+ except Exception:
+ return "unknown", None
+ return h.get("hip_compiler") or "unknown (server does not report it)", h.get("hip_compiler_warning")
+
+
def rocm_version():
for f in ("/opt/rocm/.info/version", "/opt/rocm/.info/version-dev"):
if Path(f).is_file():
@@ -232,8 +242,11 @@ def main():
return f"{x:.1f}" if x is not None else "n/a"
ptok = int(statistics.median(n for n, _ in pf))
+ comp = server_compiler(base)
+ if comp[1]:
+ print(comp[1], file=sys.stderr)
info = {"model": model, "cpu": cpu_name(), "ram": ram_gib(), "gpu_target": gpu_name(), "kernel": platform.release(),
- "rocm": rocm_version(), "server": base, "date": time.strftime('%Y-%m-%d')}
+ "rocm": rocm_version(), "kernel_compiler": comp[0], "server": base, "date": time.strftime('%Y-%m-%d')}
prefill_med = med([t for _, t in pf])
lines = [
"### Kyojin benchmark",
@@ -244,6 +257,7 @@ def main():
f"- GPU target: {info['gpu_target']}",
f"- Kernel: {info['kernel']}",
f"- ROCm: {info['rocm']}",
+ f"- Kernel compiler: {info['kernel_compiler']}",
f"- Server: {info['server']}",
f"- Date: {info['date']}",
"",
diff --git a/tools/glm/serve.py b/tools/glm/serve.py
index 0c3d47c..e575cb7 100644
--- a/tools/glm/serve.py
+++ b/tools/glm/serve.py
@@ -483,7 +483,8 @@ def create_app(engine: Any, model_id: str, template: str) -> web.Application:
draft_tokens=proposed, accepted=accepted)
async def health(_: web.Request) -> web.Response:
- return web.json_response({"status": "ok", "source": "kyojin", "model": model_id})
+ return web.json_response({"status": "ok", "source": "kyojin", "model": model_id,
+ **startup_health.compiler_health()})
async def models(_: web.Request) -> web.Response:
return web.json_response({"object": "list", "data": [
@@ -848,6 +849,7 @@ def main() -> None:
tune = warm and float(os.environ.get("EXL3_SERVE_DTUNE_PRIME_S", "600")) > 0
stages = ["target weights", "drafter weights"] + (["warm-up"] if warm else []) + (["dense GEMM tuning"] if tune else [])
startup_health.start("glm", stages, args.host, args.port)
+ startup_health.report_compiler()
try:
engine = ResidentEngine(args.model, max_history=args.max_history or args.num_draft, max_ctx=args.max_ctx, num_draft=args.num_draft)
template = Path(args.chat_template or Path(args.model) / "chat_template.jinja").expanduser().read_text(encoding="utf-8")
diff --git a/tools/mimo/serve.py b/tools/mimo/serve.py
index b014699..9b6040c 100644
--- a/tools/mimo/serve.py
+++ b/tools/mimo/serve.py
@@ -396,6 +396,7 @@ def create_app(engine: Any, model_id: str, template: str) -> web.Application:
gate = None
return web.json_response({"status": "ok", "source": "kyojin", "model": model_id,
"generator": getattr(engine, "generator", None) is not None,
+ **startup_health.compiler_health(),
"spec_gate": gate})
async def worker() -> None:
@@ -801,6 +802,7 @@ def main() -> None:
stages = (["drafter weights"] if drafter else []) + ["target weights", "engine setup"]
startup_health.start("mimo", stages, args.host, args.port)
+ startup_health.report_compiler()
# --ctx 0 = the model's own max context, with the nested text_config handled like the GLM fix.
try:
probe = Config.from_directory(args.model)
diff --git a/tools/qwen/serve.py b/tools/qwen/serve.py
index 360f1ae..03e51d2 100644
--- a/tools/qwen/serve.py
+++ b/tools/qwen/serve.py
@@ -1182,7 +1182,7 @@ def create_app(engine: Any, model_id: str, template: str, defaults: dict[str, An
"max_context": getattr(engine, "ctx", None)}]})
async def health(_: web.Request) -> web.Response:
- return web.json_response({"status": "ok", "source": "kyojin", "model": model_id, "vision": bool(engine.supports_vision),
+ return web.json_response({"status": "ok", "source": "kyojin", "model": model_id, "vision": bool(engine.supports_vision), **startup_health.compiler_health(),
**(engine.spec_stats() if hasattr(engine, "spec_stats") else {})})
async def worker() -> None:
@@ -1752,6 +1752,7 @@ def main() -> None:
stages = ["target weights"] + (["drafter weights"] if args.draft_policy != "off" else []) \
+ (["vision tower"] if not args.no_vision else []) + ["engine setup", "warm-up"]
startup_health.start("qwen", stages, args.host, args.port)
+ startup_health.report_compiler()
try:
engine, template, defaults, model_dir, t0 = load_all(args)
except BaseException as exc: # noqa: BLE001
diff --git a/tools/startup_health.py b/tools/startup_health.py
index a3a072a..5f72ac3 100644
--- a/tools/startup_health.py
+++ b/tools/startup_health.py
@@ -231,6 +231,28 @@ def start(name: str, stages: list[str], host: str, port: int) -> StartupTracker:
return ACTIVE
+def compiler_health() -> dict:
+ """Fields for /health: the HIP kernel compiler line, plus the warning line when it is not the rocm-sdk compiler.
+ Lazy import: nothing here needs torch at import time."""
+ try:
+ from exllamav3.util import hip_compiler
+ out = {"hip_compiler": hip_compiler.describe().removeprefix("HIP kernel compiler: ")}
+ if hip_compiler.warning():
+ out["hip_compiler_warning"] = hip_compiler.warning()
+ return out
+ except Exception as e: # noqa: BLE001
+ return {"hip_compiler": f"unknown ({type(e).__name__})"}
+
+
+def report_compiler() -> None:
+ """Start-up log: which compiler builds the JIT kernels, plus one warning line when it is not the rocm-sdk one."""
+ try:
+ from exllamav3.util import hip_compiler
+ hip_compiler.report(lambda line: print(line, flush=True))
+ except Exception as e: # noqa: BLE001
+ print(f"[kyojin] HIP kernel compiler: unknown ({type(e).__name__}: {e})", flush=True)
+
+
def stage(name: str) -> None:
if ACTIVE is not None and name in ACTIVE.stages:
ACTIVE.begin(name)
diff --git a/tools/strix_halo/env.sh b/tools/strix_halo/env.sh
index 82b334d..9d7cf03 100755
--- a/tools/strix_halo/env.sh
+++ b/tools/strix_halo/env.sh
@@ -111,5 +111,7 @@ except ImportError as e:
print("exllamav3_ext: NOT BUILT --", e)
import exllamav3
print("exllamav3:", exllamav3.__version__ if hasattr(exllamav3, "__version__") else "imported")
+from exllamav3.util import hip_compiler
+hip_compiler.report(print)
PY
fi