Merge branch 'f-hf-misc' into f-1402
This commit is contained in:
commit
8aeefca2d8
9 files changed
+391
-22
No files matched your search
@@ -287,6 +287,10 @@ class Telemetry:
|
||||
self.static = {
|
||||
"gpu_name": " + ".join(g.name() or "?" for _, g in self.gpus) if self.gpu.ok() else None,
|
||||
"gpu_count": len(self.gpus),
|
||||
# #1380: the AMD readings are the amdgpu driver's Linux sysfs files; a Windows AMD card has none yet, and the
|
||||
# dashboard said "not readable (NVML)" or showed empty tiles with no word why
|
||||
"gpu_note": ("no GPU load or VRAM readings for AMD cards on Windows yet (Linux reads them from the amdgpu "
|
||||
"driver); the engine's own VRAM figures are in its log" if amd and not self.gpu.ok() else None),
|
||||
"cpu_name": _cpu_name(),
|
||||
"cores": (self.ps.cpu_count(logical=False) if self.ps else None) or None,
|
||||
"threads": os.cpu_count(),
|
||||
|
||||
@@ -191,6 +191,36 @@ def synthetic_tokenizer(seed=268, n_merges=1500):
|
||||
return ST.Tokenizer(tokens, merges, types)
|
||||
|
||||
|
||||
class ThreadedEncode(unittest.TestCase):
|
||||
"""#1385: 'int' object has no attribute 'ranks' in _bpe, seen once under load. Could not be reproduced here (it
|
||||
looks like an interpreter fault); this pins that many threads sharing one Tokenizer, as the server does, get
|
||||
exactly the single-threaded ids, and that _bpe works with a tokenizer whose own state is only read."""
|
||||
|
||||
def test_threads_match_serial(self):
|
||||
import threading
|
||||
tok = synthetic_tokenizer()
|
||||
rng = random.Random(1385)
|
||||
texts = [random_text(rng, 6) for _ in range(40)]
|
||||
want = [tok.encode(t) for t in texts]
|
||||
errors = []
|
||||
|
||||
def work():
|
||||
try:
|
||||
for _ in range(15):
|
||||
for t, w in zip(texts, want):
|
||||
if tok.encode(t) != w:
|
||||
errors.append("mismatch")
|
||||
except Exception as e: # noqa: BLE001
|
||||
errors.append(repr(e))
|
||||
|
||||
ts = [threading.Thread(target=work) for _ in range(8)]
|
||||
for t in ts:
|
||||
t.start()
|
||||
for t in ts:
|
||||
t.join()
|
||||
self.assertEqual(errors, [])
|
||||
|
||||
|
||||
class HeapBpe(unittest.TestCase):
|
||||
"""#268: words longer than HEAP_MIN symbols merge with a heap; the ids must be exactly the scan's."""
|
||||
|
||||
|
||||
+3
-3
@@ -279,11 +279,11 @@ function renderMonitor(live, hw, st, eng, h, last, requests, totals, kept) {
|
||||
const per = (f) => (hw.gpus || []).map((g) => `GPU ${g.index} ${f(g)}`).join(" · ");
|
||||
const multi = (hw.gpus || []).length > 1;
|
||||
setMetric("gpu", hw.gpu_util == null ? null : fmt(hw.gpu_util), "%",
|
||||
multi ? per((g) => (g.util == null ? "–" : `${fmt(g.util)}%`)) : st.gpu_name || "");
|
||||
multi ? per((g) => (g.util == null ? "–" : `${fmt(g.util)}%`)) : st.gpu_name || (st.gpu_note ? "not available" : ""));
|
||||
spark("sp-gpu", h.gpu_util, 100);
|
||||
setMetric("vram", hw.gpu_mem_used == null ? null : gb(hw.gpu_mem_used), hw.gpu_mem_total ? `/ ${gb(hw.gpu_mem_total, 0)} GB` : "GB",
|
||||
multi ? per((g) => (g.mem_used == null ? "–" : `${gb(g.mem_used)} GB`))
|
||||
: eng.expert_slots ? `${fmt(eng.expert_slots)} experts cached` : "");
|
||||
: eng.expert_slots ? `${fmt(eng.expert_slots)} experts cached` : (st.gpu_note ? "not available on Windows AMD yet" : ""));
|
||||
spark("sp-vram", h.gpu_mem_used, hw.gpu_mem_total);
|
||||
setMetric("temp", hw.gpu_temp == null ? null : fmt(hw.gpu_temp), "°C",
|
||||
multi ? per((g) => (g.temp == null ? "–" : `${fmt(g.temp)}°`)) : "");
|
||||
@@ -379,7 +379,7 @@ function renderAbout(eng, hw, st) {
|
||||
["Experimental speed projection", projectionText(eng.cvec)],
|
||||
]);
|
||||
facts($("facts-hw"), [
|
||||
["GPU", st.gpu_name ? `${st.gpu_name}${hw.gpu_mem_total ? `, ${gb(hw.gpu_mem_total, 0)} GB` : ""}` : "not readable (NVML)"],
|
||||
["GPU", st.gpu_name ? `${st.gpu_name}${hw.gpu_mem_total ? `, ${gb(hw.gpu_mem_total, 0)} GB` : ""}` : (st.gpu_note || "not readable (NVML)")],
|
||||
["CPU", st.cpu_name ? `${st.cpu_name}${st.threads ? `, ${st.threads} threads` : ""}` : null],
|
||||
["RAM", hw.ram_total ? `${gb(hw.ram_total, 0)} GB` : null],
|
||||
]);
|
||||
|
||||
@@ -2183,21 +2183,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:
|
||||
|
||||
@@ -3988,11 +3988,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)" : "");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -4190,6 +4204,27 @@ int main(int argc, char** argv) {
|
||||
// under WDDM an over-subscribed allocation does not fail, it pages to system memory and crawls.
|
||||
// (with borrowing - the default with a profile - the prompt path lends cache slots instead; `pf_borrow` is
|
||||
// the predicate a local `borrow` was here, hoisted above so both cache-size branches read the same one)
|
||||
// #1376: under WDDM the free figure read here runs high, and what is allocated after the cache (the verify
|
||||
// windows, the prompt path) comes out of the reserve. 0.1.40 ended a 20 GB RX 7900 XT with 2,170 MiB free
|
||||
// (its write-back check cut the cache); 0.1.40.2 passed that check with the default 700 MiB and ended with
|
||||
// 323 MiB, where Windows paged and decode fell from 52 to 21-25 tok/s. --vram-reserve-mib 2600 fixed it. So on
|
||||
// Windows HIP an auto cache on a card of 16 GiB or more keeps a floor of kWddmAutoReserveMib. CUDA on Windows is
|
||||
// left as it was: the same 0.1.40 / 0.1.40.2 pair on an RTX 5070 ended with the same slots and free VRAM, and a
|
||||
// floor there would only cost 16 GB+ NVIDIA cards ~1.8 GiB of cache. A reserve given on the command line is
|
||||
// kept as it is; a smaller card keeps its own sizing (#496 lowers the reserve further when the cache would not
|
||||
// fit); and this is said, never silent. The cache size changes no output bit.
|
||||
constexpr int kWddmAutoReserveMib = 2560;
|
||||
if (!o.vram_reserve_given && o.vram_reserve_mib < kWddmAutoReserveMib) {
|
||||
#if defined(_WIN32) && defined(STRATA_USE_HIP)
|
||||
size_t fb_now = 0, tb_now = 0;
|
||||
if (cudaMemGetInfo(&fb_now, &tb_now) == cudaSuccess && tb_now >= (16ull << 30)) {
|
||||
std::fprintf(stderr, "strata generate: expert cache auto: Windows keeps %d MiB free after the cache on a card "
|
||||
"this size (the default %d MiB left 323 MiB on a 20 GB card and Windows paged, #1376); "
|
||||
"--vram-reserve-mib N sets it\n", kWddmAutoReserveMib, o.vram_reserve_mib);
|
||||
o.vram_reserve_mib = kWddmAutoReserveMib;
|
||||
}
|
||||
#endif
|
||||
}
|
||||
const int64_t prefill_mib = owned_prefill_mib();
|
||||
// the draft layer's head and logits are allocated when it binds, after this: 0.1.27's CJK subset made them
|
||||
// ~110-180 MiB larger, and out of the reserve they left 16 GB cards below the stall line (#199)
|
||||
|
||||
@@ -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())
|
||||
@@ -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"
|
||||
|
||||
@@ -150,11 +150,16 @@ class Tokenizer:
|
||||
"""
|
||||
if len(word) > self.HEAP_MIN:
|
||||
return self._bpe_heap(word)
|
||||
# `self` is read ONCE, here. #1385: an interpreter (CPython 3.14.4) was seen handing this frame an int
|
||||
# for `self` partway through the scan (`'int' object has no attribute 'ranks'`). Nothing in this class
|
||||
# can do that (no cache, decorator, slots or callback; a thread hammering test cannot make it happen),
|
||||
# so the scan below works on a local and no longer re-reads `self` once per symbol pair.
|
||||
ranks_get = self.ranks.get
|
||||
parts = list(word)
|
||||
while len(parts) > 1:
|
||||
best, best_rank = None, None
|
||||
for i in range(len(parts) - 1):
|
||||
r = self.ranks.get((parts[i], parts[i + 1]))
|
||||
r = ranks_get((parts[i], parts[i + 1]))
|
||||
if r is not None and (best_rank is None or r < best_rank):
|
||||
best, best_rank = i, r
|
||||
if best is None:
|
||||
|
||||
@@ -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()
|
||||
Reference in new issue
Block a user