diff --git a/.gitignore b/.gitignore index 26885bfe..6e65fb38 100644 --- a/.gitignore +++ b/.gitignore @@ -49,3 +49,4 @@ build-vision.bat *.done /third_party/*.zip +/.rocm-win/ diff --git a/CMakeLists.txt b/CMakeLists.txt index b6d051a4..a11130e7 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -426,6 +426,15 @@ if(STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP) add_test(NAME hip_handoff COMMAND hip_handoff) list(APPEND _strata_hip_tests hip_handoff) endif() + if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/tests/hip/mapped_alias.cpp") + # #325: reports what a hipHostGetDevicePointer alias is on this stack (on Windows: the host pointer, and a + # D2D copy into it does not land - hip_handoff's timeout there). A diagnosis: exits 0 whenever it ran. + add_executable(hip_mapped_alias tests/hip/mapped_alias.cpp) + target_link_libraries(hip_mapped_alias PRIVATE strata_kernels strata_hip_runtime) + add_test(NAME hip_mapped_alias COMMAND hip_mapped_alias) + set_tests_properties(hip_mapped_alias PROPERTIES SKIP_RETURN_CODE 77) + list(APPEND _strata_hip_tests hip_mapped_alias) + endif() if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/tests/hip/native_qsa_score.cpp") add_executable(hip_native_qsa_score tests/hip/native_qsa_score.cpp) target_link_libraries(hip_native_qsa_score PRIVATE strata_kernels strata_hip_runtime) diff --git a/START-HERE.bat b/START-HERE.bat index 2b80315d..dfb92feb 100644 --- a/START-HERE.bat +++ b/START-HERE.bat @@ -1,6 +1,6 @@ @echo off rem Strata for Windows: the first run installs everything and starts the model; later runs just start it. -rem Needs only an NVIDIA driver. Python is installed for your user account if it is missing (no admin needed). +rem Needs only an NVIDIA or AMD graphics driver. Python is installed for your user account if it is missing (no admin needed). setlocal title Strata cd /d "%~dp0" diff --git a/cmake/hip_backend.cmake b/cmake/hip_backend.cmake index 558bb07c..255ee381 100644 --- a/cmake/hip_backend.cmake +++ b/cmake/hip_backend.cmake @@ -12,8 +12,14 @@ endif() set(_strata_hip_validated gfx1100 gfx1201) set(_strata_hip_community gfx1101 gfx1200) set(_strata_hip_unvalidated gfx1102 gfx1030) +# CMake hands HIP a ';' list, but a -DCMAKE_HIP_ARCHITECTURES typed by hand (or ROCm's own Windows tooling) may use +# spaces, which foreach(IN LISTS) would otherwise treat as one element. +string(REPLACE " " ";" _strata_hip_norm "${CMAKE_HIP_ARCHITECTURES}") set(STRATA_HIP_ARCH_LIST "") -foreach(_arch IN LISTS CMAKE_HIP_ARCHITECTURES) +foreach(_arch IN LISTS _strata_hip_norm) + if(_arch STREQUAL "") + continue() + endif() string(REGEX REPLACE ":.*$" "" _base "${_arch}") # gfx1100:xnack- -> gfx1100 if(_base IN_LIST _strata_hip_validated) elseif(_base IN_LIST _strata_hip_community) @@ -62,11 +68,19 @@ target_include_directories(strata_hip_runtime BEFORE INTERFACE "${STRATA_HIP_COMPAT_INCLUDE_DIR}" "${CMAKE_CURRENT_SOURCE_DIR}/include") target_compile_definitions(strata_hip_runtime INTERFACE STRATA_USE_HIP=1 "STRATA_HIP_ARCHS=\"${STRATA_HIP_ARCHS}\"") target_link_libraries(strata_hip_runtime INTERFACE hip::host) -foreach(_language IN ITEMS CXX HIP) +# The shim renames the CUDA runtime to HIP, force-included into every host and device source. On Windows the host +# compiler is ROCm's clang++ too (tools/hip/build_windows.bat: CMake refuses to mix cl.exe with Clang HIP), which takes +# -include like it does on Linux; an MSVC-style front end (cl / clang-cl) takes /FI instead. Forward slashes, so /FI +# does not read the path's backslashes as escapes. +file(TO_CMAKE_PATH "${STRATA_HIP_COMPAT_INCLUDE_DIR}/cuda_runtime.h" _strata_hip_force) +if(MSVC) + target_compile_options(strata_hip_runtime INTERFACE "$<$:/FI${_strata_hip_force}>") +else() target_compile_options(strata_hip_runtime INTERFACE - "$<$:-include>" - "$<$:${STRATA_HIP_COMPAT_INCLUDE_DIR}/cuda_runtime.h>") -endforeach() + "$<$:-include>" "$<$:${_strata_hip_force}>") +endif() +target_compile_options(strata_hip_runtime INTERFACE + "$<$:-include>" "$<$:${_strata_hip_force}>") # CMake does not infer HIP from Strata's existing CUDA-shaped .cu suffixes. file(GLOB_RECURSE _strata_hip_sources CONFIGURE_DEPENDS diff --git a/docs/AMD_HIP.md b/docs/AMD_HIP.md index 8df4bb85..9dd33588 100644 --- a/docs/AMD_HIP.md +++ b/docs/AMD_HIP.md @@ -1,10 +1,10 @@ # Experimental AMD HIP backend (gfx1100, gfx1101, gfx1200, gfx1201, gfx1030) -This is a Linux source build for the RX 7900 XT / XTX (RDNA3, gfx1100) and the +On Linux this is a source build (on Windows a ready-made engine, see [Windows](#windows)) for the RX 7900 XT / XTX (RDNA3, gfx1100) and the RX 9070 / 9070 XT / Radeon AI PRO R9700 (RDNA4, gfx1201; see [RDNA4](#rdna4-gfx1201)). The RX 7800 XT / 7700 XT (gfx1101) and the RX 9060 XT (gfx1200) were validated by their owners (see [Community-validated cards](#community-validated-cards)); the RX 6800 / 6900 series (RDNA2, gfx1030) builds and runs too, reported by a community machine and not yet validated by the maintainers (see [RDNA2](#rdna2-gfx1030)). It is opt-in; the NVIDIA installer and CUDA build remain the default. Other AMD -architectures, wave64, Windows HIP, and mixed AMD/NVIDIA execution are outside this contribution. +architectures, wave64, and mixed AMD/NVIDIA execution are outside this contribution. The backend maps the CUDA-shaped runtime and BLAS calls to HIP/hipBLAS, uses RDNA2/RDNA3/RDNA4's signed integer dot instruction for quantized kernels, and supplies @@ -49,6 +49,59 @@ the kernel's amdgpu driver (no ROCm install needed): The rest of setup is the same as on NVIDIA: the model download, the start script, the server. +## Windows + +Since 0.1.33 an AMD card on Windows is set up like an NVIDIA one: download Strata, double-click `START-HERE.bat`. +On a PC with no NVIDIA card Strata can use, the AMD card is chosen by itself; with both, setup asks +(`START-HERE.bat --backend hip` picks AMD directly). + +- **You need:** Windows 10 or 11 (64-bit), one of the cards above, and a current AMD driver ([AMD Software: + Adrenalin Edition](https://www.amd.com/en/support/download/drivers.html)). Nothing else: no ROCm or HIP SDK + install, no compiler, no admin rights. +- **Detection:** setup reads the display adapters Windows lists (their PCI ids; the VRAM size from the display + driver's registry entry). An integrated Radeon is listed as not supported. +- **Engine:** the ready-made `strata-windows-x64-hip.zip` from the release (built by `tools\hip\build_windows.bat` + for gfx1100, gfx1101, gfx1102, gfx1200, gfx1201 and gfx1030) goes into `engine\`. It carries the ROCm libraries the + engine loads (`engine\rocm\bin`: the HIP runtime, hipBLAS / rocBLAS / hipBLASLt with their kernels for these cards, + amd_comgr and the Microsoft C++ runtime; ROCm 10.2.0a20260930 from AMD's TheRock builds, licenses in + `engine\rocm\licenses`). The HIP runtime works through the AMD driver's own components, so the driver is the one + thing it needs from the PC. +- **Before the ~60 GB model download** setup runs `engine\strata-device.exe --list-devices` (with `engine\rocm\bin` on + the PATH): if the HIP runtime does not see the card, setup stops there and points to the driver. It also gives the + card's HIP number: with an integrated Radeon that is device 1, not 0 (#325). From then on setup lists the AMD cards + as HIP numbers them, so `--gpu N` and the config's `"gpu"` are HIP numbers. +- **Differences from Windows-on-NVIDIA and Linux-on-AMD:** no images yet (the CPU image encoder is Linux-only for + now), one card per model (`--gpus` is Linux-only for now), no calibration. +- Two Windows-only engine details (#247, #325): hipBLAS can return success and still leave `hipErrorInvalidValue` + set after some BF16/FP16 GEMMs (seen on gfx1201); the engine clears that one stale error after a GEMM that + succeeded, on Windows only. `hipHostGetDevicePointer` returns the host pointer itself on Windows: kernels read + mapped memory through it correctly, but a device-to-device copy into it does not land, which is why + `tests/hip/handoff` times out there (the engine does not use that copy; `tests/hip/mapped_alias` reports it). + +**What is validated (0.1.33):** #325's author ran the engine of this port on an RX 9070 XT (Windows 11, ROCm +10.2.0a20260930 in `.venv`, compiled on the PC): Coder IQ1_M at 32K, 29.2 tok/s decode, ~181 tok/s prefill, +correct answers; ctest 42 of 46. The maintainers have no Windows AMD card: the release zip was built on an NVIDIA PC, +and checked there on the Ryzen CPU's integrated Radeon (gfx1036, a test build of the same tree): with only the zip's +libraries on the PATH, `strata-device` lists the card and a hipBLAS BF16 GEMM matches the CPU; the HIP ctest passes +52 of 56, the 4 failures the same as on the RX 9070 XT (`hip_handoff`, and three tests that need a pack fixture). +The ready-made zip itself has not run a model on a discrete card yet - please report. + +**Reporting a Windows AMD run** (an issue, or on #325): your card and driver version (AMD Software > System), then + +```bat +engine\strata-device.exe --list-devices +engine\strata-device.exe --selftest +``` + +(from the Strata folder, after `set PATH=%CD%\engine\rocm\bin;%PATH%`), the end of `strata-.log`, and the +speed lines the server window prints for a first answer. + +**Building it yourself:** `tools\hip\build_windows.bat` (Visual Studio 2022 Build Tools with the C++ workload, Python, +git; no admin, no AMD GPU) installs ROCm from AMD's TheRock wheels into `.rocm-win`, builds, and packages +`dist\strata-windows-x64-hip.zip`; `START-HERE.bat --backend hip --prebuilt dist\` installs that one. +`tools\hip\build_windows.bat tests` also builds the HIP tests (`ctest` in `build-hip-win`, with +`.rocm-win\Lib\site-packages\_rocm_sdk_devel\bin` on the PATH). `STRATA_HIP_ARCHS` picks other architectures. + ## Build Requirements: a working ROCm driver/runtime, HIP development headers and diff --git a/include/strata/core/device.hpp b/include/strata/core/device.hpp index 2c180263..091dff1c 100644 --- a/include/strata/core/device.hpp +++ b/include/strata/core/device.hpp @@ -38,6 +38,16 @@ std::string gpu_arch_problem(int ordinal); // The GPU architectures this binary was compiled for ("gfx1100,gfx1201"); "" on CUDA builds. const char* compiled_gpu_archs(); +// How many devices the runtime enumerates, numbered as HIP_VISIBLE_DEVICES / CUDA_VISIBLE_DEVICES number them; 0 when +// there is none (or no usable runtime). `device_info` throws on a card this binary cannot run, so a caller that LISTS +// every card - the ones it has no code for included (`strata-device --list-devices`) - counts them with this first. +int device_count(); + +// One line per device for `strata-device --list-devices`, without the arch check that `device_info` applies: +// "arch gfx1201, 15.9 GiB" (HIP) or "compute capability 12.0, 11.9 GiB" (CUDA), plus the device's name. false when +// the runtime cannot describe it. +bool device_summary(int ordinal, std::string& name, std::string& detail); + // Throws when there is no CUDA device. The engine targets sm_120 specifically and must say so rather than // run slowly on something else: `CMakeLists.txt` already refuses to COMPILE for another architecture, and // this is the matching check at run time (a binary can be carried to a different machine). diff --git a/include/strata/hip_compat/cuda_runtime.h b/include/strata/hip_compat/cuda_runtime.h index bf78284a..40c1c79c 100644 --- a/include/strata/hip_compat/cuda_runtime.h +++ b/include/strata/hip_compat/cuda_runtime.h @@ -1,5 +1,14 @@ #pragma once // Included only by STRATA_ENABLE_HIP builds. CUDA builds use NVIDIA headers. +#if defined(_WIN32) +// hip_runtime.h pulls in on Windows: keep its min/max macros and the rarely used APIs out of the engine. +#ifndef WIN32_LEAN_AND_MEAN +#define WIN32_LEAN_AND_MEAN +#endif +#ifndef NOMINMAX +#define NOMINMAX +#endif +#endif #include // Do not let HIP's legacy macro corrupt libstdc++ attribute names. #ifdef __noinline__ diff --git a/serve/server.py b/serve/server.py index 9b07375d..c2333bca 100644 --- a/serve/server.py +++ b/serve/server.py @@ -631,12 +631,28 @@ def engine_args(cfg: dict) -> list[str]: return args +def hip_visible(cfg: dict) -> list[int]: + """AMD: the devices the engine should see, as the HIP runtime numbers them (HIP_VISIBLE_DEVICES). + + On Linux setup's KFD order is HIP's order, so the config's "gpu" is it. On Windows setup finds the cards in the + display-adapter order, and an integrated Radeon that HIP also enumerates takes ordinal 0 and pushes the discrete + card to 1 (#325): setup records the ordinal `strata-device --list-devices` gave the card as "hip_ordinal", which + wins for a one-card config. Without it (a config from before), the config's "gpu".""" + ordinal = cfg.get("hip_ordinal") + if ordinal is not None and str(ordinal).strip() != "" and len(gpu_list(cfg)) <= 1: + try: + return [int(str(ordinal).strip())] + except ValueError: + pass + return gpu_list(cfg) + + def child_env(cfg: dict) -> dict: """The engine's environment: the CUDA libraries setup installed (pip's nvidia packages, or the toolkit that compiled it) first on the library search path.""" env = dict(os.environ) - if gpu_list(cfg) and cfg.get("backend") == "hip": # AMD: numbered as HIP numbers them (setup's KFD order) - env["HIP_VISIBLE_DEVICES"] = ",".join(str(i) for i in gpu_list(cfg)) + if hip_visible(cfg) and cfg.get("backend") == "hip": # AMD: numbered as HIP numbers them (hip_visible) + env["HIP_VISIBLE_DEVICES"] = ",".join(str(i) for i in hip_visible(cfg)) elif gpu_list(cfg): # issue #51: the GPU(s) to run on, numbered as nvidia-smi does; CUDA's env["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID" # own default order (fastest first) can number the cards otherwise env["CUDA_VISIBLE_DEVICES"] = ",".join(str(i) for i in gpu_list(cfg)) diff --git a/serve/test_server.py b/serve/test_server.py index 46fea89c..34e8f731 100644 --- a/serve/test_server.py +++ b/serve/test_server.py @@ -552,6 +552,18 @@ class GpuChoice(unittest.TestCase): plain = {"gpu": [0, 1], "vision": {"exe": "v"}} self.assertIs(vision_env(plain, env), env) # no cuda_device: the engine's environment, unchanged + def test_hip_ordinal(self): + """#325: on Windows the HIP ordinal setup resolved wins over the config's "gpu" (an iGPU takes HIP's 0).""" + from serve.server import child_env + self.assertEqual(child_env({"backend": "hip", "gpu": 1})["HIP_VISIBLE_DEVICES"], "1") # Linux: KFD order + self.assertEqual(child_env({"backend": "hip", "hip_ordinal": 1})["HIP_VISIBLE_DEVICES"], "1") + self.assertEqual(child_env({"backend": "hip", "gpu": 0, "hip_ordinal": 1})["HIP_VISIBLE_DEVICES"], "1") + self.assertEqual(child_env({"backend": "hip", "gpu": [1, 0], "hip_ordinal": 2})["HIP_VISIBLE_DEVICES"], + "1,0") # a layer split keeps its list + self.assertEqual(child_env({"backend": "hip", "gpu": 0, "hip_ordinal": "x"})["HIP_VISIBLE_DEVICES"], "0") + plain = child_env({"backend": "hip"}) + self.assertEqual(plain.get("HIP_VISIBLE_DEVICES"), os.environ.get("HIP_VISIBLE_DEVICES")) + class RecordingPrompt(MockEngine): def generate(self, ids, max_new, sampling, cancel, embeddings=None): diff --git a/setup.py b/setup.py index 2ddebc64..9f42aa4d 100644 --- a/setup.py +++ b/setup.py @@ -1,5 +1,5 @@ #!/usr/bin/env python3 -"""Strata one-click setup and start (Windows and Linux, NVIDIA GPUs). +"""Strata one-click setup and start (Windows and Linux, NVIDIA or AMD GPUs). START-HERE.bat (Windows) / ./setup.sh (Linux) - they install Python if needed and run this file @@ -10,11 +10,12 @@ is already downloaded, installed or prepared is done again. What the first run does (each step is skipped when it is already done): - 1. checks your PC: NVIDIA GPU and driver, RAM, CPU, free disk space + 1. checks your PC: NVIDIA or AMD GPU and driver, RAM, CPU, free disk space 2. asks the questions 3. installs the Python packages it needs into .venv (numpy, jinja2, ..., and NVIDIA's CUDA libraries) 4. gets the Strata engine: a ready-made build for RTX 20/30/40/50 cards (no compiler needed); if none fits your PC, - it installs the build tools (asks first) and compiles the engine for your GPU + it installs the build tools (asks first) and compiles the engine for your GPU. AMD (--backend hip, chosen by + itself on a PC with no usable NVIDIA card): the ready-made HIP engine on Windows, compiled here on Linux 5. downloads the model from Hugging Face (resumable), and the vision encoder if you want images 6. prepares the model for Strata and fetches the MTP draft layer (~5 GB, from the original Qwen checkpoint) 7. writes run-.bat / run-.sh and starts the model @@ -980,10 +981,12 @@ def rocm_index(arch): def amd_gpus(sysfs="/sys"): """AMD GPUs from the kernel's KFD topology (the amdgpu driver; no ROCm needed), numbered as HIP numbers them: the GPU nodes in order, the CPU nodes skipped. Integrated GPUs are listed too (not supported). - sysfs: the tree to read (tools/test_setup_amd.py passes a mocked one).""" + sysfs: the tree to read (tools/test_setup_amd.py passes a mocked one). Windows: amd_gpus_win.""" + if WIN: + return amd_gpus_win() base = Path(sysfs) / "class/kfd/kfd/topology/nodes" found = [] - if WIN or not base.is_dir(): + if not base.is_dir(): return found for node in sorted((p for p in base.iterdir() if p.name.isdigit()), key=lambda p: int(p.name)): try: @@ -1016,9 +1019,17 @@ def amd_gpus(sysfs="/sys"): def amd_problem(g): if g["arch"] not in AMD_ARCHS: return f"not supported - Strata's AMD backend runs on {AMD_CARDS} only, this is {g['arch']}" + if g.get("cannot_run"): # Windows: the installed engine's own check (--list-devices) + return g["cannot_run"] return None +def amd_gpus_win() -> list[dict]: + """Windows: the AMD GPUs as the HIP runtime numbers them once the HIP engine is installed (hip_devices), else in + the display-adapter order (amd_gpus_windows).""" + return hip_devices() or amd_gpus_windows() + + def amd_parse_gpus(text, amd) -> list: """--gpus with AMD cards, numbered as HIP numbers them (setup's list): "1,0", or "all" (every supported card, the most VRAM first). Every chosen card must be one Strata supports (AMD_ARCHS; they may be of different @@ -1046,6 +1057,278 @@ def amd_parse_gpus(text, amd) -> list: return [byid[i] for i in sel] +# ------------------------------------------------------------------------------------------------ AMD on Windows +# Windows has no KFD topology: the cards are found from the display adapters (Win32_VideoController: the ones present, +# with their PCI ids) and the display-class registry (each adapter's 64-bit VRAM size), before any AMD software is +# needed. The engine is the ready-made HIP one (WIN_HIP_ASSET: strata.exe, strata-device.exe and the ROCm libraries it +# loads, built by tools/hip/build_windows.bat); it needs only the AMD driver. Once it is installed, the cards are +# numbered as the HIP runtime numbers them (`strata-device --list-devices`): an integrated Radeon takes HIP's device 0 +# and pushes the discrete card to 1, which the display-adapter order does not show (#325). +WIN_HIP_ASSET = "strata-windows-x64-hip.zip" +WIN_HIP_MIN_ENGINE = max(MIN_ENGINE, (0, 1, 33)) # the first release with a Windows HIP engine +WIN_AMD_DRIVER = "https://www.amd.com/en/support/download/drivers.html" +# PCI device ids (VEN_1002) of the cards the AMD backend knows; the names below cover a card whose id is not listed +_WIN_AMD_DID = {0x744C: "gfx1100", 0x7448: "gfx1100", 0x745E: "gfx1100", # RX 7900 XTX/XT/GRE, W7900, W7800 + 0x747E: "gfx1101", # RX 7800 XT / 7700 XT + 0x7480: "gfx1102", # RX 7600 / 7600 XT + 0x7590: "gfx1200", # RX 9060 XT + 0x7550: "gfx1201", 0x7551: "gfx1201", # RX 9070 / 9070 XT, AI PRO R9700 + 0x73BF: "gfx1030", 0x73AF: "gfx1030", 0x73A5: "gfx1030"} # RX 6800 / 6800 XT / 6900 XT / 6950 XT +_WIN_AMD_NAME = ((re.compile(r"\b9070\b|R9700", re.I), "gfx1201"), + (re.compile(r"\b9060\b", re.I), "gfx1200"), + (re.compile(r"RX\s*7900|W7900|W7800", re.I), "gfx1100"), + (re.compile(r"RX\s*7800|RX\s*7700(?!\s*S)|W7700", re.I), "gfx1101"), + (re.compile(r"RX\s*7600|W7600|W7500", re.I), "gfx1102"), + (re.compile(r"RX\s*6800(?!\s*[MS])|RX\s*6900|RX\s*6950|W6800", re.I), "gfx1030")) +_DISPLAY_CLASS = r"SYSTEM\CurrentControlSet\Control\Class\{4d36e968-e325-11ce-bfc1-08002be10318}" + + +def _win_display_adapters() -> list[dict]: + """The display adapters present ({"name", "pnp"}), from Win32_VideoController.""" + ps = ("Get-CimInstance Win32_VideoController | ForEach-Object { $_.Name + '|' + $_.PNPDeviceID + '|' + " + "$_.AdapterRAM }") + text = out(["powershell", "-NoProfile", "-NonInteractive", "-Command", ps]) + found = [] + for line in text.splitlines(): + parts = line.strip().split("|") + if len(parts) >= 2 and parts[1]: + ram = parts[2] if len(parts) > 2 else "" + found.append({"name": parts[0].strip(), "pnp": parts[1].strip(), + "ram": int(ram) if ram.strip().isdigit() else 0}) + return found + + +def _win_display_registry() -> list[dict]: + """Each display driver instance's description, matching PCI id and VRAM size (the 64-bit value; the WMI one stops + at 4 GB), from the display-class registry key - readable without admin.""" + found = [] + try: + import winreg + cls = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, _DISPLAY_CLASS) + except (ImportError, OSError): + return found + i = 0 + while True: + try: + sub = winreg.EnumKey(cls, i) + except OSError: + break + i += 1 + if not sub.isdigit(): + continue + try: + key = winreg.OpenKey(cls, sub) + except OSError: + continue + vals = {} + for name in ("DriverDesc", "MatchingDeviceId", "HardwareInformation.qwMemorySize", "DriverVersion"): + try: + vals[name] = winreg.QueryValueEx(key, name)[0] + except OSError: + pass + found.append(vals) + return found + + +def _pci_device_id(text: str) -> int | None: + m = re.search(r"VEN_1002&DEV_([0-9A-F]{4})", str(text or ""), re.I) + return int(m.group(1), 16) if m else None + + +def win_amd_arch(device_id: int | None, name: str) -> str: + """A Windows AMD adapter's architecture from its PCI device id, else its name; "" when it is none Strata knows + (an integrated Radeon, an older card).""" + if device_id in _WIN_AMD_DID: + return _WIN_AMD_DID[device_id] + return next((a for rx, a in _WIN_AMD_NAME if rx.search(name or "")), "") + + +def amd_gpus_windows(adapters=None, registry=None) -> list[dict]: + """The AMD display adapters present, in display-adapter order (setup's numbering until the HIP engine is + installed), with the arch Strata would run them as ("" = unknown: listed, not supported). adapters / registry: + tools/test_setup_amd.py passes mocked ones.""" + adapters = _win_display_adapters() if adapters is None else adapters + registry = _win_display_registry() if registry is None else registry + if not adapters: # no WMI answer: the registry alone (it can list removed cards) + adapters = [{"name": r.get("DriverDesc", ""), "pnp": r.get("MatchingDeviceId", ""), "ram": 0} for r in registry] + used = set() + found = [] + for ad in adapters: + did = _pci_device_id(ad.get("pnp")) + if did is None: + continue # not an AMD (VEN_1002) PCI device + vram, driver = 0.0, "" + for k, r in enumerate(registry): # the same card's driver instance: its 64-bit VRAM size + if k in used or _pci_device_id(r.get("MatchingDeviceId")) != did: + continue + if r.get("DriverDesc") and ad.get("name") and r["DriverDesc"].strip() != ad["name"].strip(): + continue + used.add(k) + mem = r.get("HardwareInformation.qwMemorySize") + if isinstance(mem, bytes): + mem = int.from_bytes(mem[:8], "little") + vram = int(mem) / 2 ** 30 if isinstance(mem, int) and mem > 0 else 0.0 + driver = str(r.get("DriverVersion") or "") + break + if vram == 0.0 and ad.get("ram", 0) > 0: + vram = ad["ram"] / 2 ** 30 # WMI's 32-bit figure (at most 4 GB) + arch = win_amd_arch(did, ad.get("name", "")) + name = ad.get("name") or AMD_NAMES.get(arch, f"AMD Radeon (device {did:04X})") + found.append({"index": len(found), "name": name, "vram_gb": vram, "arch": arch or f"unknown (PCI {did:04X})", + "driver": driver or "amd", "vendor": "amd"}) + return found + + +def hip_devices(probe: Path | None = None, text: str | None = None) -> list[dict] | None: + """The GPUs the HIP runtime enumerates, numbered as HIP_VISIBLE_DEVICES numbers them, from the installed engine's + `strata-device --list-devices`; None when there is no HIP engine here or it does not answer. text: its output + (tests).""" + if text is None: + probe = probe or ROOT / "engine" / ("strata-device.exe" if WIN else "strata-device") + try: + hip_engine = json.loads((probe.parent / "BUILD.json").read_text()).get("backend") == "hip" + except (OSError, ValueError): + hip_engine = False + if not probe.exists() or not hip_engine: + return None + try: + env = dict(os.environ) # the ready-made engine's ROCm DLLs (rocm/bin beside it) + env["PATH"] = os.pathsep.join([str(d) for d in hip_lib_dirs(probe.parent)] + [env.get("PATH", "")]) + r = subprocess.run([str(probe), "--list-devices"], capture_output=True, text=True, timeout=120, + cwd=str(probe.parent), env=env) + except (OSError, subprocess.TimeoutExpired): + return None + if r.returncode != 0: + return None + text = r.stdout + found = [] + for line in text.splitlines(): + m = re.match(r"device\s+(\d+):\s*(.*)$", line.strip()) + if m: + found.append({"index": int(m.group(1)), "name": m.group(2).strip(), "vram_gb": 0.0, "arch": "", + "driver": "hip", "vendor": "amd"}) + continue + if not found: + continue + a = re.match(r"arch\s+(gfx[0-9a-f]+)\s*,\s*([\d.]+)\s*GiB", line.strip()) + if a and not found[-1]["arch"]: + found[-1]["arch"], found[-1]["vram_gb"] = a.group(1), float(a.group(2)) + elif line.strip().startswith("cannot run:"): + found[-1]["cannot_run"] = line.strip()[len("cannot run:"):].strip() + for g in found: + if not g["arch"]: + g["arch"] = "unknown" + if g["arch"] in AMD_NAMES and g["name"] in ("", "AMD Radeon Graphics"): + g["name"] = AMD_NAMES[g["arch"]] + return found + + +def hip_lib_dirs(eng: Path) -> list[Path]: + """Where the ready-made Windows HIP engine's ROCm DLLs are (its BUILD.json "lib_dirs", relative to engine/).""" + try: + rel = json.loads((eng / "BUILD.json").read_text()).get("lib_dirs") or [] + except (OSError, ValueError): + rel = [] + return [eng / d for d in rel if (eng / d).is_dir()] + + +def hip_match(card: dict, listed: list[dict], hip: list[dict]) -> dict | None: + """The HIP device that is setup's `card` (from `listed`, the display-adapter order): the k-th device of the same + architecture, k = the card's rank among the listed cards of that architecture. None when HIP has no such card.""" + same = [g["index"] for g in listed if g["arch"] == card["arch"]] + k = same.index(card["index"]) if card["index"] in same else 0 + cand = [g for g in hip if g["arch"] == card["arch"]] + return cand[k] if k < len(cand) else None + + +def hip_card(eng: Path, gpu: dict, listed: list[dict]) -> dict: + """Windows: setup's chosen AMD card as the installed HIP engine numbers it (HIP_VISIBLE_DEVICES), checked by the + engine itself before the model download: an integrated Radeon is HIP's device 0 (#325), and a PC without a + working AMD driver stops here with what to install.""" + hip = hip_devices(eng / "strata-device.exe") + hint = (f"install or update the AMD driver (AMD Software: Adrenalin Edition) from {WIN_AMD_DRIVER}, restart the " + f"PC and run this again; {eng / 'strata-device.exe'} --list-devices shows what the HIP runtime sees") + if not hip: + fail("the AMD HIP runtime finds no GPU (the ready-made engine's device check)", hint) + m = hip_match(gpu, listed, hip) if gpu.get("driver") != "hip" else \ + next((x for x in hip if x["index"] == gpu["index"]), None) + if m is None: + fail(f"the HIP runtime does not list your {gpu['name']} ({gpu['arch']})", hint) + if amd_problem(m): + fail(f"HIP device {m['index']} ({m['name']}) cannot be used: {amd_problem(m)}") + if gpu.get("driver") != "hip" and m["index"] != gpu["index"]: + ok(f"HIP numbers this card {m['index']} (an integrated GPU comes first): the engine is pointed at it") + return {**gpu, "index": m["index"], "count": len(hip), "vram_gb": m["vram_gb"] or gpu["vram_gb"], "driver": "hip"} + + +def get_prebuilt_hip(url_base, gpu, updating=False) -> Path | None: + """The ready-made Windows HIP engine (WIN_HIP_ASSET) in engine/, kept between runs; None when it cannot be had + (not published for this version, no internet) or has no code for the card.""" + eng = ROOT / "engine" + info = eng / "BUILD.json" + if info.exists() and (eng / EXE).exists(): + try: + meta = json.loads(info.read_text()) + except ValueError: + meta = {} + ver = tuple(int(x) for x in str(meta.get("version", "0")).split(".")[:3] if x.isdigit()) + if meta.get("backend") == "hip" and meta.get("source") == "prebuilt" and ver >= WIN_HIP_MIN_ENGINE and \ + gpu["arch"] in meta.get("archs", []) and not updating: + ok("ready-made AMD engine already installed") + return eng + if not url_base: + return None + eng.mkdir(exist_ok=True) + z = eng / WIN_HIP_ASSET + bases = prebuilt_bases(url_base) + for i, base in enumerate(bases): + if not base.startswith(("http://", "https://")): + break + try: + req = urllib.request.Request(base + WIN_HIP_ASSET, method="HEAD", headers={"User-Agent": "strata-setup"}) + urllib.request.urlopen(req, timeout=60).close() + break + except OSError as e: + if i + 1 < len(bases): + say(f" No ready-made AMD engine for v{source_version()} ({e}): the latest release instead") + continue + warn(f"no ready-made AMD engine at {base} ({e})") + return None + say(" Downloading the ready-made Strata engine for AMD GPUs (with the ROCm libraries it uses) ...") + download(base + WIN_HIP_ASSET, z, "Strata AMD engine") + tmp = eng / "_unpack" + shutil.rmtree(tmp, ignore_errors=True) + with zipfile.ZipFile(z) as f: + f.extractall(tmp) + try: + meta = json.loads((tmp / "BUILD.json").read_text()) + except (OSError, ValueError): + meta = {} + ver = tuple(int(x) for x in str(meta.get("version", "0")).split(".")[:3] if x.isdigit()) + why = None + if meta.get("backend") != "hip" or not (tmp / EXE).exists(): + why = "it is not a HIP engine" + elif ver < WIN_HIP_MIN_ENGINE: + why = f"it is version {meta.get('version')}; this setup needs {'.'.join(map(str, WIN_HIP_MIN_ENGINE))}" + elif gpu["arch"] not in meta.get("archs", []): + why = f"it is built for {', '.join(meta.get('archs', []))}; your GPU is {gpu['arch']}" + if why: + warn(f"the ready-made AMD engine at {base} cannot be used: {why}") + shutil.rmtree(tmp, ignore_errors=True) + drop_archive(z) + return None + for p in tmp.iterdir(): + dst = eng / p.name + if dst.exists(): + shutil.rmtree(dst) if dst.is_dir() else dst.unlink() + p.replace(dst) + shutil.rmtree(tmp, ignore_errors=True) + drop_archive(z) + ok(f"ready-made AMD engine {meta.get('version', '')} for {', '.join(meta.get('archs', []))} " + f"(ROCm {meta.get('rocm', '?')})") + return eng + + def rocm_version(root): """(major, minor) of a ROCm install, from rocm-core's header; None when it has none.""" try: @@ -1112,10 +1395,11 @@ def hipblaslt_version(lib_dirs): return None -def hipblaslt_table(arch, lib_dirs): +def hipblaslt_table(arch, lib_dirs, ver=None): """tools/hip/-hipblaslt-.txt for this card AND the installed hipBLASLt, else None: its solution - ids are valid only for that pair (the engine refuses any other table and uses plain hipBLAS).""" - ver = hipblaslt_version(lib_dirs) + ids are valid only for that pair (the engine refuses any other table and uses plain hipBLAS). ver: the + hipBLASLt version the ready-made Windows engine ships (its BUILD.json), else read from the installed headers.""" + ver = ver or hipblaslt_version(lib_dirs) table = ROOT / "tools" / "hip" / f"{arch}-hipblaslt-{ver}.txt" if ver is not None and table.exists(): head = table.read_text().split("\n", 2)[:2] @@ -1184,7 +1468,12 @@ def hip_vision(asked) -> str: """The image encoder with the AMD backend (--vision): the CPU one when asked for (#304); a HIP (GPU) encoder build is a later step, so `yes`/`gpu` leave images off, as before, and say how to get them.""" if asked in ("yes", "gpu"): - warn("the AMD backend has no GPU image encoder yet: images off (--vision cpu reads them on the CPU)") + warn("the AMD backend has no GPU image encoder yet: images off" + + ("" if WIN else " (--vision cpu reads them on the CPU)")) + if asked == "cpu" and WIN: + warn("images on the CPU with an AMD card are Linux-only for now (the ready-made Windows AMD engine has no " + "image encoder): images off") + return "none" return "cpu" if asked == "cpu" else "none" @@ -1222,7 +1511,7 @@ def get_prebuilt(url_base, gpu, vision, updating=False) -> Path | None: updating: called to replace an installed engine, which starts instead when this fails (no compile).""" eng = ROOT / "engine" info = eng / "BUILD.json" - if info.exists() and (eng / EXE).exists(): + if info.exists() and (eng / EXE).exists() and json.loads(info.read_text()).get("backend") != "hip": meta = json.loads(info.read_text()) ver = tuple(int(x) for x in str(meta.get("version", "0")).split(".")[:3] if x.isdigit()) if meta.get("source") == "local": # compiled here: build_engine checks its source and cards @@ -1311,6 +1600,21 @@ def update_installed_engine(url_base) -> None: return meta_text = info.read_text() meta = json.loads(meta_text) + if meta.get("backend") == "hip" and WIN: # AMD on Windows: the ready-made HIP engine, when older + ver = tuple(int(x) for x in str(meta.get("version", "0")).split(".")[:3] if x.isdigit()) + if meta.get("source") == "prebuilt" and ver < WIN_HIP_MIN_ENGINE: + try: + g = next((x for x in amd_gpus() if amd_problem(x) is None), None) + if g is None: + raise RuntimeError("no supported AMD GPU found") + say(f" Updating the ready-made AMD engine ({meta.get('version')} -> " + f"{'.'.join(map(str, WIN_HIP_MIN_ENGINE))} or newer) ...") + if get_prebuilt_hip(url_base, g, updating=True) is None: + raise RuntimeError("not published yet") + except (Exception, SystemExit) as e: + warn(f"could not update the AMD engine{'' if isinstance(e, SystemExit) else f' ({e})'}: " + "starting the installed one") + return if meta.get("backend") == "hip": # AMD: compiled here, again when its source changed if meta.get("src") != source_hash(ENGINE_SOURCES): try: @@ -2286,7 +2590,7 @@ def main() -> int: "experts fit on the GPU); auto: when the RAM has room for it") ap.add_argument("--backend", choices=["cuda", "hip"], help="cuda = NVIDIA (default), hip = AMD RX 7900 / 7800 / 7700 XT, RX 9060 XT / 9070 / AI PRO R9700 on " - "Linux (experimental; chosen by itself when the PC has no NVIDIA card Strata can use)") + "Linux or Windows (experimental; chosen by itself when the PC has no NVIDIA card Strata can use)") ap.add_argument("--skip-build", action="store_true", help=argparse.SUPPRESS) a = ap.parse_args() if a.resident_budget_gib is not None and not a.resident_budget_gib > 0: @@ -2362,7 +2666,7 @@ def main() -> int: # ---- 1. the PC step(1, "checking your PC") found = gpus() - amd = [] if WIN else amd_gpus() + amd = amd_gpus() nv_ok = any(gpu_problem(g) is None for g in found) amd_ok = [g for g in amd if amd_problem(g) is None] hip = a.backend == "hip" or (a.backend is None and not nv_ok and bool(amd_ok)) @@ -2373,19 +2677,20 @@ def main() -> int: say(" 1) NVIDIA: " + ", ".join(f"{g['name']} ({g['vram_gb']:.0f} GB)" for g in found if gpu_problem(g) is None) + " (recommended)") say(" 2) AMD: " + ", ".join(f"{g['name']} ({g['vram_gb']:.0f} GB)" for g in amd_ok) - + " (experimental: compiled here, no images - docs/AMD_HIP.md)") + + f" (experimental: {'the ready-made AMD engine' if WIN else 'compiled here'}, no images - docs/AMD_HIP.md)") hip = ask("Which cards?", ["1", "2"], "1", a.yes or a.check) == "2" if a.check and not hip: - say(" (the AMD card: ./setup.sh --backend hip)") - if hip: # AMD (experimental): compiled here - if WIN: - fail("Strata's AMD backend runs on Linux only", "use an NVIDIA RTX 20 series or newer card on Windows") - say(" Your AMD GPUs:" if amd else " No AMD GPU found (the amdgpu driver's KFD topology is empty).") + say(f" (the AMD card: {'START-HERE.bat' if WIN else './setup.sh'} --backend hip)") + if hip: # AMD (experimental): compiled here; Windows: ready-made + if WIN and a.gpus: + fail("several AMD cards sharing one model (--gpus) is Linux-only for now", "use one card: --gpu N") + say(" Your AMD GPUs:" if amd else " No AMD GPU found (" + ("Windows lists no AMD display adapter)." if WIN + else "the amdgpu driver's KFD topology is empty).")) for g in amd: say(f" GPU {g['index']}: {g['name']}, {g['vram_gb']:.0f} GB VRAM - " + (amd_problem(g) or "can be used")) usable = [g for g in amd if amd_problem(g) is None] if not usable: - fail("no AMD GPU Strata can use", f"the AMD backend runs on {AMD_CARDS} on Linux") + fail("no AMD GPU Strata can use", f"the AMD backend runs on {AMD_CARDS}") if a.gpus: # a layer split across these cards, the first one the main chosen = amd_parse_gpus(a.gpus, amd) gpu = chosen[0] @@ -2685,8 +2990,17 @@ def main() -> int: step(4, "the Strata engine") llama = get_llama_cpp() ok(f"llama.cpp {LLAMA_CPP_COMMIT[:7]} (gguf-py, ggml, mtmd)") - eng = None if a.build or hip else get_prebuilt(a.prebuilt, gpu, vision) - if eng is not None and json.loads((eng / "BUILD.json").read_text()).get("source") != "local": + if hip and WIN: # AMD on Windows: the ready-made HIP engine (no compiler) + eng = None if a.build else get_prebuilt_hip(a.prebuilt, gpu) + if eng is None: + fail("no ready-made AMD engine for this Strata version" + (" (--build)" if a.build else ""), + "compiling it on Windows: tools\\hip\\build_windows.bat makes strata-windows-x64-hip.zip, then run " + "START-HERE.bat --backend hip --prebuilt (docs/AMD_HIP.md)") + gpu = hip_card(eng, gpu, amd) + a.gpu = gpu["index"] if gpu["count"] > 1 else a.gpu + else: + eng = None if a.build or hip else get_prebuilt(a.prebuilt, gpu, vision) + if eng is not None and not hip and json.loads((eng / "BUILD.json").read_text()).get("source") != "local": pip_install(CUDA_WHEELS, "NVIDIA CUDA libraries (cuBLAS, CUDA runtime; ~0.4 GB)") if vision != "none" and not (eng / VEXE).exists(): warn("the ready-made engine has no image encoder: compiling it") @@ -2696,7 +3010,10 @@ def main() -> int: if eng is None: eng = build_engine_hip(gpu, llama, vision) if hip else build_engine(gpu, vision, a.yes, llama) meta = json.loads((eng / "BUILD.json").read_text()) - lib_dirs = meta.get("lib_dirs") or meta.get("cuda_dirs") or cuda_lib_dirs() + if hip and WIN: # the ready-made engine's rocm/bin, first on the engine's PATH + lib_dirs = [str(d) for d in hip_lib_dirs(eng)] + else: + lib_dirs = meta.get("lib_dirs") or meta.get("cuda_dirs") or cuda_lib_dirs() engine_ver = tuple(int(x) for x in str(meta.get("version", "0")).split(".")[:3] if x.isdigit()) if budget is not None and engine_ver < UNSLOTH_ENGINE: # checked before the 111 GB download fail(f"{model} needs engine {'.'.join(map(str, UNSLOTH_ENGINE))} or newer; this one is {meta.get('version')}", @@ -2853,7 +3170,7 @@ def main() -> int: # the dense prompt GEMMs through hipBLASLt with kernels measured on this GPU generation (tools/hip; +40-60% # prompt speed on the 7900 XTX): only a table for this card's arch AND the installed hipBLASLt version (the # engine refuses any other one and falls back to plain hipBLAS) - table = hipblaslt_table(gpu["arch"], lib_dirs) + table = hipblaslt_table(gpu["arch"], lib_dirs, meta.get("hipblaslt_version")) if table: cfg["env"] = {"STRATA_HIPBLASLT_TUNING": str(table)} if resident: # ROCm: large page-locked host allocations can fail or be slow for the CPU; keep the copy pageable diff --git a/src/core/device.cu b/src/core/device.cu index 814635a6..721028c9 100644 --- a/src/core/device.cu +++ b/src/core/device.cu @@ -73,6 +73,34 @@ const char* compiled_gpu_archs() { #endif } +int device_count() { + int count = 0; + if (cudaGetDeviceCount(&count) != cudaSuccess) { // HIP without a usable device reports an error, not 0 + cudaGetLastError(); + return 0; + } + return count < 0 ? 0 : count; +} + +bool device_summary(int ordinal, std::string& name, std::string& detail) { + cudaDeviceProp p{}; + if (ordinal < 0 || ordinal >= device_count() || cudaGetDeviceProperties(&p, ordinal) != cudaSuccess) { + cudaGetLastError(); + return false; + } + char buf[160]; +#if defined(STRATA_USE_HIP) + std::snprintf(buf, sizeof(buf), "arch %s, %.1f GiB, wave%d", base_arch(p.gcnArchName).c_str(), + (double) p.totalGlobalMem / (1024.0 * 1024 * 1024), p.warpSize); +#else + std::snprintf(buf, sizeof(buf), "compute capability %d.%d, %.1f GiB", p.major, p.minor, + (double) p.totalGlobalMem / (1024.0 * 1024 * 1024)); +#endif + name = p.name; + detail = buf; + return true; +} + std::string gpu_arch_problem(int ordinal) { #if defined(STRATA_USE_HIP) int count = 0; diff --git a/src/core/device_main.cpp b/src/core/device_main.cpp index 524e7b18..ff5adf51 100644 --- a/src/core/device_main.cpp +++ b/src/core/device_main.cpp @@ -19,10 +19,14 @@ static std::string human(uint64_t b) { int main(int argc, char** argv) { bool selftest = false; + bool list_devices = false; for (int i = 1; i < argc; ++i) { if (std::strcmp(argv[i], "--selftest") == 0) selftest = true; + else if (std::strcmp(argv[i], "--list-devices") == 0) list_devices = true; else if (std::strcmp(argv[i], "--help") == 0 || std::strcmp(argv[i], "-h") == 0) { - std::printf("usage: strata-device [--selftest]\n"); + std::printf("usage: strata-device [--selftest] [--list-devices]\n" + " --list-devices every GPU the runtime enumerates, numbered as HIP_VISIBLE_DEVICES /\n" + " CUDA_VISIBLE_DEVICES number them, and whether this binary can run it\n"); return 0; } else { std::fprintf(stderr, "unknown argument: %s\n", argv[i]); @@ -30,6 +34,28 @@ int main(int argc, char** argv) { } } + // The runtime's numbering, which setup needs on Windows: there an integrated Radeon is HIP device 0 and pushes the + // discrete card to 1, while setup finds the cards in the display-adapter order (#325). No arch check here - the + // cards this binary has no code for are part of the answer. Format (setup.py's hip_devices parses it): + // device N: + // arch gfx1201, 15.9 GiB, wave32 (CUDA: compute capability 12.0, 11.9 GiB) + // cannot run: (only for a card this binary cannot run) + if (list_devices) { + const int count = strata::core::device_count(); + if (count == 0) std::printf("(no GPU device)\n"); + for (int ordinal = 0; ordinal < count; ++ordinal) { + std::string name, detail; + if (!strata::core::device_summary(ordinal, name, detail)) { + std::printf("device %d: (the runtime cannot describe it)\n", ordinal); + continue; + } + std::printf("device %d: %s\n %s\n", ordinal, name.c_str(), detail.c_str()); + if (const std::string why = strata::core::gpu_arch_problem(ordinal); !why.empty()) + std::printf(" cannot run: %s\n", why.c_str()); + } + return 0; + } + try { const strata::core::DeviceInfo d = strata::core::device_info(0); std::printf("device %d: %s\n", d.ordinal, d.name.c_str()); diff --git a/src/core/native_head.cpp b/src/core/native_head.cpp index e47dfe14..acb4f81f 100644 --- a/src/core/native_head.cpp +++ b/src/core/native_head.cpp @@ -150,10 +150,31 @@ bool NativeEmbed::load(const std::vector& shards, int64_t n_embd, i } else { std::memcpy(host_, gguf.tensor_data(*t), bytes_); void* d = nullptr; +#if defined(STRATA_USE_HIP) + // #325: the Windows HIP stack can refuse the device alias of a mapped allocation (and, when it gives + // one, it is the host address itself - unified addressing; kernels read it correctly there, a + // device-to-device copy into it does not land: tests/hip/mapped_alias). The table is only gathered from, + // so without an alias it goes into VRAM like the unpinnable case above, instead of failing the start. + if (cudaHostGetDevicePointer(&d, host_, 0) != cudaSuccess || d == nullptr) { + cudaGetLastError(); + d = nullptr; + if (cudaMalloc(&d, bytes_) != cudaSuccess || + cudaMemcpy(d, gguf.tensor_data(*t), bytes_, cudaMemcpyHostToDevice) != cudaSuccess) { + if (d) cudaFree(d); + cudaGetLastError(); + err = "native embedding: no device alias for the mapped table, and no VRAM to copy it into"; + return false; + } + cudaFreeHost(host_); // the destructor frees dev_ when host_ is null + host_ = nullptr; + std::fprintf(stderr, "strata: native embedding: no device alias for the mapped table, kept in VRAM\n"); + } +#else if (cudaHostGetDevicePointer(&d, host_, 0) != cudaSuccess) { err = "native embedding: no device alias for the mapped table"; return false; } +#endif dev_ = d; } type_ = (int) t->type; diff --git a/src/prefill/gemm.cu b/src/prefill/gemm.cu index 328c8ae4..bb6ef045 100644 --- a/src/prefill/gemm.cu +++ b/src/prefill/gemm.cu @@ -42,6 +42,23 @@ void ck(cublasStatus_t s, const char* what) { } } +// #247/#325: on Windows (seen on gfx1201), hipBLAS can return success with the correct BF16/FP16 product for some +// shapes (hc up once T >= 96, the router) and still leave hipErrorInvalidValue set, which the next kernel's error +// check turns into an exit. The multiply has finished, so that one stale error is cleared after a GEMM that succeeded; +// any other error still stops the engine. Windows only: on Linux a stale hipErrorInvalidValue is a real error from +// an earlier call and keeps being reported. A no-op everywhere else (CUDA compiles none of it). +#if defined(__HIPCC__) && defined(_WIN32) +void absorb_hipblas_sticky(const char* what) { + const hipError_t sticky = hipGetLastError(); + if (sticky == hipSuccess || sticky == hipErrorInvalidValue) return; + std::fprintf(stderr, "prefill gemm: %s left %s\n", what, hipGetErrorString(sticky)); + std::exit(1); +} +#define STRATA_ABSORB_HIPBLAS_STICKY(what) absorb_hipblas_sticky(what) +#else +#define STRATA_ABSORB_HIPBLAS_STICKY(what) ((void) 0) +#endif + // A setup call whose failure the engine survives (the handle keeps its defaults), as before #240 - but said. void note(cublasStatus_t s, const char* what) { if (s != CUBLAS_STATUS_SUCCESS) std::fprintf(stderr, "prefill gemm: %s: cuBLAS status %d (continuing)\n", what, (int) s); @@ -363,6 +380,7 @@ void Gemm::bf16(const uint16_t* X, const uint16_t* W, float* Y, int64_t T, int64 #if defined(__HIPCC__) && defined(STRATA_HIPBLASLT_AVAILABLE) if (try_hipblaslt(hipblaslt_state_, strata::prefill::hipblaslt::InputType::bf16, X, W, Y, T, N, K, ldy, beta, stream_)) { + STRATA_ABSORB_HIPBLAS_STICKY("hipBLASLt bf16"); return; } #endif @@ -371,6 +389,7 @@ void Gemm::bf16(const uint16_t* X, const uint16_t* W, float* Y, int64_t T, int64 CUDA_R_16BF, (int) K, X, CUDA_R_16BF, (int) K, &beta, Y, CUDA_R_32F, (int) ldy, CUBLAS_COMPUTE_32F, CUBLAS_GEMM_DEFAULT), "cublasGemmEx"); + STRATA_ABSORB_HIPBLAS_STICKY("cublasGemmEx"); } void Gemm::f16(const uint16_t* X, const uint16_t* W, float* Y, int64_t T, int64_t N, int64_t K, int64_t ldy, @@ -381,6 +400,7 @@ void Gemm::f16(const uint16_t* X, const uint16_t* W, float* Y, int64_t T, int64_ #if defined(__HIPCC__) && defined(STRATA_HIPBLASLT_AVAILABLE) if (try_hipblaslt(hipblaslt_state_, strata::prefill::hipblaslt::InputType::f16, X, W, Y, T, N, K, ldy, beta, stream_)) { + STRATA_ABSORB_HIPBLAS_STICKY("hipBLASLt f16"); return; } #endif @@ -388,6 +408,7 @@ void Gemm::f16(const uint16_t* X, const uint16_t* W, float* Y, int64_t T, int64_ CUDA_R_16F, (int) K, X, CUDA_R_16F, (int) K, &beta, Y, CUDA_R_32F, (int) ldy, CUBLAS_COMPUTE_32F, CUBLAS_GEMM_DEFAULT), "cublasGemmEx f16"); + STRATA_ABSORB_HIPBLAS_STICKY("cublasGemmEx f16"); } void Gemm::native(const uint16_t* X, int ggml_type, const void* W_blocks, float* Y, int64_t T, int64_t N, int64_t K, diff --git a/tests/hip/mapped_alias.cpp b/tests/hip/mapped_alias.cpp new file mode 100644 index 00000000..0507bb87 --- /dev/null +++ b/tests/hip/mapped_alias.cpp @@ -0,0 +1,108 @@ +// Is a hipHostGetDevicePointer alias usable on this stack? (#325) +// +// tests/hip/handoff.cpp fails on gfx1201/Windows with "separate copy/ring timeout": it does a +// hipMemcpyAsync(..., hipMemcpyDeviceToDevice) into a hipHostGetDevicePointer alias, then waits for +// a doorbell that copy should have published. This test pins down the properties that decide it. +// +// On Linux the alias is a device address of the pinned host memory, a D2D copy lands, the host sees +// it, and a kernel reads it. On Windows (#325, RX 9070 XT) the runtime hands back the HOST pointer +// itself (unified addressing; this test prints both addresses), and a D2D copy into it does not +// publish - hip_handoff's timeout there. The engine itself runs on Windows (the reporter's serving +// run gave correct answers), so kernels reading mapped memory through that address work; only the +// copy-engine path does not. src/core/native_head.cpp keeps the token embedding in VRAM when the +// alias is refused outright. +// +// Reporting, not gating: a Windows host is EXPECTED to fail some checks below, so this test exits 0 +// whenever it ran at all, and 77 (skipped) without a device. When the alias IS the host pointer the +// D2D copy is not attempted (it may fault rather than report); the kernel read is, since that is +// what the engine relies on. + +#include "strata/kernels/elementwise.hpp" + +#include + +#include +#include + +namespace { + +int not_held = 0; + +void report(const char* what, bool holds) { + std::printf(" %-44s %s\n", what, holds ? "holds" : "DOES NOT HOLD"); + if (!holds) ++not_held; +} + +// A kernel reads `n` floats through `alias` into VRAM; the result is copied back and compared. +bool kernel_reads(const float* alias, const std::vector& want) { + const int64_t n = (int64_t) want.size(); + float* out = nullptr; + if (hipMalloc(reinterpret_cast(&out), want.size() * sizeof(float)) != hipSuccess) return false; + strata::kernels::copy_from_mapped(out, alias, n, nullptr); + std::vector got(want.size(), -1.0f); + const bool ran = hipDeviceSynchronize() == hipSuccess && + hipMemcpy(got.data(), out, want.size() * sizeof(float), hipMemcpyDeviceToHost) == hipSuccess; + hipFree(out); + hipGetLastError(); + return ran && got == want; +} + +} // namespace + +int main() { + int runtime = 0; + if (hipRuntimeGetVersion(&runtime) != hipSuccess) return 1; + int count = 0; + if (hipGetDeviceCount(&count) != hipSuccess || count < 1) { + std::printf("no HIP device\n"); + return 77; // ctest "skipped" + } + std::printf("HIP runtime %d, %d device(s)\n", runtime, count); + + const int64_t n = 4096; // enough elements for copy_from_mapped's float4 path + const size_t bytes = size_t(n) * sizeof(float); + std::vector pattern(size_t(n), 0.0f); + for (int64_t i = 0; i < n; ++i) pattern[size_t(i)] = float(i + 1); + + float* host = nullptr; + if (hipHostMalloc(reinterpret_cast(&host), bytes, hipHostMallocMapped) != hipSuccess) return 1; + void* alias = nullptr; + if (hipHostGetDevicePointer(&alias, host, 0) != hipSuccess || alias == nullptr) { + std::printf("hipHostGetDevicePointer failed: native_head.cpp keeps the embedding in VRAM here\n"); + hipGetLastError(); + hipHostFree(host); + return 0; + } + const bool distinct = alias != reinterpret_cast(host); + std::printf("\n host %p\n alias %p\n -> %s\n\n", static_cast(host), alias, + distinct ? "a distinct device address" : "the host pointer itself (unified addressing)"); + report("the alias is a distinct device address", distinct); + + // What the engine relies on: a kernel reading mapped host memory through the alias. + for (int64_t i = 0; i < n; ++i) host[i] = pattern[size_t(i)]; + report("a kernel reads the alias correctly", kernel_reads(reinterpret_cast(alias), pattern)); + + // What tests/hip/handoff.cpp attempts: a DeviceToDevice copy INTO the alias, seen by the host. + if (distinct) { + float* device = nullptr; + std::vector twice(pattern); + for (float& v : twice) v *= 2.0f; + if (hipMalloc(reinterpret_cast(&device), bytes) == hipSuccess && + hipMemcpy(device, twice.data(), bytes, hipMemcpyHostToDevice) == hipSuccess) { + const hipError_t copy = hipMemcpy(alias, device, bytes, hipMemcpyDeviceToDevice); + report("a D2D copy into the alias succeeds", copy == hipSuccess); + bool seen = hipDeviceSynchronize() == hipSuccess; + for (int64_t i = 0; seen && i < n; ++i) seen = host[i] == twice[size_t(i)]; + report("the host sees a D2D copy into the alias", seen); + } + if (device) hipFree(device); + hipGetLastError(); + } else { + std::printf(" the D2D copy into the alias is not attempted: with alias == host it may fault rather than\n" + " report (tests/hip/handoff's timeout on Windows)\n"); + } + + std::printf("\n%d check(s) did not hold (a Windows host is expected to fail some)\n", not_held); + hipHostFree(host); + return 0; +} diff --git a/tools/hip/build_windows.bat b/tools/hip/build_windows.bat new file mode 100644 index 00000000..b3d0011c --- /dev/null +++ b/tools/hip/build_windows.bat @@ -0,0 +1,86 @@ +@echo off +rem Strata's HIP (AMD) engine for Windows, and the ready-made zip setup.py downloads (strata-windows-x64-hip.zip). +rem +rem tools\hip\build_windows.bat build strata.exe + strata-device.exe and package dist\strata-windows-x64-hip.zip +rem tools\hip\build_windows.bat tests also build the HIP unit tests (ctest in build-hip-win; they need an AMD GPU) +rem +rem Needs: Visual Studio 2022 (or 2019) Build Tools with the C++ workload (the linker, the CRT and the Windows SDK), +rem Python 3.10+ and git. No admin rights and no AMD GPU: ROCm comes from AMD's TheRock Python wheels (the same +rem ROCm 10.2 nightly #325 ran on an RX 9070 XT), installed into a private venv (ROCM_VENV, ~7 GB). CMake refuses to +rem mix cl.exe with Clang for HIP, so ROCm's clang compiles the host code too (targeting the MSVC ABI, with MSVC's +rem headers and linker from vcvars); cmake/hip_backend.cmake force-includes the CUDA->HIP shim. +rem +rem Settings (environment variables, all optional): +rem STRATA_HIP_ARCHS gfx1100;gfx1101;gfx1102;gfx1200;gfx1201;gfx1030 (the cards setup supports, + gfx1102) +rem STRATA_ROCM_VERSION 10.2.0a20260930 STRATA_ROCM_INDEX https://nightly.repo.amd.com/rocm/whl-next/ +rem ROCM_VENV \.rocm-win BUILD_DIR \build-hip-win DIST_DIR \dist +rem STRATA_GGML_DIR a llama.cpp checkout at the pinned commit (default: CMake fetches it) +setlocal EnableDelayedExpansion +for %%I in ("%~dp0..\..") do set "SRC=%%~fI" +if not defined STRATA_HIP_ARCHS set "STRATA_HIP_ARCHS=gfx1100;gfx1101;gfx1102;gfx1200;gfx1201;gfx1030" +if not defined STRATA_ROCM_VERSION set "STRATA_ROCM_VERSION=10.2.0a20260930" +if not defined STRATA_ROCM_INDEX set "STRATA_ROCM_INDEX=https://nightly.repo.amd.com/rocm/whl-next/" +if not defined ROCM_VENV set "ROCM_VENV=%SRC%\.rocm-win" +if not defined BUILD_DIR set "BUILD_DIR=%SRC%\build-hip-win" +if not defined DIST_DIR set "DIST_DIR=%SRC%\dist" +set "TESTS=OFF" +if /i "%~1"=="tests" set "TESTS=ON" + +rem ---- 1. ROCm (TheRock wheels: the compiler, the HIP runtime, hipBLAS/hipBLASLt/rocBLAS, a device package per arch) +set "PY=" +py -3 -c "import sys" >nul 2>nul && set "PY=py -3" +if not defined PY python -c "import sys" >nul 2>nul && set "PY=python" +if not defined PY (echo Python 3.10+ is needed & exit /b 1) +if not exist "%ROCM_VENV%\Scripts\python.exe" %PY% -m venv "%ROCM_VENV%" || exit /b 1 +set "EXTRAS=libraries,devel" +for %%A in (%STRATA_HIP_ARCHS:;= %) do set "EXTRAS=!EXTRAS!,device-%%A" +set "STAMP=%ROCM_VENV%\strata-rocm.txt" +set "WANT=%STRATA_ROCM_VERSION% %EXTRAS%" +set "HAVE=" +if exist "%STAMP%" set /p HAVE=<"%STAMP%" +if not "!HAVE!"=="!WANT!" ( + echo Installing ROCm %STRATA_ROCM_VERSION% [%EXTRAS%] into %ROCM_VENV% ... + "%ROCM_VENV%\Scripts\python.exe" -m pip install --disable-pip-version-check --index-url "%STRATA_ROCM_INDEX%" "rocm[%EXTRAS%]==%STRATA_ROCM_VERSION%" || exit /b 1 + "%ROCM_VENV%\Scripts\rocm-sdk.exe" init || exit /b 1 + >"%STAMP%" echo !WANT! +) +for /f "delims=" %%R in ('"%ROCM_VENV%\Scripts\rocm-sdk.exe" path --root') do set "ROCM=%%R" +if not exist "%ROCM%\lib\llvm\bin\clang++.exe" (echo ROCm has no compiler in "%ROCM%" & exit /b 1) +set "ROCM_F=%ROCM:\=/%" +set "BITCODE=%ROCM_F%/lib/llvm/amdgcn/bitcode" + +rem ---- 2. MSVC: the linker, the C runtime and the Windows SDK (ROCm's clang uses them) +set "VSWHERE=%ProgramFiles(x86)%\Microsoft Visual Studio\Installer\vswhere.exe" +set "VS=" +if exist "%VSWHERE%" for /f "delims=" %%V in ('"%VSWHERE%" -latest -products * -requires Microsoft.VisualStudio.Component.VC.Tools.x86.x64 -property installationPath') do set "VS=%%V" +if not defined VS (echo Visual Studio Build Tools with the C++ workload are needed & exit /b 1) +call "%VS%\VC\Auxiliary\Build\vcvars64.bat" >nul || exit /b 1 +set "HIP_PLATFORM=amd" +set "HIP_PATH=%ROCM%" +set "ROCM_PATH=%ROCM%" +set "PATH=%ROCM%\bin;%ROCM%\lib\llvm\bin;%PATH%" + +rem ---- 3. configure + build (STRATA_PORTABLE: the CPU kernels for an AVX2 baseline, as in the NVIDIA zip) +set "GGML=" +if defined STRATA_GGML_DIR set "GGML=-DSTRATA_GGML_DIR=%STRATA_GGML_DIR:\=/%" +if not exist "%BUILD_DIR%\build.ninja" ( + cmake -G Ninja -S "%SRC%" -B "%BUILD_DIR%" -DCMAKE_BUILD_TYPE=Release ^ + -DSTRATA_ENABLE_HIP=ON -DSTRATA_ENABLE_CUDA=OFF -DSTRATA_BUILD_TESTS=%TESTS% -DSTRATA_PREFILL_MMQ=ON ^ + -DSTRATA_NATIVE_EXPERTS=ON -DSTRATA_PORTABLE=ON "-DCMAKE_HIP_ARCHITECTURES=%STRATA_HIP_ARCHS%" ^ + "-DCMAKE_C_COMPILER=%ROCM_F%/lib/llvm/bin/clang.exe" "-DCMAKE_CXX_COMPILER=%ROCM_F%/lib/llvm/bin/clang++.exe" ^ + "-DCMAKE_HIP_COMPILER=%ROCM_F%/lib/llvm/bin/clang++.exe" "-DCMAKE_HIP_COMPILER_ROCM_ROOT=%ROCM_F%" ^ + "-DCMAKE_PREFIX_PATH=%ROCM_F%" "-DCMAKE_HIP_FLAGS=--rocm-path=%ROCM_F% --rocm-device-lib-path=%BITCODE%" ^ + %GGML% || exit /b 1 +) +if "%TESTS%"=="ON" ( + cmake --build "%BUILD_DIR%" || exit /b 1 +) else ( + cmake --build "%BUILD_DIR%" --target strata strata-device || exit /b 1 +) + +rem ---- 4. the zip: the two programs, the ROCm DLLs they load (+ rocBLAS/hipBLASLt kernels for these archs), licenses +"%ROCM_VENV%\Scripts\python.exe" "%SRC%\tools\hip\package_windows.py" --build "%BUILD_DIR%" --rocm "%ROCM%" ^ + --archs "%STRATA_HIP_ARCHS%" --rocm-version "%STRATA_ROCM_VERSION%" --out "%DIST_DIR%" || exit /b 1 +echo. +echo Done: %DIST_DIR%\strata-windows-x64-hip.zip +endlocal diff --git a/tools/hip/package_windows.py b/tools/hip/package_windows.py new file mode 100644 index 00000000..b7ee3d59 --- /dev/null +++ b/tools/hip/package_windows.py @@ -0,0 +1,159 @@ +#!/usr/bin/env python3 +"""Package the Windows HIP engine as the ready-made zip setup.py downloads (strata-windows-x64-hip.zip). + + python tools/hip/package_windows.py --build build-hip-win --rocm \\ + --archs "gfx1100;gfx1201" --rocm-version 10.2.0a20260930 --out dist + +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) + 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 + rocm/bin/rocblas/library, rocm/bin/hipblaslt/library the GEMM kernels, for these archs only + rocm/.kpack/ rocBLAS's own device code for these archs (rocblas.dll finds it at + ../.kpack from its folder) + rocm/licenses/ the shipped components' licenses, and NOTICE.txt + +setup.py puts rocm/bin first on the engine's PATH (the config's lib_dirs). The AMD display driver (AMD Software: +Adrenalin Edition) is the only thing the user installs: TheRock's HIP runtime runs on top of it. +""" +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import zipfile +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[2] +ASSET = "strata-windows-x64-hip.zip" +PROGRAMS = ("strata.exe", "strata-device.exe") +DYNAMIC = ("amd_comgr.dll",) # LoadLibrary'd by amdhip64_7.dll: not in any import table +CRT = ("msvcp140.dll", "msvcp140_1.dll", "msvcp140_2.dll", "vcruntime140.dll", "vcruntime140_1.dll") +KPACKS = ("blas_lib",) # rocblas.dll's own device code; rocSOLVER's (27 MB per arch) is never launched by Strata +LICENSES = ("rocblas", "rocsolver", "hipblas", "hipblas-common", "hipblaslt", "amd_comgr", "rocm-core") +NOTICE = """Strata's Windows HIP engine ships these AMD ROCm components unmodified, from AMD's TheRock Python wheels +(ROCm {rocm}, https://nightly.repo.amd.com/rocm/whl-next/, built from https://github.com/ROCm/TheRock): + +{dlls} + +Licenses: rocBLAS, hipBLAS, hipBLAS-common, hipBLASLt (and its TensileLite host and origami libraries), rocm-core: MIT; +rocSOLVER: BSD 2-clause; amd_comgr: Apache 2.0 with LLVM exceptions (files in this folder). The HIP runtime +(amdhip64_7.dll, https://github.com/ROCm/rocm-systems/tree/develop/projects/clr) and rocm_kpack.dll (TheRock) are MIT +licensed; their wheels carry no license file. The Microsoft Visual C++ runtime DLLs (msvcp140*.dll, +vcruntime140*.dll) are redistributable under the Visual Studio license (Distributable Code). +""" + + +def imports(objdump: Path, dll: Path) -> list[str]: + text = subprocess.run([str(objdump), "-p", str(dll)], capture_output=True, text=True, check=True).stdout + return [m.group(1) for m in re.finditer(r"DLL Name:\s*(\S+)", text)] + + +def crt_dir() -> Path | None: + """The MSVC redist folder with the C++ runtime DLLs (vcvars sets VCToolsRedistDir).""" + base = os.environ.get("VCToolsRedistDir") + if not base: + return None + hits = sorted(Path(base, "x64").glob("Microsoft.VC*.CRT")) + return hits[-1] if hits else None + + +def main() -> int: + ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + ap.add_argument("--build", required=True, type=Path) + ap.add_argument("--rocm", required=True, type=Path, help="the ROCm root (rocm-sdk path --root)") + ap.add_argument("--archs", required=True, help="the archs the engine was compiled for, ';'-separated") + ap.add_argument("--rocm-version", required=True) + ap.add_argument("--out", required=True, type=Path) + a = ap.parse_args() + archs = [x for x in re.split(r"[;, ]+", a.archs) if x] + rbin = a.rocm / "bin" + objdump = a.rocm / "lib" / "llvm" / "bin" / "llvm-objdump.exe" + stage = a.out / "strata-windows-x64-hip" + shutil.rmtree(stage, ignore_errors=True) + (stage / "rocm" / "bin").mkdir(parents=True) + + for p in PROGRAMS: + shutil.copy2(a.build / p, stage / p) + + # the ROCm DLLs: the programs' imports, followed through the ROCm DLLs themselves + rocm_dlls = {p.name.lower(): p for p in rbin.glob("*.dll")} + need, todo, crt = [], [stage / p for p in PROGRAMS] + [rbin / d for d in DYNAMIC], set() + while todo: + f = todo.pop() + for name in imports(objdump, f): + low = name.lower() + if low in CRT: + crt.add(low) + elif low in rocm_dlls and low not in need: + need.append(low) + todo.append(rocm_dlls[low]) + for d in DYNAMIC: + if d not in need: + need.append(d) + for d in sorted(need): + shutil.copy2(rocm_dlls[d], stage / "rocm" / "bin" / rocm_dlls[d].name) + cdir = crt_dir() + if cdir is None: + sys.exit("VCToolsRedistDir is not set: run this from a Visual Studio x64 developer prompt (vcvars64.bat)") + for d in sorted(crt): + shutil.copy2(cdir / d, stage / "rocm" / "bin" / d) + + # the GEMM kernels and the libraries' own device code, for these archs + lib = stage / "rocm" / "bin" / "rocblas" / "library" + lib.mkdir(parents=True) + for f in (rbin / "rocblas" / "library").iterdir(): + m = re.search(r"gfx[0-9a-f]+", f.name) + if m is None or m.group() in archs: + shutil.copy2(f, lib / f.name) + for arch in archs: + src = rbin / "hipblaslt" / "library" / arch + if src.is_dir(): # hipBLASLt has no RDNA2 (gfx1030) kernels + shutil.copytree(src, stage / "rocm" / "bin" / "hipblaslt" / "library" / arch) + kp = stage / "rocm" / ".kpack" + kp.mkdir() + kpack_src = a.rocm / ".kpack" + for arch in archs: + for k in KPACKS: + f = kpack_src / f"{k}_{arch}.kpack" + if not f.exists(): + sys.exit(f"missing {f}: install the rocm-sdk-device-{arch} wheel and run rocm-sdk init") + shutil.copy2(f, kp / f.name) + + lic = stage / "rocm" / "licenses" + lic.mkdir() + for comp in LICENSES: + for f in (a.rocm / "share" / "doc" / comp).glob("LICENSE*"): + shutil.copy2(f, lic / f"{comp}-{f.name}") + shipped = sorted(p.name for p in (stage / "rocm" / "bin").glob("*.dll")) + (lic / "NOTICE.txt").write_text(NOTICE.format(rocm=a.rocm_version, dlls="\n".join(" " + d for d in shipped)), + encoding="utf-8") + + version = re.search(r"project\(strata VERSION ([\d.]+)", (ROOT / "CMakeLists.txt").read_text()).group(1) + hl = (a.rocm / "include" / "hipblaslt" / "hipblaslt-version.h").read_text() + hlv = [int(re.search(rf"#define\s+HIPBLASLT_VERSION_{k}\s+(\d+)", hl).group(1)) for k in ("MAJOR", "MINOR", "PATCH")] + meta = {"source": "prebuilt", "backend": "hip", "platform": "windows-x64", "version": version, "archs": archs, + "rocm": a.rocm_version, "hipblaslt_version": hlv[0] * 100000 + hlv[1] * 100 + hlv[2], "vision": "none", + "lib_dirs": ["rocm/bin"]} + (stage / "BUILD.json").write_text(json.dumps(meta, indent=1), encoding="utf-8") + + z = a.out / ASSET + z.unlink(missing_ok=True) + with zipfile.ZipFile(z, "w", zipfile.ZIP_DEFLATED, compresslevel=9) as f: + for p in sorted(stage.rglob("*")): + if p.is_file(): + f.write(p, p.relative_to(stage).as_posix()) + size = sum(p.stat().st_size for p in stage.rglob("*") if p.is_file()) + print(f"{z}: {z.stat().st_size / 2**20:.0f} MiB ({size / 2**20:.0f} MiB unpacked), engine {version}, " + f"{', '.join(archs)}, ROCm {a.rocm_version}, DLLs: {', '.join(shipped)}") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tools/test_setup_amd.py b/tools/test_setup_amd.py index 6c82c35f..fdca0eb4 100644 --- a/tools/test_setup_amd.py +++ b/tools/test_setup_amd.py @@ -9,6 +9,7 @@ from __future__ import annotations import sys import tempfile import unittest +from unittest import mock from pathlib import Path ROOT = Path(__file__).resolve().parents[1] @@ -152,5 +153,163 @@ class GpuLists(unittest.TestCase): setattr(setup, k, v) +class WindowsDetection(unittest.TestCase): + """Windows: the AMD cards from the display adapters (mocked Win32_VideoController rows and display-class registry + values), the HIP runtime's numbering from `strata-device --list-devices`, and the card setup chose matched to its + HIP ordinal (#325: an integrated Radeon is HIP's device 0).""" + ADAPTERS = [ # Win32_VideoController: name, PNPDeviceID, AdapterRAM (32-bit: at most 4 GB) + {"name": "NVIDIA GeForce RTX 5070", "pnp": r"PCI\VEN_10DE&DEV_2F04&SUBSYS_1234&REV_A1\4&1", "ram": 4293918720}, + {"name": "AMD Radeon RX 9070 XT", "pnp": r"PCI\VEN_1002&DEV_7550&SUBSYS_0E3B1002&REV_C0\6&2", "ram": 4293918720}, + {"name": "AMD Radeon(TM) Graphics", "pnp": r"PCI\VEN_1002&DEV_164E&SUBSYS_88771043&REV_C1\4&3", "ram": 536870912}, + {"name": "AMD Radeon RX 7800 XT", "pnp": r"PCI\VEN_1002&DEV_7499&SUBSYS_0000&REV_C8\6&4", "ram": 4293918720}, + ] + REGISTRY = [ # the display class's driver instances: 64-bit VRAM size (as int, or as bytes) + {"DriverDesc": "NVIDIA GeForce RTX 5070", "MatchingDeviceId": r"PCI\VEN_10DE&DEV_2F04", + "HardwareInformation.qwMemorySize": 12 << 30}, + {"DriverDesc": "AMD Radeon RX 6600", "MatchingDeviceId": r"PCI\VEN_1002&DEV_73FF", # a removed card + "HardwareInformation.qwMemorySize": 8 << 30}, + {"DriverDesc": "AMD Radeon RX 9070 XT", "MatchingDeviceId": r"PCI\VEN_1002&DEV_7550&REV_C0", + "HardwareInformation.qwMemorySize": (16 << 30).to_bytes(8, "little"), "DriverVersion": "32.0.21013.1000"}, + {"DriverDesc": "AMD Radeon(TM) Graphics", "MatchingDeviceId": r"PCI\VEN_1002&DEV_164E&REV_C1", + "HardwareInformation.qwMemorySize": 512 << 20}, + {"DriverDesc": "AMD Radeon RX 7800 XT", "MatchingDeviceId": r"PCI\VEN_1002&DEV_7499", + "HardwareInformation.qwMemorySize": 16 << 30}, + ] + LIST = ("device 0: AMD Radeon(TM) Graphics\n arch gfx1036, 28.1 GiB, wave32\n" + " cannot run: GPU 0 (AMD Radeon(TM) Graphics, gfx1036) is not an architecture this Strata engine was " + "compiled for (gfx1100,gfx1101,gfx1102,gfx1200,gfx1201,gfx1030); ...\n" + "device 1: AMD Radeon RX 9070 XT\n arch gfx1201, 15.9 GiB, wave32\n" + "device 2: AMD Radeon RX 7800 XT\n arch gfx1101, 16.0 GiB, wave32\n") + + def test_adapters(self): + g = setup.amd_gpus_windows(self.ADAPTERS, self.REGISTRY) + self.assertEqual([x["name"] for x in g], ["AMD Radeon RX 9070 XT", "AMD Radeon(TM) Graphics", + "AMD Radeon RX 7800 XT"]) # AMD only, present only, in order + self.assertEqual([x["index"] for x in g], [0, 1, 2]) + self.assertEqual(g[0]["arch"], "gfx1201") # by PCI device id + self.assertEqual(g[2]["arch"], "gfx1101") # an unlisted id: by its name + self.assertTrue(g[1]["arch"].startswith("unknown")) # the iGPU: listed, not supported + self.assertAlmostEqual(g[0]["vram_gb"], 16.0) # the registry's 64-bit size + self.assertEqual(g[0]["driver"], "32.0.21013.1000") + self.assertEqual([setup.amd_problem(x) is None for x in g], [True, False, True]) + + def test_registry_alone(self): + """No WMI answer: the registry's own list (which can hold a removed card).""" + g = setup.amd_gpus_windows([], self.REGISTRY) + self.assertEqual([x["arch"] for x in g if not x["arch"].startswith("unknown")], ["gfx1201", "gfx1101"]) + + def test_arch_names(self): + for name, arch in (("AMD Radeon RX 9070 GRE", "gfx1201"), ("AMD Radeon AI PRO R9700", "gfx1201"), + ("AMD Radeon RX 9060 XT", "gfx1200"), ("AMD Radeon RX 7900 GRE", "gfx1100"), + ("AMD Radeon PRO W7800", "gfx1100"), ("AMD Radeon RX 7700 XT", "gfx1101"), + ("AMD Radeon RX 7600", "gfx1102"), ("AMD Radeon RX 6950 XT", "gfx1030"), + ("AMD Radeon RX 6800M", ""), ("AMD Radeon 780M Graphics", ""), ("AMD Radeon RX 7700S", "")): + self.assertEqual(setup.win_amd_arch(None, name), arch, name) + self.assertEqual(setup.win_amd_arch(0x744C, "whatever"), "gfx1100") + + def test_list_devices(self): + h = setup.hip_devices(text=self.LIST) + self.assertEqual([(x["index"], x["arch"]) for x in h], [(0, "gfx1036"), (1, "gfx1201"), (2, "gfx1101")]) + self.assertAlmostEqual(h[1]["vram_gb"], 15.9) + self.assertIn("not an architecture", h[0]["cannot_run"]) + self.assertIsNotNone(setup.amd_problem(h[0])) + self.assertIsNone(setup.amd_problem(h[1])) + cannot = setup.hip_devices(text="device 0: AMD Radeon RX 9070 XT\n arch gfx1201, 15.9 GiB, wave32\n" + " cannot run: GPU 0 runs wave64\n") + self.assertEqual(setup.amd_problem(cannot[0]), "GPU 0 runs wave64") # the engine's own check counts + self.assertEqual(setup.hip_devices(text="(no GPU device)\n"), []) + + def test_the_card_by_its_hip_ordinal(self): + """#325: setup's GPU 0 (the 9070 XT, display order) is HIP's device 1 behind the iGPU.""" + listed = setup.amd_gpus_windows(self.ADAPTERS, self.REGISTRY) + hip = setup.hip_devices(text=self.LIST) + self.assertEqual(setup.hip_match(listed[0], listed, hip)["index"], 1) + self.assertEqual(setup.hip_match(listed[2], listed, hip)["index"], 2) + two = [{"index": 0, "arch": "gfx1201"}, {"index": 1, "arch": "gfx1201"}] # two of a kind: by rank + self.assertEqual(setup.hip_match(two[1], two, [{"index": 0, "arch": "gfx1036"}, {"index": 1, "arch": "gfx1201"}, + {"index": 2, "arch": "gfx1201"}])["index"], 2) + self.assertIsNone(setup.hip_match({"index": 0, "arch": "gfx1100"}, [{"index": 0, "arch": "gfx1100"}], hip)) + + def test_hip_card(self): + listed = setup.amd_gpus_windows(self.ADAPTERS, self.REGISTRY) + with mock.patch.object(setup, "hip_devices", lambda probe=None, text=None: setup_hip(self.LIST)), \ + mock.patch.object(setup, "ok", lambda *a: None): + g = setup.hip_card(Path("engine"), listed[0], listed) + self.assertEqual((g["index"], g["count"], g["arch"], g["vram_gb"]), (1, 3, "gfx1201", 15.9)) + with mock.patch.object(setup, "hip_devices", lambda probe=None, text=None: []), \ + mock.patch.object(setup, "say", lambda *a, **k: None), self.assertRaises(SystemExit): + setup.hip_card(Path("engine"), listed[0], listed) # no AMD driver: stops before the download + with mock.patch.object(setup, "hip_devices", lambda probe=None, text=None: setup_hip(self.LIST)[:1]), \ + mock.patch.object(setup, "say", lambda *a, **k: None), self.assertRaises(SystemExit): + setup.hip_card(Path("engine"), listed[0], listed) # HIP does not list the card + + def test_windows_dispatch(self): + """amd_gpus() on Windows: HIP's numbering once the HIP engine answers, the display adapters before.""" + with mock.patch.object(setup, "WIN", True), \ + mock.patch.object(setup, "hip_devices", lambda probe=None, text=None: None), \ + mock.patch.object(setup, "amd_gpus_windows", lambda adapters=None, registry=None: ["display"]): + self.assertEqual(setup.amd_gpus(), ["display"]) + with mock.patch.object(setup, "WIN", True), \ + mock.patch.object(setup, "hip_devices", lambda probe=None, text=None: ["hip"]), \ + mock.patch.object(setup, "amd_gpus_windows", lambda adapters=None, registry=None: ["display"]): + self.assertEqual(setup.amd_gpus(), ["hip"]) + + def test_no_hip_engine_no_probe(self): + with tempfile.TemporaryDirectory() as d: + eng = Path(d) + (eng / "strata-device.exe").write_text("x") + (eng / "BUILD.json").write_text('{"backend": "cuda"}') # an NVIDIA engine is never asked + self.assertIsNone(setup.hip_devices(eng / "strata-device.exe")) + + def test_prebuilt_hip_zip(self): + """get_prebuilt_hip: a published zip (here a local folder) is unpacked into engine/; one without code for the + card, or older than the first Windows HIP release, is refused.""" + import json + import zipfile + with tempfile.TemporaryDirectory() as d: + root = Path(d) + pub = root / "pub" + pub.mkdir() + + def publish(meta): + with zipfile.ZipFile(pub / setup.WIN_HIP_ASSET, "w") as z: + z.writestr("strata.exe", "engine") + z.writestr("strata-device.exe", "probe") + z.writestr("rocm/bin/amdhip64_7.dll", "dll") + z.writestr("BUILD.json", json.dumps(meta)) + ver = ".".join(map(str, setup.WIN_HIP_MIN_ENGINE)) + good = {"source": "prebuilt", "backend": "hip", "version": ver, "archs": ["gfx1100", "gfx1201"], + "lib_dirs": ["rocm/bin"]} + with mock.patch.object(setup, "ROOT", root), mock.patch.object(setup, "say", lambda *a, **k: None), \ + mock.patch.object(setup, "ok", lambda *a: None), mock.patch.object(setup, "warn", lambda *a: None): + publish({**good, "archs": ["gfx1100"]}) + self.assertIsNone(setup.get_prebuilt_hip(str(pub) + "/", {"arch": "gfx1201"})) + publish({**good, "version": "0.1.30"}) + self.assertIsNone(setup.get_prebuilt_hip(str(pub) + "/", {"arch": "gfx1201"})) + publish(good) + eng = setup.get_prebuilt_hip(str(pub) + "/", {"arch": "gfx1201"}) + self.assertEqual(eng, root / "engine") + self.assertTrue((eng / "rocm" / "bin" / "amdhip64_7.dll").exists()) + self.assertEqual(setup.hip_lib_dirs(eng), [eng / "rocm" / "bin"]) + (pub / setup.WIN_HIP_ASSET).unlink() # installed: kept, nothing downloaded again + self.assertEqual(setup.get_prebuilt_hip(str(pub) + "/", {"arch": "gfx1201"}), eng) + + +_HIP_DEVICES = setup.hip_devices # the real parser, for the tests that mock setup.hip_devices + + +def setup_hip(text): + return _HIP_DEVICES(text=text) + + +class WindowsHipVision(unittest.TestCase): + def test_no_cpu_encoder_on_windows(self): + with mock.patch.object(setup, "WIN", True), mock.patch.object(setup, "warn", lambda *a: None): + self.assertEqual(setup.hip_vision("cpu"), "none") + self.assertEqual(setup.hip_vision("yes"), "none") + with mock.patch.object(setup, "WIN", False), mock.patch.object(setup, "warn", lambda *a: None): + self.assertEqual(setup.hip_vision("cpu"), "cpu") + + if __name__ == "__main__": unittest.main() diff --git a/tools/test_setup_choices.py b/tools/test_setup_choices.py index 3823ec89..756a6d4a 100644 --- a/tools/test_setup_choices.py +++ b/tools/test_setup_choices.py @@ -160,6 +160,7 @@ class ExperimentalSm60(unittest.TestCase): class HipVision(unittest.TestCase): """#304: --vision cpu with --backend hip builds the CPU image encoder beside the HIP engine.""" + @mock.patch.object(setup, "WIN", False) # Linux: compiled here (Windows has no AMD image encoder yet) def test_the_choice(self): self.assertEqual(quiet(setup.hip_vision, "cpu"), ("cpu", "")) for asked in (None, "no", "none"):