diff --git a/serve/telemetry.py b/serve/telemetry.py index 6fc1a030..33ad71ac 100644 --- a/serve/telemetry.py +++ b/serve/telemetry.py @@ -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(), diff --git a/serve/test_detok.py b/serve/test_detok.py index b1c61424..01b3e0fa 100644 --- a/serve/test_detok.py +++ b/serve/test_detok.py @@ -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.""" diff --git a/serve/web/app.js b/serve/web/app.js index ade19016..f4a2b2c5 100644 --- a/serve/web/app.js +++ b/serve/web/app.js @@ -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], ]); diff --git a/setup.py b/setup.py index b192dfd0..8d7b4666 100644 --- a/setup.py +++ b/setup.py @@ -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: diff --git a/src/program/generate.cpp b/src/program/generate.cpp index 7101dc25..ce8e0047 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -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) diff --git a/tools/hip/dll_closure.py b/tools/hip/dll_closure.py new file mode 100644 index 00000000..4a56f6a3 --- /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(" 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 1ece8f0d..a2104e81 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/strata_tokenizer.py b/tools/strata_tokenizer.py index 11fcd45e..b5d1fdef 100644 --- a/tools/strata_tokenizer.py +++ b/tools/strata_tokenizer.py @@ -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: diff --git a/tools/test_dll_closure.py b/tools/test_dll_closure.py new file mode 100644 index 00000000..5d4e4ca9 --- /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("