Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Studio: keep the AMD gfx target and HIP id map until hardware re-detection (#14970)
Daniel Hande03e0691819
diff --git a/studio/backend/tests/test_static_gpu_inventory_cache.py b/studio/backend/tests/test_static_gpu_inventory_cache.pynew file mode 100644index 00000000000..c900323f8b7--- /dev/null+++ b/studio/backend/tests/test_static_gpu_inventory_cache.py@@ -0,0 +1,377 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Static AMD answers (gfx target, HIP id map) are kept until hardware re-detection; live reads stay live."""++import subprocess+import sys++import pytest++from utils.hardware import amd, gpu_query+from utils.hardware import hardware as hw+++class _Result:+ def __init__(+ self,+ stdout,+ returncode = 0,+ ):+ self.stdout, self.stderr, self.returncode = stdout, "", returncode+++_MASKS = (+ "ROCR_VISIBLE_DEVICES",+ "HIP_VISIBLE_DEVICES",+ "CUDA_VISIBLE_DEVICES",+ "GPU_DEVICE_ORDINAL",+ "HSA_OVERRIDE_GFX_VERSION",+)+++def rocm_cli(monkeypatch):+ calls = []++ def run(argv, *a, **k):+ calls.append(list(argv))+ if argv[0] == "rocminfo":+ return _Result(" Name: gfx1100\n")+ if argv[0] == "amd-smi" and argv[1:3] == ["list", "-e"]:+ return _Result('[{"gpu": 0, "hip_id": 0}]')+ if argv[0] == "amd-smi" and argv[1] == "metric":+ return _Result(+ '[{"gpu": 0, "mem_usage": {"total_vram": {"value": 24560, "unit": "MB"},'+ ' "used_vram": {"value": 100, "unit": "MB"}}}]'+ )+ raise FileNotFoundError(argv[0])++ monkeypatch.setattr(subprocess, "run", run)+ monkeypatch.setattr(+ "shutil.which",+ lambda name, *a, **k: f"/opt/rocm/bin/{name}" if name in ("rocminfo", "amd-smi") else None,+ )+ monkeypatch.delenv("UNSLOTH_GPU_QUERY_CACHE", raising = False)+ for name in _MASKS:+ monkeypatch.delenv(name, raising = False)+ monkeypatch.setattr(hw, "_gfx_candidates_cache", None, raising = False)+ # Other files can leave amd-smi latched off (failures, a non-Linux platform stub): start clean.+ monkeypatch.setattr(amd, "_amd_smi_disabled", False)+ monkeypatch.setattr(amd, "_amd_smi_consecutive_failures", 0)+ monkeypatch.setattr(amd, "_amd_smi_allowed", lambda *a, **k: True)+ monkeypatch.setattr(amd, "_hip_id_map_cache", None)+ return calls+++def _count(calls, *prefix):+ return sum(1 for argv in calls if argv[: len(prefix)] == list(prefix))+++def test_rocminfo_runs_once_across_inventory_passes(rocm_cli):+ for _ in range(10):+ assert hw._linux_amd_gfx_candidates() == ["gfx1100"]+ assert _count(rocm_cli, "rocminfo") == 1+++def test_hardware_redetection_reads_the_gfx_target_again(rocm_cli):+ hw._linux_amd_gfx_candidates()+ hw.invalidate_detection()+ hw._linux_amd_gfx_candidates()+ assert _count(rocm_cli, "rocminfo") == 2+++ "name", ["ROCR_VISIBLE_DEVICES", "HIP_VISIBLE_DEVICES", "HSA_OVERRIDE_GFX_VERSION"]+)+def test_a_changed_mask_or_override_reads_the_gfx_target_again(rocm_cli, monkeypatch, name):+ hw._linux_amd_gfx_candidates()+ monkeypatch.setenv(name, "1" if "VISIBLE" in name else "11.0.0")+ hw._linux_amd_gfx_candidates()+ hw._linux_amd_gfx_candidates()+ assert _count(rocm_cli, "rocminfo") == 2+++def test_a_rocm_install_landing_mid_session_is_seen(rocm_cli, monkeypatch):+ monkeypatch.setattr("shutil.which", lambda name, *a, **k: None)+ hw._linux_amd_gfx_candidates()+ monkeypatch.setattr("shutil.which", lambda name, *a, **k: f"/opt/rocm/bin/{name}")+ assert hw._linux_amd_gfx_candidates() == ["gfx1100"]+ assert _count(rocm_cli, "rocminfo") == 2+++def test_an_amd_card_attached_beside_another_reads_the_gfx_target_again(rocm_cli, monkeypatch):+ topology = [(("0000:03:00.0", "0x744c"),)]+ monkeypatch.setattr(hw, "_linux_amd_pci_topology", lambda *a, **k: topology[0])+ hw._linux_amd_gfx_candidates()+ hw._linux_amd_gfx_candidates()+ assert _count(rocm_cli, "rocminfo") == 1+ topology[0] = (("0000:03:00.0", "0x744c"), ("0000:0c:00.0", "0x7550"))+ hw._linux_amd_gfx_candidates()+ assert _count(rocm_cli, "rocminfo") == 2+++ sys.platform == "win32", reason = "sysfs is Linux only; PCI addresses contain ':'"+)+def test_amd_pci_topology_reads_sysfs(tmp_path):+ def card(name, vendor, device, slot):+ dev = tmp_path / "pci" / slot+ dev.mkdir(parents = True)+ (dev / "vendor").write_text(vendor + "\n")+ (dev / "device").write_text(device + "\n")+ (tmp_path / "drm" / name).mkdir(parents = True)+ (tmp_path / "drm" / name / "device").symlink_to(dev)++ card("card0", "0x1002", "0x744C", "0000:03:00.0")+ card("card1", "0x10de", "0x2684", "0000:01:00.0")+ (tmp_path / "drm" / "card0-DP-1").mkdir()+ assert hw._linux_amd_pci_topology(str(tmp_path / "drm")) == (("0000:03:00.0", "0x744c"),)+++def test_a_timed_out_probe_is_not_kept(rocm_cli, monkeypatch):+ def hung(argv, *a, **k):+ rocm_cli.append(list(argv))+ raise subprocess.TimeoutExpired(argv, 10)++ monkeypatch.setattr(subprocess, "run", hung)+ assert hw._linux_amd_gfx_candidates() == []+ assert hw._linux_amd_gfx_candidates() == []+ assert _count(rocm_cli, "rocminfo") == 2+++def test_a_failing_probe_is_not_kept(rocm_cli, monkeypatch):+ def failing(argv, *a, **k):+ rocm_cli.append(list(argv))+ return _Result("", returncode = 1)++ monkeypatch.setattr(subprocess, "run", failing)+ assert hw._linux_amd_gfx_candidates() == []+ assert hw._linux_amd_gfx_candidates() == []+ assert _count(rocm_cli, "rocminfo") == 2+++def test_a_fallback_answer_after_rocminfo_failed_is_not_kept(rocm_cli, monkeypatch):+ def rocminfo_hangs(argv, *a, **k):+ rocm_cli.append(list(argv))+ if argv[0] == "rocminfo":+ raise subprocess.TimeoutExpired(argv, 10)+ return _Result("ASIC: gfx1100\n")++ monkeypatch.setattr(subprocess, "run", rocminfo_hangs)+ assert hw._linux_amd_gfx_candidates() == ["gfx1100"]+ assert hw._linux_amd_gfx_candidates() == ["gfx1100"]+ assert _count(rocm_cli, "rocminfo") == 2+++def test_a_present_but_unstartable_rocminfo_is_not_kept(rocm_cli, monkeypatch):+ def no_interpreter(argv, *a, **k):+ rocm_cli.append(list(argv))+ raise FileNotFoundError(argv[0])++ monkeypatch.setattr(subprocess, "run", no_interpreter)+ hw._linux_amd_gfx_candidates()+ hw._linux_amd_gfx_candidates()+ assert _count(rocm_cli, "rocminfo") == 2+++def test_an_absent_rocm_userspace_is_kept(rocm_cli, monkeypatch):+ monkeypatch.setattr("shutil.which", lambda name, *a, **k: None)++ def absent(argv, *a, **k):+ rocm_cli.append(list(argv))+ raise FileNotFoundError(argv[0])++ monkeypatch.setattr(subprocess, "run", absent)+ hw._linux_amd_gfx_candidates()+ hw._linux_amd_gfx_candidates()+ assert _count(rocm_cli, "rocminfo") == 1+++def test_a_numbered_per_device_override_reads_the_gfx_target_again(rocm_cli, monkeypatch):+ hw._linux_amd_gfx_candidates()+ monkeypatch.setenv("HSA_OVERRIDE_GFX_VERSION_1", "11.0.0")+ hw._linux_amd_gfx_candidates()+ assert _count(rocm_cli, "rocminfo") == 2+++def test_forced_hardware_detection_reads_the_gfx_target_again(rocm_cli, monkeypatch):+ hw._linux_amd_gfx_candidates()+ # detect_hardware() rebinds the module's detection globals: restore them after the test.+ for name in list(vars(hw)):+ if name.lstrip("_").isupper():+ monkeypatch.setattr(hw, name, getattr(hw, name))+ monkeypatch.setattr(hw, "_has_torch", lambda: False)+ try:+ hw.detect_hardware()+ except Exception:+ pass+ hw._linux_amd_gfx_candidates()+ assert _count(rocm_cli, "rocminfo") >= 2+++def test_forced_hardware_detection_reads_the_hip_id_map_again(rocm_cli, monkeypatch):+ monkeypatch.setattr(amd, "_hip_id_map_cache", None)+ amd.get_hip_id_by_gpu_index()+ for name in list(vars(hw)):+ if name.lstrip("_").isupper():+ monkeypatch.setattr(hw, name, getattr(hw, name))+ monkeypatch.setattr(hw, "_has_torch", lambda: False)+ try:+ hw.detect_hardware()+ except Exception:+ pass+ amd.get_hip_id_by_gpu_index()+ assert _count(rocm_cli, "amd-smi", "list", "-e") >= 2+++def test_partial_output_from_a_failing_probe_is_used_not_kept(rocm_cli, monkeypatch):+ def partial(argv, *a, **k):+ rocm_cli.append(list(argv))+ return _Result(" Name: gfx1100\n", returncode = 1)++ monkeypatch.setattr(subprocess, "run", partial)+ assert hw._linux_amd_gfx_candidates() == ["gfx1100"]+ assert hw._linux_amd_gfx_candidates() == ["gfx1100"]+ assert _count(rocm_cli, "rocminfo") == 2+++def test_a_probe_running_across_a_forced_detection_cannot_republish(rocm_cli, monkeypatch):+ import threading++ entered, release = threading.Event(), threading.Event()+ real_probe = hw._probe_linux_amd_gfx_candidates++ def slow_probe():+ entered.set()+ release.wait(10)+ return ["gfx1030"], True++ monkeypatch.setattr(hw, "_probe_linux_amd_gfx_candidates", slow_probe)+ reader = threading.Thread(target = hw._linux_amd_gfx_candidates)+ reader.start()+ assert entered.wait(10)+ # What forced detection does to this cache, while the old probe is still running.+ monkeypatch.setattr(hw, "_gfx_detect_epoch", hw._gfx_detect_epoch + 1)+ monkeypatch.setattr(hw, "_gfx_candidates_cache", None)+ release.set()+ reader.join(10)+ monkeypatch.setattr(hw, "_probe_linux_amd_gfx_candidates", real_probe)+ assert hw._linux_amd_gfx_candidates() == ["gfx1100"]+ assert _count(rocm_cli, "rocminfo") == 1+++def test_an_empty_answer_is_asked_again_after_its_window(rocm_cli, monkeypatch):+ now = [1000.0]+ answers = [" Name: CPU\n", " Name: gfx1100\n"]++ def run(argv, *a, **k):+ rocm_cli.append(list(argv))+ if argv[0] == "rocminfo":+ return _Result(answers[0] if _count(rocm_cli, "rocminfo") == 1 else answers[1])+ return _Result("")++ monkeypatch.setattr(subprocess, "run", run)+ monkeypatch.setattr(hw.time, "monotonic", lambda: now[0])+ assert hw._linux_amd_gfx_candidates() == []+ now[0] += hw._GFX_EMPTY_TTL_S - 1+ assert hw._linux_amd_gfx_candidates() == []+ assert _count(rocm_cli, "rocminfo") == 1+ now[0] += 2+ assert hw._linux_amd_gfx_candidates() == ["gfx1100"]+ assert _count(rocm_cli, "rocminfo") == 2+++def test_the_cache_switch_turns_it_off(rocm_cli, monkeypatch):+ monkeypatch.setenv("UNSLOTH_GPU_QUERY_CACHE", "0")+ for _ in range(3):+ hw._linux_amd_gfx_candidates()+ assert _count(rocm_cli, "rocminfo") == 3+++def test_hardware_redetection_reads_the_hip_id_map_again(rocm_cli):+ assert amd.get_hip_id_by_gpu_index() == {0: 0}+ assert amd.get_hip_id_by_gpu_index() == {0: 0}+ assert _count(rocm_cli, "amd-smi", "list", "-e") == 1+ gpu_query.invalidate_static("re-seated card")+ assert amd.get_hip_id_by_gpu_index() == {0: 0}+ assert _count(rocm_cli, "amd-smi", "list", "-e") == 2+++def test_an_amd_card_attached_beside_another_reads_the_hip_id_map_again(rocm_cli, monkeypatch):+ topology = [(("0000:03:00.0", "0x744c"),)]+ monkeypatch.setattr(hw, "_linux_amd_pci_topology", lambda *a, **k: topology[0])+ monkeypatch.setattr(amd, "_hip_id_map_cache", None)+ amd.get_hip_id_by_gpu_index()+ amd.get_hip_id_by_gpu_index()+ assert _count(rocm_cli, "amd-smi", "list", "-e") == 1+ topology[0] = (("0000:03:00.0", "0x744c"), ("0000:0c:00.0", "0x7550"))+ amd.get_hip_id_by_gpu_index()+ assert _count(rocm_cli, "amd-smi", "list", "-e") == 2+++def test_an_unreadable_topology_keeps_the_hip_id_map(rocm_cli, monkeypatch):+ topology = [(("0000:03:00.0", "0x744c"),)]+ monkeypatch.setattr(hw, "_linux_amd_pci_topology", lambda *a, **k: topology[0])+ monkeypatch.setattr(amd, "_hip_id_map_cache", None)+ amd.get_hip_id_by_gpu_index()+ topology[0] = None+ amd.get_hip_id_by_gpu_index()+ assert _count(rocm_cli, "amd-smi", "list", "-e") == 1+++def test_a_topology_that_becomes_readable_sets_the_hip_id_map_baseline(rocm_cli, monkeypatch):+ topology = [None]+ monkeypatch.setattr(hw, "_linux_amd_pci_topology", lambda *a, **k: topology[0])+ monkeypatch.setattr(amd, "_hip_id_map_cache", None)+ amd.get_hip_id_by_gpu_index()+ topology[0] = (("0000:03:00.0", "0x744c"),)+ amd.get_hip_id_by_gpu_index()+ amd.get_hip_id_by_gpu_index()+ assert _count(rocm_cli, "amd-smi", "list", "-e") == 2+ topology[0] = (("0000:03:00.0", "0x744c"), ("0000:0c:00.0", "0x7550"))+ amd.get_hip_id_by_gpu_index()+ assert _count(rocm_cli, "amd-smi", "list", "-e") == 3+++def test_an_unreadable_topology_probes_the_gfx_target_every_pass(rocm_cli, monkeypatch):+ monkeypatch.setattr(hw, "_linux_amd_pci_topology", lambda *a, **k: None)+ hw._linux_amd_gfx_candidates()+ hw._linux_amd_gfx_candidates()+ assert _count(rocm_cli, "rocminfo") == 2+++def test_no_drm_class_is_no_cards(tmp_path):+ assert hw._linux_amd_pci_topology(str(tmp_path / "missing")) == ()+++def test_an_invalidation_during_a_hip_id_map_read_is_not_overwritten(rocm_cli, monkeypatch):+ import threading++ monkeypatch.setattr(amd, "_hip_id_map_cache", None)+ entered, release = threading.Event(), threading.Event()++ def slow_read():+ entered.set()+ release.wait(10)+ return {0: 0}++ monkeypatch.setattr(amd, "_read_hip_id_by_gpu_index", slow_read)+ reader = threading.Thread(target = amd.get_hip_id_by_gpu_index)+ reader.start()+ assert entered.wait(10)+ clearer = threading.Thread(target = amd.invalidate_hip_id_map)+ clearer.start()+ clearer.join(0.3) # an unlocked clear would finish here, before the read lands+ release.set()+ reader.join(10)+ clearer.join(10)+ assert amd._hip_id_map_cache is None+++def test_live_vram_reads_still_run_every_time(rocm_cli):+ hw._linux_amd_gfx_candidates()+ amd.get_hip_id_by_gpu_index()+ for _ in range(3):+ assert amd.get_gpu_vram_mib()+ assert _count(rocm_cli, "amd-smi", "metric") == 3diff --git a/studio/backend/tests/test_torch_cpu_build_on_nvidia_host.py b/studio/backend/tests/test_torch_cpu_build_on_nvidia_host.pyindex e8b4d576aad..987bc619651 100644--- a/studio/backend/tests/test_torch_cpu_build_on_nvidia_host.py+++ b/studio/backend/tests/test_torch_cpu_build_on_nvidia_host.py@@ -1738,6 +1738,7 @@ def test_the_gfx_probe_answers_nothing_without_a_rocm_userspace(monkeypatch):class _Result:stdout = " Name: gfx1030\n Name: gfx1030\n"+ returncode = 0monkeypatch.setattr(hw.subprocess, "run", lambda *_a, **_k: _Result())assert hw._linux_amd_gfx_candidates() == ["gfx1030"]diff --git a/studio/backend/utils/hardware/amd.py b/studio/backend/utils/hardware/amd.pyindex 1622f78298e..e9be2e99e7e 100644--- a/studio/backend/utils/hardware/amd.py+++ b/studio/backend/utils/hardware/amd.py@@ -381,21 +381,58 @@ def get_gpu_vram_mib() -> dict[int, tuple[int, int]]:_HIP_ID_MAP_NONE_TTL_S = 300.0_hip_id_map_lock = threading.Lock()-_hip_id_map_cache: Optional[tuple[float, Optional[dict[int, int]]]] = None+_hip_id_map_cache: Optional[+ tuple[float, Optional[dict[int, int]], Optional[int], Optional[tuple]]+] = Nonedef get_hip_id_by_gpu_index() -> Optional[dict[int, int]]:- """{amd-smi gpu id: HIP device id}, or None when the mapping is not readable. Two index spaces, one number: amd-smi's gpu id is an enumeration index in discovery order over its KFD/sysfs view, while HIP's is what ``HIP_VISIBLE_DEVICES`` names and what torch reports as ``cuda:N``, derived from the KFD node id instead (``hip_id = node_id - smallest_node_id``). They coincide on most hosts and not on all of them, so the number cannot be carried from one space to the other without this call. ``amd-smi list -e`` is the mapping AMD publishes for exactly this ("mapping physical-to-logical GPU IDs"), added in ROCm 6.4.0. None when any device lacks a usable id (an older CLI rejects ``-e`` outright, and ``hip_id`` reads "N/A" when the library cannot reach the device's KFD node) so callers decline rather than assume the identity mapping. Cached for the process; an unreadable answer is retried after five minutes."""+ """{amd-smi gpu id: HIP device id}, or None when the mapping is not readable. Two index spaces, one number: amd-smi's gpu id is an enumeration index in discovery order over its KFD/sysfs view, while HIP's is what ``HIP_VISIBLE_DEVICES`` names and what torch reports as ``cuda:N``, derived from the KFD node id instead (``hip_id = node_id - smallest_node_id``). They coincide on most hosts and not on all of them, so the number cannot be carried from one space to the other without this call. ``amd-smi list -e`` is the mapping AMD publishes for exactly this ("mapping physical-to-logical GPU IDs"), added in ROCm 6.4.0. None when any device lacks a usable id (an older CLI rejects ``-e`` outright, and ``hip_id`` reads "N/A" when the library cannot reach the device's KFD node) so callers decline rather than assume the identity mapping. Cached until hardware re-detection; an unreadable answer is retried after five minutes."""global _hip_id_map_cache+ static_gen = _static_generation()+ topology = _amd_pci_topology()with _hip_id_map_lock:cached = _hip_id_map_cache- if cached is None or (- cached[1] is None and time.monotonic() - cached[0] >= _HIP_ID_MAP_NONE_TTL_S+ if (+ cached is None+ or cached[2] != static_gen+ # Cards changed, or the first readable walk (no baseline); an unreadable walk keeps the map.+ or (topology is not None and cached[3] != topology)+ or (cached[1] is None and time.monotonic() - cached[0] >= _HIP_ID_MAP_NONE_TTL_S)):- cached = _hip_id_map_cache = (time.monotonic(), _read_hip_id_by_gpu_index())+ cached = _hip_id_map_cache = (+ time.monotonic(),+ _read_hip_id_by_gpu_index(),+ static_gen,+ topology,+ )return None if cached[1] is None else dict(cached[1])+def invalidate_hip_id_map() -> None:+ """Drop the HIP id map, under its lock so a read in flight cannot land after the clear."""+ global _hip_id_map_cache+ with _hip_id_map_lock:+ _hip_id_map_cache = None+++def _static_generation() -> Optional[int]:+ """gpu_query's static generation, bumped by hardware re-detection (a swapped or re-seated card)."""+ try:+ from utils.hardware import gpu_query+ return gpu_query._static_gen+ except Exception:+ return None+++def _amd_pci_topology() -> Optional[tuple]:+ try:+ from utils.hardware.hardware import _linux_amd_pci_topology+ return _linux_amd_pci_topology()+ except Exception:+ return None++def _read_hip_id_by_gpu_index() -> Optional[dict[int, int]]:data = _run_amd_smi("list", "-e", count_failures = False)if data is None:diff --git a/studio/backend/utils/hardware/hardware.py b/studio/backend/utils/hardware/hardware.pyindex 24680392b2d..7a1cd2f9d1b 100644--- a/studio/backend/utils/hardware/hardware.py+++ b/studio/backend/utils/hardware/hardware.py@@ -440,8 +440,107 @@ def _linux_kfd_gfx1153_candidates() -> list[str]:return found+# The gfx target is the silicon's: kept until re-detection rather than re-running rocminfo (it starts HSA)+# every 60 s inventory pass. Keyed on the resolved binaries and the masks / overrides the CLIs inherit.+_GFX_CANDIDATE_ENV = (+ "ROCR_VISIBLE_DEVICES",+ "HIP_VISIBLE_DEVICES",+ "CUDA_VISIBLE_DEVICES",+ "GPU_DEVICE_ORDINAL",+ "HSA_OVERRIDE_GFX_VERSION",+)+_gfx_candidates_cache: Optional[tuple[tuple, list[str], float]] = None+# An empty answer (GPU runtime still coming up) is asked again after this long.+_GFX_EMPTY_TTL_S = 300.0+# In the key: a probe started before a forced detection publishes under a key no later read matches.+_gfx_detect_epoch = 0+++def _gfx_candidates_key() -> Optional[tuple]:+ """None when caching is off or gpu_query is unavailable (the no-torch sandbox stub tree)."""+ try:+ import shutil++ from . import gpu_query++ if not gpu_query.enabled():+ return None+ static_gen = gpu_query._static_gen+ binaries = (shutil.which("rocminfo"), shutil.which("amd-smi"))+ except Exception:+ return None+ topology = _linux_amd_pci_topology()+ if topology is None:+ # An unreadable walk cannot see a swapped card: probe every pass, as before.+ return None+ # The runner object, as gpu_query keys it, so a swapped fake never shares an answer.+ return (+ subprocess.run,+ static_gen,+ binaries,+ tuple(os.environ.get(name) for name in _GFX_CANDIDATE_ENV),+ # Per-device overrides (HSA_OVERRIDE_GFX_VERSION_<n>) change what rocminfo reports too.+ tuple(+ sorted(+ (k, v) for k, v in os.environ.items() if k.startswith("HSA_OVERRIDE_GFX_VERSION_")+ )+ ),+ topology,+ _gfx_detect_epoch,+ )+++def _linux_amd_pci_topology(root: str = "/sys/class/drm") -> "tuple | None":+ """Sorted (PCI address, device id) of every bound AMD card: sees a card swapped beside one that stays,+ which re-detection misses. () with no DRM class (not Linux), None when the walk is unreadable."""+ try:+ entries = os.listdir(root)+ except FileNotFoundError:+ return ()+ except OSError:+ return None+ found = []+ for entry in entries:+ if not re.fullmatch(r"card\d+", entry):+ continue+ device = os.path.join(root, entry, "device")+ try:+ with open(os.path.join(device, "vendor"), encoding = "utf-8") as fh:+ if fh.read().strip().lower() != "0x1002":+ continue+ with open(os.path.join(device, "device"), encoding = "utf-8") as fh:+ device_id = fh.read().strip().lower()+ except FileNotFoundError:+ continue+ except OSError:+ return None+ found.append((os.path.basename(os.path.realpath(device)), device_id))+ return tuple(sorted(found))++def _linux_amd_gfx_candidates() -> list[str]:"""gfx targets the ROCm userspace reports for this host, sorted, or []. rocminfo is what studio/setup.sh reads to pick an arch, with amd-smi as its fallback; neither is required to exist, and a host with no ROCm userspace reports nothing, so the caller keeps the card rather than guessing an arch. Bounded and never raises."""+ global _gfx_candidates_cache+ key = _gfx_candidates_key()+ cached = _gfx_candidates_cache+ if (+ key is not None+ and cached is not None+ and cached[0] == key+ and (cached[1] or time.monotonic() - cached[2] < _GFX_EMPTY_TTL_S)+ ):+ return list(cached[1])+ found, settled = _probe_linux_amd_gfx_candidates()+ if key is not None and settled:+ _gfx_candidates_cache = (key, list(found), time.monotonic())+ return found+++def _probe_linux_amd_gfx_candidates() -> tuple[list[str], bool]:+ """(targets, settled); not settled when an existing CLI timed out, could not start or failed."""+ import shutil++ settled = Truefor command, pattern in ((["rocminfo"], r"\bgfx[0-9a-f]+\b"),(["amd-smi", "static", "--asic"], r"\bgfx[0-9a-f]+\b"),@@ -457,14 +556,22 @@ def _linux_amd_gfx_candidates() -> list[str]:check = False,)except FileNotFoundError:+ # ENOENT also comes from an executable that exists but cannot start (a missing interpreter).+ if shutil.which(command[0]) is not None:+ settled = Falsecontinueexcept (OSError, subprocess.TimeoutExpired) as e:logger.debug("%s could not report a gfx target: %s", command[0], e)+ settled = Falsecontinuefound = {match.group(0).lower() for match in re.finditer(pattern, result.stdout or "")}if found:- return sorted(found)- return []+ # Used, not kept, after a non-zero exit (maybe partial output) or a failed rocminfo.+ return sorted(found), settled and result.returncode == 0+ # Ran and failed (no /dev/kfd access yet, driver loading): not an answer.+ if result.returncode != 0:+ settled = False+ return [], settleddef _hidden_console_kwargs() -> Dict[str, Any]:@@ -1570,7 +1677,16 @@ def _detect_hardware_locked() -> DeviceType:"""detect_hardware() body. Call only with _DETECT_LOCK held."""global DEVICE, CHAT_ONLY, CHAT_ONLY_REASON, CHAT_ONLY_DETAIL, IS_ROCMglobal _MLX_BLOCKERS_MEASURED, CHAT_ONLY_MISMATCH_VENDORS+ global _gfx_candidates_cache, _gfx_detect_epochCHAT_ONLY = True # reset -- only CUDA/ROCm/XPU/MLX sets it to False+ # A forced detection asks the ROCm CLIs again, and an older probe cannot publish.+ _gfx_detect_epoch += 1+ _gfx_candidates_cache = None+ try:+ from . import amd as _amd+ _amd.invalidate_hip_id_map()+ except Exception:+ passCHAT_ONLY_REASON = NoneCHAT_ONLY_DETAIL = NoneCHAT_ONLY_MISMATCH_VENDORS = frozenset()