Skip to content

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

C++

setup: AMD on Windows - the ready-made HIP engine, chosen by itself without a usable NVIDIA card

Niko122126cc76347aac
diff --git a/START-HERE.bat b/START-HERE.bat
index 2b80315de..dfb92feb8 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/setup.py b/setup.py
index 9d09d17ba..ca65f3a2e 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-<model>.bat / run-<model>.sh and starts the model
@@ -926,10 +927,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:
@@ -962,9 +965,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
@@ -992,6 +1003,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:
@@ -1058,10 +1341,11 @@ def hipblaslt_version(lib_dirs):
return None
-def hipblaslt_table(arch, lib_dirs):
+def hipblaslt_table(arch, lib_dirs, ver=None):
"""tools/hip/<arch>-hipblaslt-<version>.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]
@@ -1130,7 +1414,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"
@@ -1168,7 +1457,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
@@ -1257,6 +1546,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:
@@ -2156,7 +2460,7 @@ def main() -> int:
"else read through the OS file cache (mmap); resident / mmap force one of the two")
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.gpu is not None: # --gpu 0,2 means --gpus 0,2 (a user tried it: issue report)
@@ -2230,7 +2534,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))
@@ -2241,19 +2545,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]
@@ -2534,8 +2839,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 <its dist folder> (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")
@@ -2545,7 +2859,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')}",
@@ -2684,7 +3001,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/tools/test_setup_amd.py b/tools/test_setup_amd.py
index 6c82c35f8..fdca0eb41 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 b024dd4b4..c3eb8f08d 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"):