Skip to content

Qwen3.8-Flash-Next on any consumer hardware: one-click install for Windows / Linux. Strata inference engine, OpenAI/Anthropic API on localhost, optional image input.

C++

Windows HIP: setup and the package put the whole dependency closure of amdhip64_7.dll and amd_comgr.dll beside strata.exe, and the engine says why the bundled runtime did not load (#461)

Niko12214b3ff7a1b4e7
diff --git a/setup.py b/setup.py
index 14d982ca3..e15612f8e 100644
--- a/setup.py
+++ b/setup.py
@@ -2142,21 +2142,40 @@ def hip_lib_dirs(eng: Path) -> list[Path]:
HIP_RUNTIME_DLLS = ("amdhip64_*.dll", "amd_comgr*.dll")
+def hip_runtime_closure(d: Path) -> list[str]:
+ """The DLLs of `d` (the engine's rocm/bin) that amdhip64_7.dll and amd_comgr.dll need, the two included, read from
+ their PE import tables and followed recursively (tools/hip/dll_closure.py). #461: amdhip64_7.dll imports
+ rocm_kpack.dll, which imports the MSVC runtime; with only the two DLLs beside strata.exe the full-path load fails
+ (error 126), Windows falls back to System32's copy of the runtime, and the first big prompt dies with
+ hipErrorInvalidDeviceFunction. Falls back to the names above when the helper cannot be read."""
+ roots = sorted({p.name for pat in HIP_RUNTIME_DLLS for p in d.glob(pat)})
+ try:
+ sys.path.insert(0, str(ROOT / "tools" / "hip"))
+ from dll_closure import dll_closure
+ return dll_closure(d, roots)
+ except Exception: # noqa: BLE001 - a missing helper must not stop setup
+ return roots
+ finally:
+ if str(ROOT / "tools" / "hip") in sys.path:
+ sys.path.remove(str(ROOT / "tools" / "hip"))
+
+
def hip_runtime_beside_exe(eng: Path) -> None:
- """Copy the bundled HIP runtime DLLs from rocm/bin next to the engine's exes when missing or different (a 0.1.34
- install, whose zip had them in rocm/bin only, is fixed on its next start)."""
+ """Copy the bundled HIP runtime DLLs and everything they import from rocm/bin next to the engine's exes when
+ missing or different (a 0.1.34 install, whose zip had them in rocm/bin only, is fixed on its next start; a
+ 0.1.40.2 install, which got only the two runtime DLLs, gets rocm_kpack.dll and the C++ runtime now, #461)."""
for d in hip_lib_dirs(eng):
- for pat in HIP_RUNTIME_DLLS:
- for src in d.glob(pat):
- dst = eng / src.name
- try:
- if dst.exists() and dst.stat().st_size == src.stat().st_size and \
- dst.stat().st_mtime >= src.stat().st_mtime:
- continue
- shutil.copy2(src, dst)
- except OSError as e: # e.g. the engine is running and holds the old copy
- warn(f"could not put {src.name} next to the AMD engine ({e}); if the engine stops on its first "
- "request, close Strata and run START-HERE.bat again")
+ for name in hip_runtime_closure(d):
+ src = d / name
+ dst = eng / src.name
+ try:
+ if dst.exists() and dst.stat().st_size == src.stat().st_size and \
+ dst.stat().st_mtime >= src.stat().st_mtime:
+ continue
+ shutil.copy2(src, dst)
+ except OSError as e: # e.g. the engine is running and holds the old copy
+ warn(f"could not put {src.name} next to the AMD engine ({e}); if the engine stops on its first "
+ "request, close Strata and run START-HERE.bat again")
def hip_match(card: dict, listed: list[dict], hip: list[dict]) -> dict | None:
diff --git a/src/program/generate.cpp b/src/program/generate.cpp
index a78d08860..5a01ac2ba 100644
--- a/src/program/generate.cpp
+++ b/src/program/generate.cpp
@@ -3972,11 +3972,25 @@ int main(int argc, char** argv) {
const size_t cut = beside.find_last_of("\\/");
beside = (cut == std::string::npos ? std::string() : beside.substr(0, cut + 1)) + "amdhip64_7.dll";
if (GetFileAttributesA(beside.c_str()) != INVALID_FILE_ATTRIBUTES &&
- _stricmp(beside.c_str(), path) != 0)
+ _stricmp(beside.c_str(), path) != 0) {
std::fprintf(stderr, "strata generate: WARNING: the HIP runtime in use is not the bundled one beside "
"the engine (%s): if prompts fail with hipErrorInvalidDeviceFunction, tell the "
"maintainers with this log (#1261)\n",
beside.c_str());
+ // #461: why the bundled one lost. Its imports (rocm_kpack.dll and the C++ runtime) must be beside the
+ // exe too; LoadLibraryEx on it with the search limited to its own folder says what is missing (126 =
+ // a dependency). A diagnostic only: the copy it loads is released at once and nothing is forced.
+ SetLastError(0);
+ HMODULE probe = LoadLibraryExA(beside.c_str(), nullptr,
+ LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR | LOAD_LIBRARY_SEARCH_DEFAULT_DIRS);
+ const DWORD le = probe != nullptr ? 0 : GetLastError();
+ if (probe != nullptr) FreeLibrary(probe);
+ std::fprintf(stderr, "strata generate: the bundled runtime beside the engine %s (GetLastError %lu)%s\n",
+ probe != nullptr ? "loads on its own" : "does NOT load", (unsigned long) le,
+ le == 126 ? ": a DLL it imports is missing from the engine's folder (rocm_kpack.dll, "
+ "msvcp140.dll, vcruntime140.dll, vcruntime140_1.dll); run START-HERE.bat "
+ "again (0.1.40.3 and later copy them)" : "");
+ }
}
}
}
diff --git a/tools/hip/dll_closure.py b/tools/hip/dll_closure.py
new file mode 100644
index 000000000..4a56f6a32
--- /dev/null
+++ b/tools/hip/dll_closure.py
@@ -0,0 +1,117 @@
+"""tools/hip/dll_closure.py - which DLLs a DLL needs, read from the PE import tables (no pefile, no objdump).
+
+ python tools/hip/dll_closure.py DIR amdhip64_7.dll amd_comgr.dll # prints the closure inside DIR
+
+Why: the Windows HIP engine puts amdhip64_7.dll and amd_comgr.dll next to strata.exe so that Windows binds THEM and not
+an AMD driver's copy in System32 (#468, #461). But amdhip64_7.dll itself imports rocm_kpack.dll, which imports the
+MSVC runtime; with only the two DLLs beside the exe the full-path load fails (error 126, ERROR_MOD_NOT_FOUND), Windows
+falls back to System32's copy, and the first big prompt dies with hipErrorInvalidDeviceFunction (#461, maraa081). So
+what goes beside the exe is the DLLs' whole dependency closure, computed here from the files actually shipped rather
+than from a list of names that goes stale with the next ROCm.
+
+A name is followed only when the DLL exists in `search_dir` (the bundle's rocm/bin). Everything else - kernel32,
+user32, setupapi, the api-ms-win-* forwarders - is a Windows system DLL and is left alone.
+"""
+from __future__ import annotations
+
+import struct
+import sys
+from pathlib import Path
+
+
+def pe_imports(path) -> list[str]:
+ """The DLL names in a PE file's import table and delay-import table, in file order. [] for a file that is not a
+ PE image (or is truncated): the caller treats it as a leaf."""
+ try:
+ data = Path(path).read_bytes()
+ except OSError:
+ return []
+ try:
+ if data[:2] != b"MZ":
+ return []
+ pe = struct.unpack_from("<I", data, 0x3C)[0]
+ if data[pe:pe + 4] != b"PE\0\0":
+ return []
+ nsec, = struct.unpack_from("<H", data, pe + 6)
+ opt_size, = struct.unpack_from("<H", data, pe + 20)
+ opt = pe + 24
+ magic, = struct.unpack_from("<H", data, opt)
+ dd = opt + (112 if magic == 0x20B else 96) # PE32+ : 112, PE32 : 96
+ secs = []
+ sec0 = opt + opt_size
+ for i in range(nsec):
+ o = sec0 + 40 * i
+ vsize, va, rsize, raw = struct.unpack_from("<IIII", data, o + 8)
+ secs.append((va, max(vsize, rsize), raw))
+
+ def off(rva):
+ for va, size, raw in secs:
+ if va <= rva < va + size:
+ return rva - va + raw
+ return None
+
+ def cstr(o):
+ e = data.index(b"\0", o)
+ return data[o:e].decode("ascii", "replace")
+
+ names: list[str] = []
+ imp_rva, = struct.unpack_from("<I", data, dd + 8 * 1) # directory 1: imports
+ o = off(imp_rva) if imp_rva else None
+ while o is not None:
+ name_rva = struct.unpack_from("<I", data, o + 12)[0]
+ if name_rva == 0:
+ break
+ n = off(name_rva)
+ if n is not None:
+ names.append(cstr(n))
+ o += 20
+ dly_rva, = struct.unpack_from("<I", data, dd + 8 * 13) # directory 13: delay imports
+ o = off(dly_rva) if dly_rva else None
+ while o is not None:
+ attrs, name_rva = struct.unpack_from("<II", data, o)
+ if name_rva == 0:
+ break
+ n = off(name_rva) # (RVA form, attrs bit 0)
+ if n is not None:
+ names.append(cstr(n))
+ o += 32
+ return names
+ except (struct.error, ValueError, IndexError):
+ return []
+
+
+def dll_closure(search_dir, roots, imports=pe_imports) -> list[str]:
+ """`roots` (file names inside `search_dir`) plus every DLL in `search_dir` they import, followed recursively.
+ The names are returned as spelled on disk, roots first, the rest in discovery order. A root that is not in the
+ directory is skipped; an import that is not in the directory (a Windows system DLL) is not followed."""
+ d = Path(search_dir)
+ on_disk = {p.name.lower(): p.name for p in d.iterdir() if p.is_file() and p.suffix.lower() == ".dll"} \
+ if d.is_dir() else {}
+ out: list[str] = []
+ todo = [r for r in roots]
+ seen: set[str] = set()
+ while todo:
+ name = todo.pop(0)
+ low = name.lower()
+ if low in seen or low not in on_disk:
+ continue
+ seen.add(low)
+ real = on_disk[low]
+ out.append(real)
+ for dep in imports(d / real):
+ if dep.lower() not in seen:
+ todo.append(dep)
+ return out
+
+
+def main() -> int:
+ if len(sys.argv) < 3:
+ print(__doc__)
+ return 2
+ for n in dll_closure(sys.argv[1], sys.argv[2:]):
+ print(n)
+ return 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/tools/hip/package_windows.py b/tools/hip/package_windows.py
index 1ece8f0d8..a2104e814 100644
--- a/tools/hip/package_windows.py
+++ b/tools/hip/package_windows.py
@@ -7,7 +7,7 @@
tools/hip/build_windows.bat runs it after the build. The zip holds:
strata.exe, strata-device.exe, BUILD.json (backend "hip", the archs, the ROCm and hipBLASLt versions)
- amdhip64_7.dll, amd_comgr.dll the HIP runtime beside the exes too (#468 #461: before System32)
+ amdhip64_7.dll, amd_comgr.dll + what they import the HIP runtime beside the exes too (#468 #461: before System32)
rocm/bin/*.dll the ROCm DLLs the two programs load (their import tables, followed
through the ROCm DLLs, + amd_comgr.dll, which the HIP runtime loads
by name) and the Microsoft C++ runtime they import
@@ -108,9 +108,13 @@ def main() -> int:
# #468 #461: the HIP runtime (and the compiler it loads by name) next to the exes as well - Windows searches the
# exe's folder before System32, where an AMD driver may install its own amdhip64_7.dll (found before PATH's
# rocm/bin); rocBLAS/hipBLASLt stay in rocm/bin, which they resolve their kernel libraries and ../.kpack from
- for pat in ("amdhip64_*.dll", "amd_comgr*.dll"):
- for f in (stage / "rocm" / "bin").glob(pat):
- shutil.copy2(f, stage / f.name)
+ # #461: and everything those two import (amdhip64_7.dll needs rocm_kpack.dll and the C++ runtime, or its full-path
+ # load fails with error 126 and Windows falls back to System32's copy): the closure of their PE import tables
+ sys.path.insert(0, str(Path(__file__).resolve().parent))
+ from dll_closure import dll_closure
+ roots = sorted(f.name for pat in ("amdhip64_*.dll", "amd_comgr*.dll") for f in (stage / "rocm" / "bin").glob(pat))
+ for name in dll_closure(stage / "rocm" / "bin", roots):
+ shutil.copy2(stage / "rocm" / "bin" / name, stage / name)
# the GEMM kernels and the libraries' own device code, for these archs
lib = stage / "rocm" / "bin" / "rocblas" / "library"
diff --git a/tools/test_dll_closure.py b/tools/test_dll_closure.py
new file mode 100644
index 000000000..5d4e4ca9b
--- /dev/null
+++ b/tools/test_dll_closure.py
@@ -0,0 +1,155 @@
+"""#461: the DLLs the Windows HIP runtime needs beside strata.exe, from the PE import tables.
+
+ python tools/test_dll_closure.py (the real-zip test skips when the 0.1.40.2 HIP zip is not here)
+
+Covers tools/hip/dll_closure.py and setup.hip_runtime_beside_exe on a fake engine folder.
+"""
+import os
+import struct
+import sys
+import tempfile
+import unittest
+import zipfile
+from pathlib import Path
+from unittest import mock
+
+ROOT = Path(__file__).resolve().parent.parent
+sys.path.insert(0, str(ROOT / "tools" / "hip"))
+sys.path.insert(0, str(ROOT))
+
+import dll_closure as dc # noqa: E402
+import setup # noqa: E402
+
+
+def fake_pe(imports, delay=()):
+ """A minimal PE32+ image whose import table (and delay-import table) names `imports` (`delay`)."""
+ text = bytearray()
+ va = 0x1000
+
+ def add_str(s):
+ off = len(text)
+ text.extend(s.encode() + b"\0")
+ return va + off
+
+ names = [add_str(n) for n in imports]
+ dnames = [add_str(n) for n in delay]
+ while len(text) % 8:
+ text.append(0)
+ imp_off = len(text)
+ for rva in names:
+ text.extend(struct.pack("<IIIII", 0, 0, 0, rva, 0))
+ text.extend(b"\0" * 20)
+ dly_off = len(text)
+ for rva in dnames:
+ text.extend(struct.pack("<IIIIIIII", 1, rva, 0, 0, 0, 0, 0, 0))
+ text.extend(b"\0" * 32)
+ opt_size = 112 + 16 * 8
+ pe = 0x80
+ hdr = bytearray(0x200)
+ hdr[0:2] = b"MZ"
+ struct.pack_into("<I", hdr, 0x3C, pe)
+ hdr[pe:pe + 4] = b"PE\0\0"
+ struct.pack_into("<HHIIIHH", hdr, pe + 4, 0x8664, 1, 0, 0, 0, opt_size, 0x2022)
+ opt = pe + 24
+ struct.pack_into("<H", hdr, opt, 0x20B)
+ dd = opt + 112
+ struct.pack_into("<II", hdr, dd + 8 * 1, va + imp_off, 20 * (len(names) + 1))
+ struct.pack_into("<II", hdr, dd + 8 * 13, va + dly_off, 32 * (len(dnames) + 1))
+ sec = opt + opt_size
+ hdr[sec:sec + 8] = b".idata\0\0"
+ struct.pack_into("<IIII", hdr, sec + 8, len(text), va, len(text), 0x200)
+ return bytes(hdr) + bytes(text)
+
+
+class Closure(unittest.TestCase):
+ def test_reads_imports_and_delay_imports(self):
+ with tempfile.TemporaryDirectory() as d:
+ f = Path(d) / "a.dll"
+ f.write_bytes(fake_pe(["KERNEL32.dll", "b.dll"], delay=["c.dll"]))
+ self.assertEqual(dc.pe_imports(f), ["KERNEL32.dll", "b.dll", "c.dll"])
+
+ def test_not_a_pe_is_a_leaf(self):
+ with tempfile.TemporaryDirectory() as d:
+ f = Path(d) / "a.dll"
+ f.write_bytes(b"hip-3686")
+ self.assertEqual(dc.pe_imports(f), [])
+ self.assertEqual(dc.pe_imports(Path(d) / "missing.dll"), [])
+
+ def test_follows_only_what_is_shipped(self):
+ with tempfile.TemporaryDirectory() as d:
+ d = Path(d)
+ (d / "AmdHip64_7.dll").write_bytes(fake_pe(["KERNEL32.dll", "ROCM_KPACK.dll", "SETUPAPI.dll"]))
+ (d / "rocm_kpack.dll").write_bytes(fake_pe(["MSVCP140.dll", "VCRUNTIME140.dll", "kernel32.dll"]))
+ (d / "msvcp140.dll").write_bytes(fake_pe(["VCRUNTIME140.dll", "api-ms-win-crt-heap-l1-1-0.dll"]))
+ (d / "vcruntime140.dll").write_bytes(fake_pe(["KERNEL32.dll"]))
+ (d / "amd_comgr.dll").write_bytes(fake_pe(["msvcp140.dll"]))
+ (d / "hipblas.dll").write_bytes(fake_pe(["amdhip64_7.dll", "rocblas.dll"])) # not a root: left out
+ got = dc.dll_closure(d, ["AmdHip64_7.dll", "amd_comgr.dll", "not_there.dll"])
+ self.assertEqual(sorted(x.lower() for x in got),
+ ["amd_comgr.dll", "amdhip64_7.dll", "msvcp140.dll", "rocm_kpack.dll", "vcruntime140.dll"])
+ self.assertEqual(got[:2], ["AmdHip64_7.dll", "amd_comgr.dll"]) # roots first, as spelled
+
+ def test_cycle_terminates(self):
+ with tempfile.TemporaryDirectory() as d:
+ d = Path(d)
+ (d / "a.dll").write_bytes(fake_pe(["b.dll"]))
+ (d / "b.dll").write_bytes(fake_pe(["a.dll"]))
+ self.assertEqual(dc.dll_closure(d, ["a.dll"]), ["a.dll", "b.dll"])
+
+ ZIP = ROOT.parent / "release" / "z04002" / "strata-windows-x64-hip.zip"
+
+ @unittest.skipUnless(ZIP.exists(), "the 0.1.40.2 HIP zip is not here")
+ def test_real_zip(self):
+ """The reporter's finding: amdhip64_7.dll needs rocm_kpack.dll and the MSVC runtime, which the 0.1.40.2 setup
+ did not put beside strata.exe."""
+ with tempfile.TemporaryDirectory() as d, zipfile.ZipFile(self.ZIP) as z:
+ for n in z.namelist():
+ if n.startswith("rocm/bin/") and n.endswith(".dll"):
+ z.extract(n, d)
+ got = dc.dll_closure(Path(d) / "rocm" / "bin", ["amdhip64_7.dll", "amd_comgr.dll"])
+ self.assertEqual(sorted(got), ["amd_comgr.dll", "amdhip64_7.dll", "msvcp140.dll", "rocm_kpack.dll",
+ "vcruntime140.dll", "vcruntime140_1.dll"])
+ self.assertNotIn("hipblas.dll", got) # strata.exe loads that one from rocm/bin by PATH
+
+
+class SetupCopy(unittest.TestCase):
+ def test_copies_the_closure_not_the_rest(self):
+ import json
+ with tempfile.TemporaryDirectory() as d:
+ eng = Path(d)
+ rb = eng / "rocm" / "bin"
+ rb.mkdir(parents=True)
+ (eng / "BUILD.json").write_text(json.dumps({"backend": "hip", "lib_dirs": ["rocm/bin"]}))
+ (rb / "amdhip64_7.dll").write_bytes(fake_pe(["KERNEL32.dll", "rocm_kpack.dll"]))
+ (rb / "rocm_kpack.dll").write_bytes(fake_pe(["MSVCP140.dll", "VCRUNTIME140.dll", "VCRUNTIME140_1.dll"]))
+ for n in ("msvcp140.dll", "vcruntime140.dll", "vcruntime140_1.dll"):
+ (rb / n).write_bytes(fake_pe(["KERNEL32.dll"]))
+ (rb / "amd_comgr.dll").write_bytes(fake_pe(["msvcp140.dll"]))
+ (rb / "rocblas.dll").write_bytes(fake_pe(["amdhip64_7.dll"]))
+ (rb / "hipblas.dll").write_bytes(fake_pe(["rocblas.dll"]))
+ # a 0.1.40.2 install: the two runtime DLLs beside the exe, and nothing else
+ (eng / "amdhip64_7.dll").write_bytes((rb / "amdhip64_7.dll").read_bytes())
+ with mock.patch.object(setup, "warn", lambda *a: None):
+ setup.hip_runtime_beside_exe(eng)
+ beside = sorted(p.name for p in eng.glob("*.dll"))
+ self.assertEqual(beside, ["amd_comgr.dll", "amdhip64_7.dll", "msvcp140.dll", "rocm_kpack.dll",
+ "vcruntime140.dll", "vcruntime140_1.dll"])
+ self.assertFalse((eng / "rocblas.dll").exists())
+ self.assertFalse((eng / "hipblas.dll").exists())
+ before = {p.name: p.stat().st_mtime_ns for p in eng.glob("*.dll")}
+ with mock.patch.object(setup, "warn", lambda *a: None):
+ setup.hip_runtime_beside_exe(eng) # a second run changes nothing
+ self.assertEqual(before, {p.name: p.stat().st_mtime_ns for p in eng.glob("*.dll")})
+
+ def test_unreadable_helper_falls_back_to_the_runtime_pair(self):
+ with tempfile.TemporaryDirectory() as d:
+ d = Path(d)
+ (d / "amdhip64_7.dll").write_bytes(b"x")
+ (d / "amd_comgr.dll").write_bytes(b"y")
+ (d / "rocm_kpack.dll").write_bytes(b"z")
+ with mock.patch.object(setup, "ROOT", d): # no tools/hip/dll_closure.py under this root
+ self.assertEqual(setup.hip_runtime_closure(d), ["amd_comgr.dll", "amdhip64_7.dll"])
+
+
+if __name__ == "__main__":
+ unittest.main()