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.

GDN HF: shared GCC discovery, readable JIT errors, gate tests (#181)

resynth5b6ebed8626e
diff --git a/exllamav3/modules/attention_fn/qdec_hip.py b/exllamav3/modules/attention_fn/qdec_hip.py
index a2eea03..e897747 100644
--- a/exllamav3/modules/attention_fn/qdec_hip.py
+++ b/exllamav3/modules/attention_fn/qdec_hip.py
@@ -139,9 +139,7 @@ def _compile(cfg, arch):
VPF=int(cfg.get("vpf", False)), SMM1=int(cfg.get("smm", 0)), SCALE=repr(float(cfg["scale"])) + "f")
extra = [f"-D{k}={v}" for k, v in defs.items()] + knob("EXL3_QDEC_HIP_FLAGS", "").split()
flags = ["--genco", f"--offload-arch={arch}", "-O3", "-ffp-contract=off", "--no-gpu-bundle-output"] + extra
- 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}")
+ flags += hip_compiler.gcc_flags()
src = open(_SRC, "rb").read()
tag = hashlib.sha1(src + " ".join(flags).encode() + b"\0" + hip_compiler.key().encode()).hexdigest()[:16]
path = os.path.join(_CACHE, f"qdec_hip_{arch}_{tag}.hsaco")
diff --git a/exllamav3/modules/attention_fn/qsa_prefill_hip.py b/exllamav3/modules/attention_fn/qsa_prefill_hip.py
index 5f583f7..08577fa 100644
--- a/exllamav3/modules/attention_fn/qsa_prefill_hip.py
+++ b/exllamav3/modules/attention_fn/qsa_prefill_hip.py
@@ -23,8 +23,7 @@ def compile_hsaco(defs = "", arch = "gfx1151", src_path = None, extra = ()):
require_proof(src_path, defs)
src = open(src_path, "rb").read()
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}")
+ flags += hip_compiler.gcc_flags()
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):
diff --git a/exllamav3/modules/dsv41_fn/ds41_pf.py b/exllamav3/modules/dsv41_fn/ds41_pf.py
index bb135be..4633ec8 100644
--- a/exllamav3/modules/dsv41_fn/ds41_pf.py
+++ b/exllamav3/modules/dsv41_fn/ds41_pf.py
@@ -12,9 +12,7 @@ _FUNCS = ("ds41_sparse_attn_pf", "ds41_gather_sum", "ds41_rope_rows")
def compile_hsaco(arch="gfx1151"):
src = open(_SRC, "rb").read()
flags = ["--genco", f"--offload-arch={arch}", "-O3", "-ffp-contract=off", "--no-gpu-bundle-output"]
- 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}")
+ flags += hip_compiler.gcc_flags()
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"ds41_pf_{arch}_{tag}.hsaco")
if not os.path.isfile(cache):
diff --git a/exllamav3/modules/dsv41_fn/dsv41_hip.py b/exllamav3/modules/dsv41_fn/dsv41_hip.py
index ea0d5f0..f4e57f8 100644
--- a/exllamav3/modules/dsv41_fn/dsv41_hip.py
+++ b/exllamav3/modules/dsv41_fn/dsv41_hip.py
@@ -23,9 +23,7 @@ def compile_hsaco(arch="gfx1151", src_path=None):
src_path = src_path or _SRC
src = open(src_path, "rb").read() + open(_HDR, "rb").read()
flags = ["--genco", f"--offload-arch={arch}", "-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}")
+ flags += hip_compiler.gcc_flags()
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"dsv41_{arch}_{tag}.hsaco")
if not os.path.isfile(cache):
diff --git a/exllamav3/modules/dsv41_fn/dsv41_moe.py b/exllamav3/modules/dsv41_fn/dsv41_moe.py
index 5020ed0..d1f7f9c 100644
--- a/exllamav3/modules/dsv41_fn/dsv41_moe.py
+++ b/exllamav3/modules/dsv41_fn/dsv41_moe.py
@@ -28,9 +28,7 @@ def _compile(arch):
src += open(os.path.join(_EXT, h), "rb").read()
flags = ["--genco", f"--offload-arch={arch}", "-O3", f"-I{os.path.join(_DIR, 'stub')}"]
flags += os.environ.get("DSV41_MOE_DEFS", "").split() # experiments: -DMV_VU=3 -DEXL3_MOE_VALU_W=8
- 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}")
+ flags += hip_compiler.gcc_flags()
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"dsv41moe_{arch}_{tag}.hsaco")
if not os.path.isfile(cache):
diff --git a/exllamav3/modules/gr_fn/gr_mix_hip.py b/exllamav3/modules/gr_fn/gr_mix_hip.py
index d392875..6be302f 100644
--- a/exllamav3/modules/gr_fn/gr_mix_hip.py
+++ b/exllamav3/modules/gr_fn/gr_mix_hip.py
@@ -16,8 +16,7 @@ def compile_hsaco(defs="", arch="gfx1151", src_path=None):
src_path = src_path or _SRC
src = open(src_path, "rb").read()
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}")
+ flags += hip_compiler.gcc_flags()
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):
diff --git a/exllamav3/modules/ple_fn/ple_hip.py b/exllamav3/modules/ple_fn/ple_hip.py
index 368ff56..a1bc7ec 100644
--- a/exllamav3/modules/ple_fn/ple_hip.py
+++ b/exllamav3/modules/ple_fn/ple_hip.py
@@ -19,9 +19,7 @@ def compile_hsaco(arch="gfx1151", src_path=None):
src_path = src_path or _SRC
src = open(src_path, "rb").read()
flags = ["--genco", f"--offload-arch={arch}", "-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}")
+ flags += hip_compiler.gcc_flags()
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):
diff --git a/exllamav3/util/hip_compiler.py b/exllamav3/util/hip_compiler.py
index a4cef7f..caa1e0c 100644
--- a/exllamav3/util/hip_compiler.py
+++ b/exllamav3/util/hip_compiler.py
@@ -7,11 +7,12 @@ the slow build. The path and `--version` string are recorded once per process; `
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
+import glob, hashlib, os, platform, re, shutil, subprocess, sys, sysconfig
FIX_LINE = "export EXL3_ROCM_SDK=$(rocm-sdk path --root)"
SLOW_COST = "prefill can be about 20 % slower"
_info = {}
+_gcc = {}
def _sdk_from_package():
@@ -83,6 +84,51 @@ def key():
return resolve()["key"]
+def _gcc_version_key(path):
+ return tuple(int(x) for x in re.findall(r"\d+", os.path.basename(path)))
+
+
+def gcc_install_dir():
+ """GCC installation directory for clang's --gcc-install-dir, or None when there is none.
+
+ EXL3_GCC_INSTALL_DIR when it names a directory, else the GCC on PATH, else the newest GCC tree
+ installed without the driver (slim images). The scan prefers a host-triplet tree so a cross
+ compiler under /usr/lib/gcc/<triple>/<version> cannot win on version alone. Cached per process:
+ the flag is part of every kernel cache tag, and the kernel loaders call this once per arch."""
+ if "dir" in _gcc:
+ return _gcc["dir"]
+ env = os.environ.get("EXL3_GCC_INSTALL_DIR")
+ if env:
+ if os.path.isdir(env):
+ _gcc["dir"] = env
+ return env
+ if not _gcc.get("warned"):
+ _gcc["warned"] = True
+ print(f" -- EXL3_GCC_INSTALL_DIR={env!r} is not a directory; probing gcc", flush=True)
+ try:
+ out = subprocess.run(["gcc", "-print-libgcc-file-name"], capture_output=True, text=True, timeout=10).stdout.strip()
+ d = os.path.dirname(out) if out else ""
+ if d and os.path.isdir(d):
+ _gcc["dir"] = d
+ return d
+ except Exception: # noqa: BLE001
+ pass
+ cands = []
+ for pattern in ("/usr/lib/gcc/*/*", "/usr/lib64/gcc/*/*", "/usr/lib/gcc-cross/*/*"):
+ cands += [d for d in glob.glob(pattern) if os.path.isfile(os.path.join(d, "libgcc.a"))]
+ host = platform.machine()
+ host_cands = [d for d in cands if host and host in os.path.dirname(d)]
+ found = max(host_cands or cands, key=_gcc_version_key) if cands else None
+ _gcc["dir"] = found
+ return found
+
+
+def gcc_flags():
+ """--gcc-install-dir flag for the JIT compilers, or [] when no GCC installation is found."""
+ d = gcc_install_dir()
+ return [f"--gcc-install-dir={d}"] if d else []
+
+
def describe():
i = resolve()
if not i["path"]:
@@ -109,3 +155,4 @@ def report(log=print):
def reset():
_info.clear()
+ _gcc.clear()
diff --git a/exllamav3/vendor/fla/__init__.py b/exllamav3/vendor/fla/__init__.py
index f249446..69bd69d 100644
--- a/exllamav3/vendor/fla/__init__.py
+++ b/exllamav3/vendor/fla/__init__.py
@@ -112,7 +112,7 @@ def chunk_gated_delta_rule_pf(q, k, v, g, beta, scale=None, initial_state=None,
try:
return chunk_gdn_hf(q, v, qn, kn, g, beta, scale, initial_state, output_final_state, ckpt=ckpt)
except Exception as e:
- print(f" -- EXL3_GDN_HF failed, Triton/HIP chain for the rest of the process: {e!r}", flush=True)
+ print(f" -- EXL3_GDN_HF failed, Triton/HIP chain for the rest of the process: {e}", flush=True)
if isinstance(ckpt, (list, tuple)) and len(ckpt) > 2:
# the fused chain below side-writes 2 rows (the HF kernel above takes 8): keep the two deepest, the others stay unwritten
ckpt = sorted(ckpt, key = lambda c: c["chunk"])[-2:]
diff --git a/exllamav3/vendor/fla/hip/gdn_fused_h_hip.py b/exllamav3/vendor/fla/hip/gdn_fused_h_hip.py
index 1336b1b..f18b53f 100644
--- a/exllamav3/vendor/fla/hip/gdn_fused_h_hip.py
+++ b/exllamav3/vendor/fla/hip/gdn_fused_h_hip.py
@@ -19,9 +19,7 @@ def _compile(defs, arch):
# hsaco path for these defines (compiled once, cached by source + flags hash); needs no GPU
src = open(_SRC, "rb").read()
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}")
+ flags += hip_compiler.gcc_flags()
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):
diff --git a/exllamav3/vendor/fla/hip/gdn_hf_hip.py b/exllamav3/vendor/fla/hip/gdn_hf_hip.py
index aeb8304..eb55b39 100644
--- a/exllamav3/vendor/fla/hip/gdn_hf_hip.py
+++ b/exllamav3/vendor/fla/hip/gdn_hf_hip.py
@@ -50,14 +50,25 @@ def supported(device=None):
def _gcc_flag():
- gcc = os.environ.get("EXL3_GCC_INSTALL_DIR")
- if not gcc:
- try:
- out = subprocess.run(["gcc", "-print-libgcc-file-name"], capture_output=True, text=True, timeout=10).stdout.strip()
- gcc = os.path.dirname(out) if out else ""
- except Exception: # noqa: BLE001
- gcc = ""
- return [f"--gcc-install-dir={gcc}"] if gcc and os.path.isdir(gcc) else []
+ """Shared GCC discovery (see hip_compiler.gcc_install_dir)."""
+ return hip_compiler.gcc_flags()
+
+
+def _compile_tail(lines, n=12):
+ """Last n lines, plus any error lines clang printed before them (its warning preamble would
+ otherwise fill the window)."""
+ if len(lines) <= n:
+ return lines
+ start = len(lines) - n
+ hits = [i for i, l in enumerate(lines[:start]) if "error:" in l or "fatal error" in l][-n:]
+ keep = sorted(set(hits) | set(range(start, len(lines))))
+ out, prev = [], None
+ for i in keep:
+ if prev is not None and i > prev + 1:
+ out.append("...")
+ out.append(lines[i])
+ prev = i
+ return out
def _load(device=None):
@@ -78,7 +89,7 @@ def _load(device=None):
except OSError:
pass
err = (r.stderr or r.stdout or b"").decode(errors="replace").strip().splitlines()
- raise RuntimeError(f"gdn_hf_hip: hipcc failed for {arch}:\n" + "\n".join(err[-12:]))
+ raise RuntimeError(f"gdn_hf_hip: hipcc failed for {arch}:\n" + "\n".join(_compile_tail(err)))
os.replace(tmp, cache)
lib = load_hip_runtime()
torch.cuda.init()
@@ -97,6 +108,9 @@ def _load(device=None):
def gdn_hf_ok(q_raw, v, qn, kn, g, beta, initial_state):
"""q_raw, v: views of the conv output row (q at column 0, v at column 2 H K, same token pitch); qn, kn [1, T, H, 128] bf16
contiguous (l2-normalized); g [1, T, HV] fp32 raw log decay (natural log, before the chunk cumsum); beta [1, T, HV]."""
+ # Process-wide on purpose: a JIT/module/launch failure is treated as a toolchain/driver
+ # problem, so it also disables other gfx11.5 devices on a mixed box (gfx12 never reaches
+ # _load because supported() already refuses it).
if os.environ.get("EXL3_GDN_HF", "1" if torch.version.hip else "0") != "1" or _state.get("fail"):
return False
if not supported(v.device):
diff --git a/exllamav3/vendor/fla/hip/kda_fused_h_hip.py b/exllamav3/vendor/fla/hip/kda_fused_h_hip.py
index 1c85cc2..3049a18 100644
--- a/exllamav3/vendor/fla/hip/kda_fused_h_hip.py
+++ b/exllamav3/vendor/fla/hip/kda_fused_h_hip.py
@@ -19,9 +19,7 @@ def _compile(defs, arch):
# hsaco path for these defines (compiled once, cached by source + flags hash); needs no GPU
src = open(_SRC, "rb").read()
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}")
+ flags += hip_compiler.gcc_flags()
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):
diff --git a/exllamav3/vendor/fla/hip/kda_hf_hip.py b/exllamav3/vendor/fla/hip/kda_hf_hip.py
index d81eef5..e80c5f6 100644
--- a/exllamav3/vendor/fla/hip/kda_hf_hip.py
+++ b/exllamav3/vendor/fla/hip/kda_hf_hip.py
@@ -20,9 +20,7 @@ def _load(defs=""):
arch = torch.cuda.get_device_properties(0).gcnArchName.split(":")[0]
src = open(_SRC, "rb").read()
flags = ["--genco", f"--offload-arch={arch}", "-O3", "-ffp-contract=off"] + [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}")
+ flags += hip_compiler.gcc_flags()
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_hf_{arch}_{tag}.hsaco")
if not os.path.isfile(cache):
diff --git a/tests/test_gdn_hf_cpu.py b/tests/test_gdn_hf_cpu.py
new file mode 100644
index 0000000..863c59f
--- /dev/null
+++ b/tests/test_gdn_hf_cpu.py
@@ -0,0 +1,88 @@
+"""CPU tests of the gdn_hf_hip device gate and the hipcc error tail.
+No GPU, no ROCm, no built extension (the package __init__ files are bypassed with empty namespace
+stubs while the module is imported, then removed)."""
+import importlib, sys, types
+from pathlib import Path
+from types import SimpleNamespace
+
+import pytest
+import torch
+
+ROOT = Path(__file__).resolve().parent.parent
+_PKGS = ["exllamav3", "exllamav3.util", "exllamav3.vendor", "exllamav3.vendor.fla", "exllamav3.vendor.fla.hip"]
+_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:
+ gdn_hf = importlib.import_module("exllamav3.vendor.fla.hip.gdn_hf_hip")
+finally:
+ for _n in _added:
+ sys.modules.pop(_n, None)
+
+
[email protected](autouse=True)
+def _clean_state():
+ gdn_hf._supported.clear()
+ yield
+ gdn_hf._supported.clear()
+
+
+def _dev(arch):
+ return SimpleNamespace(gcnArchName = f"{arch}:sramecc+:xnack-")
+
+
[email protected]("arch", ["gfx1150", "gfx1151", "gfx1152"])
+def test_supported_accepts_the_gfx115_family(monkeypatch, arch):
+ monkeypatch.setattr(torch.version, "hip", "7.2.0")
+ monkeypatch.setattr(torch.cuda, "current_device", lambda: 0)
+ monkeypatch.setattr(torch.cuda, "get_device_properties", lambda _index: _dev(arch))
+ assert gdn_hf.supported(0) is True
+
+
[email protected]("arch", ["gfx1200", "gfx1201", "gfx1100", "sm_90", "", "unknown"])
+def test_supported_rejects_other_archs(monkeypatch, arch):
+ monkeypatch.setattr(torch.version, "hip", "7.2.0")
+ monkeypatch.setattr(torch.cuda, "current_device", lambda: 0)
+ monkeypatch.setattr(torch.cuda, "get_device_properties", lambda _index: _dev(arch))
+ assert gdn_hf.supported(0) is False
+
+
+def test_supported_requires_hip(monkeypatch):
+ monkeypatch.setattr(torch.version, "hip", None)
+ monkeypatch.setattr(torch.cuda, "get_device_properties",
+ lambda _index: (_ for _ in ()).throw(AssertionError("probed without HIP")))
+ assert gdn_hf.supported(0) is False
+
+
+def test_supported_probes_once_per_device(monkeypatch):
+ probes = []
+ monkeypatch.setattr(torch.version, "hip", "7.2.0")
+ monkeypatch.setattr(torch.cuda, "current_device", lambda: 0)
+ monkeypatch.setattr(torch.cuda, "get_device_properties", lambda index: (probes.append(index), _dev("gfx1151"))[1])
+ assert gdn_hf.supported(0) is True
+ assert gdn_hf.supported(torch.device("cuda", 0)) is True
+ assert gdn_hf.supported("0") is True
+ assert probes == [0]
+
+
+def test_supported_probe_failure_is_false(monkeypatch):
+ monkeypatch.setattr(torch.version, "hip", "7.2.0")
+ monkeypatch.setattr(torch.cuda, "current_device", lambda: 0)
+ monkeypatch.setattr(torch.cuda, "get_device_properties",
+ lambda _index: (_ for _ in ()).throw(RuntimeError("no device")))
+ assert gdn_hf.supported(0) is False
+
+
+def test_compile_tail_short_output_is_unchanged():
+ lines = [f"line {i}" for i in range(5)]
+ assert gdn_hf._compile_tail(lines) == lines
+
+
+def test_compile_tail_keeps_an_error_before_the_tail():
+ lines = ["warning: noise"] * 30 + ["fatal error: 'cstdlib' file not found"] + ["note: context"] * 20
+ tail = gdn_hf._compile_tail(lines)
+ assert "fatal error: 'cstdlib' file not found" in tail
+ assert tail[-1] == lines[-1]
+ assert "..." in tail
diff --git a/tests/test_hip_compiler_cpu.py b/tests/test_hip_compiler_cpu.py
index c3f7cdf..e425a09 100644
--- a/tests/test_hip_compiler_cpu.py
+++ b/tests/test_hip_compiler_cpu.py
@@ -99,6 +99,56 @@ def test_key_depends_on_version(env, monkeypatch):
assert "clang version 23" in hip_compiler.describe() and str(b) in hip_compiler.describe()
+def test_gcc_install_dir_prefers_a_valid_env_dir(env, monkeypatch, tmp_path):
+ d = tmp_path / "gcc"; d.mkdir()
+ monkeypatch.setenv("EXL3_GCC_INSTALL_DIR", str(d))
+ monkeypatch.setattr(hip_compiler.subprocess, "run",
+ lambda *a, **k: (_ for _ in ()).throw(AssertionError("probed despite a valid env dir")))
+ assert hip_compiler.gcc_flags() == [f"--gcc-install-dir={d}"]
+
+
+def test_gcc_install_dir_probes_gcc_once_when_env_is_stale(env, monkeypatch, tmp_path, capsys):
+ d = tmp_path / "gcc"; d.mkdir(); (d / "libgcc.a").write_text("")
+ calls = []
+ monkeypatch.setenv("EXL3_GCC_INSTALL_DIR", str(tmp_path / "missing"))
+ monkeypatch.setattr(hip_compiler.subprocess, "run",
+ lambda *a, **k: (calls.append(a), types.SimpleNamespace(stdout = str(d / "libgcc.a")))[1])
+ assert hip_compiler.gcc_install_dir() == str(d)
+ assert hip_compiler.gcc_install_dir() == str(d) # cached after the first probe
+ assert len(calls) == 1
+ assert "not a directory" in capsys.readouterr().out
+
+
+def test_gcc_install_dir_scan_prefers_the_host_triple(env, monkeypatch, tmp_path):
+ root = tmp_path / "gcc"
+ old = root / "x86_64-linux-gnu" / "9"; old.mkdir(parents = True); (old / "libgcc.a").write_text("")
+ new = root / "x86_64-linux-gnu" / "13"; new.mkdir(); (new / "libgcc.a").write_text("")
+ cross = root / "aarch64-linux-gnu" / "14"; cross.mkdir(parents = True); (cross / "libgcc.a").write_text("")
+ monkeypatch.delenv("EXL3_GCC_INSTALL_DIR", raising = False)
+ monkeypatch.setattr(hip_compiler.subprocess, "run", lambda *a, **k: (_ for _ in ()).throw(FileNotFoundError()))
+ monkeypatch.setattr(hip_compiler.platform, "machine", lambda: "x86_64")
+ monkeypatch.setattr(hip_compiler.glob, "glob",
+ lambda pattern: [str(old), str(new), str(cross)] if pattern == "/usr/lib/gcc/*/*" else [])
+ assert hip_compiler.gcc_install_dir() == str(new)
+
+
+def test_gcc_install_dir_scan_falls_back_to_any_triple(env, monkeypatch, tmp_path):
+ cross = tmp_path / "gcc" / "aarch64-linux-gnu" / "14"; cross.mkdir(parents = True); (cross / "libgcc.a").write_text("")
+ monkeypatch.delenv("EXL3_GCC_INSTALL_DIR", raising = False)
+ monkeypatch.setattr(hip_compiler.subprocess, "run", lambda *a, **k: (_ for _ in ()).throw(FileNotFoundError()))
+ monkeypatch.setattr(hip_compiler.platform, "machine", lambda: "x86_64")
+ monkeypatch.setattr(hip_compiler.glob, "glob", lambda pattern: [str(cross)] if pattern == "/usr/lib/gcc/*/*" else [])
+ assert hip_compiler.gcc_install_dir() == str(cross)
+
+
+def test_gcc_install_dir_none_found(env, monkeypatch):
+ monkeypatch.delenv("EXL3_GCC_INSTALL_DIR", raising = False)
+ monkeypatch.setattr(hip_compiler.subprocess, "run", lambda *a, **k: (_ for _ in ()).throw(FileNotFoundError()))
+ monkeypatch.setattr(hip_compiler.glob, "glob", lambda pattern: [])
+ assert hip_compiler.gcc_install_dir() is None
+ assert hip_compiler.gcc_flags() == []
+
+
def test_version_recorded_once(env, monkeypatch):
log = env / "calls.log"
a = fake_hipcc(env / "a" / "hipcc", "clang X")
@@ -194,6 +244,7 @@ def test_every_jit_site_uses_the_resolver():
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
+ assert "hip_compiler.gcc_flags()" in s and "EXL3_GCC_INSTALL_DIR" not in s, f
import subprocess
out = subprocess.run(["grep", "-rl", "--include=*.py", "-e", "--genco", str(ROOT / "exllamav3")],
capture_output=True, text=True).stdout.split()