Skip to content

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.

Studio: pin the FLUX.3 prompt upsampler to the image model's card under HIP masks and on Vulkan builds (#14356)

Daniel Hanf55a9d3b16db
diff --git a/studio/backend/core/inference/flux3_prompt_upsampler.py b/studio/backend/core/inference/flux3_prompt_upsampler.py
index 6d84aff1c9d..443ce4c5d72 100644
--- a/studio/backend/core/inference/flux3_prompt_upsampler.py
+++ b/studio/backend/core/inference/flux3_prompt_upsampler.py
@@ -866,26 +866,147 @@ def _resident_cuda_ordinal() -> Optional[int]:
def _child_device_mask(ordinal: Optional[int]) -> dict:
"""Pin llama-server to the image model's card: left alone it splits layers over every visible GPU, onto a card the
memory probe never read."""
- if ordinal is None:
+ # LLAMA_ARG_DEVICE is the user's own pick, and names devices a narrowed mask would renumber.
+ if ordinal is None or ordinal < 0 or str(os.environ.get("LLAMA_ARG_DEVICE", "")).strip():
return {}
try:
import torch
if torch.cuda.device_count() <= 1:
return {}
+ from core.inference.llama_cpp import LlamaCppBackend
+
var = "CUDA_VISIBLE_DEVICES"
- if getattr(torch.version, "hip", None) and os.environ.get(var) is None:
+ # ROCm reads a non-empty HIP_VISIBLE_DEVICES over CUDA_VISIBLE_DEVICES; an empty one counts as unset.
+ if LlamaCppBackend._torch_is_rocm(torch) and (
+ (os.environ.get("HIP_VISIBLE_DEVICES") or "").strip() or os.environ.get(var) is None
+ ):
var = "HIP_VISIBLE_DEVICES"
- parent = os.environ.get(var)
+ parent = (os.environ.get(var) or "").strip() or None
if parent is None:
return {var: str(ordinal)}
# Torch indexes inside the parent's mask, so the child keeps that entry (an index or a UUID).
entries = [entry.strip() for entry in parent.split(",") if entry.strip()]
- return {var: entries[ordinal]} if ordinal < len(entries) else {}
+ if var == "HIP_VISIBLE_DEVICES":
+ # clr keeps the first of a repeated HIP entry (utils/hardware/amd.py), so 0,0,1 exposes two devices.
+ entries = list(dict.fromkeys(entries))
+ return {var: entries[ordinal]} if 0 <= ordinal < len(entries) else {}
except Exception: # noqa: BLE001 -- no mask: llama.cpp's own device choice
return {}
+_VULKAN_ROWS_TTL_S = 120.0
+_vulkan_rows_memo: dict = {}
+
+
+def _vulkan_rows(binary: str, retry_empty: bool = False) -> list:
+ """Vulkan probe rows, cached briefly; ``retry_empty`` re-probes a cached (maybe transient) empty answer."""
+ from core.inference.llama_cpp import LlamaCppBackend
+
+ try:
+ key = (binary, os.path.getmtime(binary))
+ except OSError:
+ key = (binary, None)
+ hit = _vulkan_rows_memo.get(key)
+ if (
+ hit is not None
+ and time.monotonic() - hit[1] < _VULKAN_ROWS_TTL_S
+ and (hit[0] or not retry_empty)
+ ):
+ return hit[0]
+ rows = list(LlamaCppBackend._run_vulkan_probe(binary) or [])
+ _vulkan_rows_memo.clear()
+ _vulkan_rows_memo[key] = (rows, time.monotonic())
+ return rows
+
+
+def _user_device_pick(binary: Optional[str] = None) -> bool:
+ """LLAMA_ARG_DEVICE / LLAMA_ARG_MAIN_GPU / Vulkan mask set by the user; with ``binary``, a Vulkan mask counts
+ only where Vulkan may load (CUDA and HIP ignore it)."""
+ if any(
+ str(os.environ.get(var, "")).strip() for var in ("LLAMA_ARG_DEVICE", "LLAMA_ARG_MAIN_GPU")
+ ):
+ return True
+ if not str(os.environ.get("GGML_VK_VISIBLE_DEVICES", "")).strip():
+ return False
+ if binary is None or str(os.environ.get("GGML_BACKEND_PATH", "")).strip():
+ return True
+ try:
+ from core.inference.llama_cpp import LlamaCppBackend
+ return bool(LlamaCppBackend._is_vulkan_backend(binary))
+ except Exception: # noqa: BLE001
+ return True
+
+
+def _prefetch_vulkan_rows(binary: str) -> None:
+ try:
+ from core.inference.llama_cpp import LlamaCppBackend
+ if not _user_device_pick() and LlamaCppBackend._is_vulkan_backend(binary):
+ _vulkan_rows(binary)
+ except Exception: # noqa: BLE001
+ pass
+
+
+def _vulkan_device_args(
+ binary: str,
+ ordinal: Optional[int],
+ retry_empty: bool = False,
+) -> Optional[list]:
+ """``--device Vulkan<i>`` for the image model's card (Vulkan ignores visibility masks); [] unpinned, None unknown."""
+ if ordinal is None or ordinal < 0:
+ return []
+ try:
+ from core.inference.llama_cpp import LlamaCppBackend
+
+ import torch
+
+ # The user's own device pick wins (a Vulkan mask renumbers what the probe lists).
+ if _user_device_pick():
+ return []
+ # Backends loaded from GGML_BACKEND_PATH are not the ones beside the binary the probe would list.
+ if str(os.environ.get("GGML_BACKEND_PATH", "")).strip():
+ return None if torch.cuda.device_count() > 1 else []
+ if not LlamaCppBackend._is_vulkan_backend(binary):
+ return []
+ # The card lookup reads HIP masks, which only a ROCm torch applies: elsewhere one could name the wrong card.
+ if (
+ os.environ.get("HIP_VISIBLE_DEVICES") or ""
+ ).strip() and not LlamaCppBackend._torch_is_rocm(torch):
+ return None if torch.cuda.device_count() > 1 else []
+ # Vulkan sees every physical GPU (an iGPU, cards a mask hides), so torch's count says nothing here.
+ rows = _vulkan_rows(binary, retry_empty = retry_empty)
+ if not rows:
+ return None if torch.cuda.device_count() > 1 else []
+ except Exception: # noqa: BLE001
+ return []
+ try:
+ from core.inference.sd_cpp_backend import (
+ _normalized_card_name,
+ _without_driver_tag,
+ physical_card_name,
+ sd_cpp_device_named,
+ )
+
+ # By name, as the image engine pins its Vulkan build: no torch ordinal maps onto Vulkan's index.
+ listing = "".join(f"Vulkan{row['index']}\t{row['name']}\n" for row in rows)
+ name, position = physical_card_name(ordinal)
+ device = sd_cpp_device_named(binary, name, position = position, listing = listing)
+ if not device:
+ return None
+ # Exact model match: containment takes an `RX 7600 XT` for an `RX 7600`.
+ import torch
+
+ matched = next((row["name"] for row in rows if f"Vulkan{row['index']}" == device), "")
+ exact = bool(name) and _normalized_card_name(
+ _without_driver_tag(matched)
+ ) == _normalized_card_name(name)
+ if not exact and (len(rows) > 1 or torch.cuda.device_count() > 1):
+ return None
+ return [] if len(rows) == 1 else ["--device", device]
+ except Exception: # noqa: BLE001
+ return None
+
+
def _accelerator_memory_mib(
ordinal: Optional[int] = None,
) -> tuple[Optional[int], Optional[int], str]:
@@ -1136,6 +1257,8 @@ class PromptUpsamplerSidecar:
cmd += ["--mmproj", mmproj]
if layers == 0:
cmd.append("--no-mmproj-offload")
+ if layers:
+ cmd += _vulkan_device_args(binary, ordinal, retry_empty = True) or []
sock.close()
if is_process_shutting_down():
raise UpsamplerUnavailableError("Unsloth is shutting down.")
@@ -1377,6 +1500,11 @@ class PromptUpsamplerSidecar:
# every eviction.
if _gpu_unowned() or not _image_model_owns_gpu() or _training_active():
return "gpu"
+ # A user-picked device is not the card the memory probe reads; its first enhanced run starts it.
+ if _user_device_pick(binary) and _cuda_device_count() > 1:
+ return "placement"
+ # The Vulkan probe can take its full timeout, so it runs before the slot that renders queue behind.
+ _prefetch_vulkan_rows(binary)
# The engine's generation slot, held until the server is up: a render or model transition that arrives
# meanwhile queues behind the start instead of overlapping it (a load cancels it first through
# stop_for_handover). Not taken while one runs or a load is in flight.
@@ -1387,7 +1515,9 @@ class PromptUpsamplerSidecar:
ordinal = _resident_cuda_ordinal()
# Unpinnable on a multi-GPU host (the native engine records its card elsewhere): the server would split
# over every visible card and the probe below would read the wrong one. Its first enhanced run starts it.
- if ordinal is None and _cuda_device_count() > 1:
+ if (ordinal is None and _cuda_device_count() > 1) or _vulkan_device_args(
+ binary, ordinal
+ ) is None:
return "placement"
free_mib, total_mib, device = _accelerator_memory_mib(ordinal)
if free_mib is None or device not in ("cuda", "mps"):
diff --git a/studio/backend/core/inference/sd_cpp_backend.py b/studio/backend/core/inference/sd_cpp_backend.py
index 09f7d57d4ad..1804d47ecc9 100644
--- a/studio/backend/core/inference/sd_cpp_backend.py
+++ b/studio/backend/core/inference/sd_cpp_backend.py
@@ -794,7 +794,9 @@ def _physical_index_of(ordinal: int, env: Optional[dict] = None) -> "tuple[Optio
source = os.environ if env is None else env
# Windows HIP has no ROCr layer, so a leftover ROCR_VISIBLE_DEVICES masks nothing there.
rocr = None if sys.platform == "win32" else source.get(_ROCR_MASK_VAR)
- hip = next((source.get(var) for var in _HIP_MASK_VARS if source.get(var) is not None), None)
+ # ROCm reads a non-empty HIP_VISIBLE_DEVICES over CUDA_VISIBLE_DEVICES; an empty one does not shadow it.
+ present = [source.get(var) for var in _HIP_MASK_VARS if source.get(var) is not None]
+ hip = next((raw for raw in present if raw.strip()), present[0] if present else None)
opaque = source.get(_OPAQUE_MASK_VAR)
if rocr is None and hip is None and opaque is None:
return ordinal, False
@@ -807,6 +809,11 @@ def _physical_index_of(ordinal: int, env: Optional[dict] = None) -> "tuple[Optio
entries = _mask_entries(raw)
if entries is None:
return None, True
+ # clr keeps the first of a repeated HIP entry; ROCr stops at one (utils/hardware/amd.py).
+ if raw is hip:
+ entries = list(dict.fromkeys(entries))
+ elif len(set(entries)) < len(entries):
+ entries = entries[: next(i for i, e in enumerate(entries) if e in entries[:i])]
if visible is None:
visible = entries
else:
@@ -928,17 +935,19 @@ def sd_cpp_device_named(
card_name: Optional[str],
*,
position: Optional[int] = None,
+ listing: Optional[str] = None,
) -> Optional[str]:
"""The ggml device that IS *card_name*, when exactly one of them is. The Vulkan build names its
devices in its own namespace, so a physical ordinal names nothing in it. ``position`` breaks a
tie on the ASSUMPTION that RADV and HIP walk one vendor's GPUs in the same order -- unreadable
- here, so only among devices already agreed to be the right MODEL."""
+ here, so only among devices already agreed to be the right MODEL. ``listing``: tab-separated name and
+ description lines read elsewhere, instead of running ``binary --list-devices``."""
if not binary or not card_name:
return None
wanted = _normalized_card_name(card_name)
if not wanted:
return None
- text = _sd_cpp_probe_output(binary, "--list-devices")
+ text = listing if listing is not None else _sd_cpp_probe_output(binary, "--list-devices")
if text is None:
return None
# Both readings: containment cannot tell `RX 7600` from `RX 7600 XT`, equality cannot see through a driver tag.
diff --git a/studio/backend/tests/test_flux3_prompt_upsampler.py b/studio/backend/tests/test_flux3_prompt_upsampler.py
index 9b5255ffec8..270c90e96c7 100644
--- a/studio/backend/tests/test_flux3_prompt_upsampler.py
+++ b/studio/backend/tests/test_flux3_prompt_upsampler.py
@@ -941,6 +941,262 @@ def test_the_child_is_pinned_to_the_image_models_card(monkeypatch):
assert pup._child_device_mask(0) == {}
+def test_rocm_pins_inside_hip_mask_when_cuda_mask_is_also_set(monkeypatch):
+ import torch
+
+ monkeypatch.setattr(torch.cuda, "device_count", lambda: 2)
+ monkeypatch.setattr(torch.version, "hip", "6.2", raising = False)
+ # HIP wins on ROCm: torch's cuda:1 is physical 3, which CUDA_VISIBLE_DEVICES=1 would not name.
+ monkeypatch.setenv("HIP_VISIBLE_DEVICES", "2,3")
+ monkeypatch.setenv("CUDA_VISIBLE_DEVICES", "0,1,2,3")
+ assert pup._child_device_mask(1) == {"HIP_VISIBLE_DEVICES": "3"}
+ monkeypatch.delenv("HIP_VISIBLE_DEVICES")
+ assert pup._child_device_mask(1) == {"CUDA_VISIBLE_DEVICES": "1"}
+ monkeypatch.delenv("CUDA_VISIBLE_DEVICES")
+ assert pup._child_device_mask(1) == {"HIP_VISIBLE_DEVICES": "1"}
+
+
+_VULKAN_ROWS = [
+ {"index": 0, "name": "AMD Radeon Graphics (RADV RAPHAEL)"},
+ {"index": 1, "name": "AMD Radeon RX 7600 (RADV NAVI33)"},
+ {"index": 2, "name": "AMD Radeon RX 7900 XTX (RADV NAVI31)"},
+]
+
+
+def spawn_argv(monkeypatch):
+ """Run _spawn_server up to Popen on a ROCm torch with two cards; returns (argv, env) per call."""
+ import torch
+
+ from core.inference import llama_cpp, sd_cpp_backend, stt_mtmd_sidecar, stt_sidecar
+ from utils import process_lifetime
+
+ names = ["AMD Radeon RX 7900 XTX", "AMD Radeon RX 7600"]
+ state = {"vulkan": True, "rows": _VULKAN_ROWS, "names": names, "ordinal": 1}
+ for var in (
+ "CUDA_VISIBLE_DEVICES",
+ "HIP_VISIBLE_DEVICES",
+ "ROCR_VISIBLE_DEVICES",
+ "LLAMA_ARG_DEVICE",
+ ):
+ monkeypatch.delenv(var, raising = False)
+ monkeypatch.setattr(torch.cuda, "device_count", lambda: 2)
+ monkeypatch.setattr(torch.cuda, "is_available", lambda: True)
+ monkeypatch.setattr(torch.cuda, "get_device_name", lambda i = 0: state["names"][i])
+ monkeypatch.setattr(torch.version, "hip", "6.2", raising = False)
+ monkeypatch.setattr(
+ llama_cpp.LlamaCppBackend,
+ "_is_vulkan_backend",
+ staticmethod(lambda b = None: state["vulkan"]),
+ )
+ monkeypatch.setattr(
+ llama_cpp.LlamaCppBackend, "_run_vulkan_probe", staticmethod(lambda b = None: state["rows"])
+ )
+ monkeypatch.setattr(
+ pup, "_VULKAN_ROWS_TTL_S", 0.0
+ ) # rows change mid-test; the memo has its own test
+ monkeypatch.setattr(
+ sd_cpp_backend,
+ "_physical_position_of",
+ lambda hip: (state["names"][hip], state["names"][:hip].count(state["names"][hip])),
+ )
+ monkeypatch.setattr(pup, "_resident_cuda_ordinal", lambda: state["ordinal"])
+ monkeypatch.setattr(
+ pup, "_accelerator_memory_mib", lambda o = None: (160 * 1024, 180 * 1024, "cuda")
+ )
+ monkeypatch.setattr(pup, "_gpu_unowned", lambda: False)
+ monkeypatch.setattr(stt_sidecar, "_training_active", lambda: False)
+ monkeypatch.setattr(stt_mtmd_sidecar, "_llama_server_child_env", lambda b: {})
+ monkeypatch.setattr(llama_cpp, "_llama_server_api_key_enabled", lambda: False)
+ monkeypatch.setattr(process_lifetime, "is_process_shutting_down", lambda: False)
+ monkeypatch.setattr(process_lifetime, "spawn_on_lifetime_thread", lambda fn: fn())
+
+ class _Stop(Exception):
+ pass
+
+ def _popen(
+ cmd,
+ env = None,
+ **_kwargs,
+ ):
+ seen.append((cmd, env))
+ raise _Stop
+
+ monkeypatch.setattr(pup.subprocess, "Popen", _popen)
+ seen = []
+
+ def run():
+ with pytest.raises(_Stop):
+ pup.PromptUpsamplerSidecar()._spawn_server("/x/llama-server", __file__, None)
+ return seen[-1]
+
+ return state, run
+
+
+def test_vulkan_build_pins_the_image_models_card_by_name(spawn_argv, warmable):
+ state, run = spawn_argv
+ sidecar, launched, _memory, model, _mmproj = warmable
+ # The iGPU enumerates first on Vulkan, so torch's cuda:1 (the RX 7600) is Vulkan1, cuda:0 is Vulkan2.
+ argv, env = run()
+ assert argv[-2:] == ["--device", "Vulkan1"] and env == {"HIP_VISIBLE_DEVICES": "1"}
+ state["ordinal"] = 0
+ assert run()[0][-2:] == ["--device", "Vulkan2"]
+ assert sidecar.warm(binary = "b", model = model, mmproj = None) == "started"
+ sidecar._cancel_idle_locked()
+
+
+def test_vulkan_build_leaves_an_unmatched_card_unpinned(spawn_argv, warmable, monkeypatch):
+ state, run = spawn_argv
+ sidecar, launched, _memory, model, _mmproj = warmable
+ # Two cards of one model and no way to place the selection among them: no guess.
+ state["names"] = ["AMD Radeon RX 7600", "AMD Radeon RX 7600"]
+ state["rows"] = [_VULKAN_ROWS[1], {"index": 2, "name": "AMD Radeon RX 7600 (RADV NAVI33)"}]
+ from core.inference import sd_cpp_backend
+
+ monkeypatch.setattr(sd_cpp_backend, "_physical_position_of", lambda hip: (None, None))
+ monkeypatch.setenv("CUDA_VISIBLE_DEVICES", "GPU-a,GPU-b")
+ assert "--device" not in run()[0]
+ assert sidecar.warm(binary = "b", model = model, mmproj = None) == "placement"
+ monkeypatch.delenv("CUDA_VISIBLE_DEVICES")
+ state["rows"] = []
+ assert "--device" not in run()[0]
+ assert sidecar.warm(binary = "b", model = model, mmproj = None) == "placement"
+ assert launched == []
+
+
+def test_non_vulkan_and_single_card_launches_keep_their_argv(spawn_argv, monkeypatch):
+ import torch
+
+ state, run = spawn_argv
+ state["vulkan"] = False
+ assert "--device" not in run()[0]
+ state["vulkan"] = True
+ monkeypatch.setenv("LLAMA_ARG_DEVICE", "Vulkan0") # the user's own pin wins
+ assert "--device" not in run()[0]
+ monkeypatch.delenv("LLAMA_ARG_DEVICE")
+ monkeypatch.setattr(torch.cuda, "device_count", lambda: 1)
+ state["rows"] = [
+ _VULKAN_ROWS[2]
+ ] # one Vulkan device, the image model's card: nothing to choose
+ argv, env = run()
+ assert "--device" not in argv and env == {}
+
+
+def test_vulkan_sole_device_must_be_the_image_models_card(spawn_argv, warmable, monkeypatch):
+ import torch
+
+ state, run = spawn_argv
+ sidecar, launched, _memory, model, _mmproj = warmable
+ # torch holds the image model on the 7900 XTX, but the only Vulkan device is the iGPU.
+ monkeypatch.setattr(torch.cuda, "device_count", lambda: 1)
+ state["names"] = ["AMD Radeon RX 7900 XTX"]
+ state["ordinal"] = 0
+ state["rows"] = [_VULKAN_ROWS[0]]
+ assert "--device" not in run()[0]
+ assert sidecar.warm(binary = "b", model = model, mmproj = None) == "placement"
+
+
+ "count, row, pinned",
+ [
+ (2, "AMD Radeon RX 7600 XT (RADV NAVI33)", False), # containment only: another model
+ (2, "AMD Radeon RX 7600 (RADV NAVI33)", True),
+ (1, "AMD Radeon RX 7600 XT (RADV NAVI33)", True), # one torch card: as before
+ ],
+)
+def test_sole_vulkan_device_needs_the_exact_model_beside_other_cards(
+ spawn_argv, monkeypatch, count, row, pinned
+):
+ import torch
+
+ state, _run = spawn_argv
+ monkeypatch.setattr(torch.cuda, "device_count", lambda: count)
+ state["names"] = ["AMD Radeon RX 7600", "AMD Radeon RX 7900 XTX"][:count]
+ state["ordinal"] = 0
+ state["rows"] = [{"index": 0, "name": row}]
+ assert pup._vulkan_device_args("b", 0) == ([] if pinned else None)
+
+
+def test_users_vulkan_mask_wins(spawn_argv, monkeypatch):
+ state, run = spawn_argv
+ # GGML_VK_VISIBLE_DEVICES renumbers the probe's devices, so a position-based pick could name another card.
+ monkeypatch.setenv("GGML_VK_VISIBLE_DEVICES", "1,2")
+ assert "--device" not in run()[0]
+
+
+def test_vulkan_pins_one_torch_card_beside_an_igpu(spawn_argv, monkeypatch):
+ import torch
+
+ state, run = spawn_argv
+ # torch sees only the 7900 XTX, but Vulkan also lists the iGPU and a masked-off RX 7600.
+ monkeypatch.setattr(torch.cuda, "device_count", lambda: 1)
+ state["names"] = ["AMD Radeon RX 7900 XTX"]
+ state["ordinal"] = 0
+ argv, env = run()
+ assert argv[-2:] == ["--device", "Vulkan2"] and env == {}
+
+
+def test_empty_hip_mask_falls_back_to_the_cuda_mask(monkeypatch):
+ import torch
+
+ monkeypatch.setattr(torch.cuda, "device_count", lambda: 2)
+ monkeypatch.setattr(torch.version, "hip", "6.2", raising = False)
+ monkeypatch.setenv("HIP_VISIBLE_DEVICES", "")
+ monkeypatch.setenv("CUDA_VISIBLE_DEVICES", "4,5")
+ assert pup._child_device_mask(1) == {"CUDA_VISIBLE_DEVICES": "5"}
+
+
[email protected]("hip", [None, "6.2"])
+def test_users_llama_arg_device_keeps_every_card_visible(monkeypatch, hip):
+ # ROCm1 / CUDA1 would name a device a one-card mask no longer has.
+ import torch
+
+ monkeypatch.setattr(torch.cuda, "device_count", lambda: 2)
+ monkeypatch.setattr(torch.version, "hip", hip, raising = False)
+ monkeypatch.setenv("HIP_VISIBLE_DEVICES", "2,3")
+ monkeypatch.setenv("CUDA_VISIBLE_DEVICES", "2,3")
+ monkeypatch.setenv("LLAMA_ARG_DEVICE", "ROCm1" if hip else "CUDA1")
+ assert pup._child_device_mask(1) == {}
+ monkeypatch.setenv("LLAMA_ARG_DEVICE", " ")
+ assert pup._child_device_mask(1) == {("HIP" if hip else "CUDA") + "_VISIBLE_DEVICES": "3"}
+
+
+def test_negative_ordinal_never_pins_the_last_mask_entry(monkeypatch):
+ import torch
+
+ monkeypatch.setattr(torch.cuda, "device_count", lambda: 2)
+ monkeypatch.setattr(torch.version, "hip", None, raising = False)
+ monkeypatch.setenv("CUDA_VISIBLE_DEVICES", "4,5")
+ assert pup._child_device_mask(-1) == {}
+
+
+def test_rocm_wheel_without_version_hip_still_reads_the_hip_mask(monkeypatch):
+ import torch
+
+ monkeypatch.setattr(torch.cuda, "device_count", lambda: 2)
+ monkeypatch.setattr(torch.version, "hip", None, raising = False)
+ monkeypatch.setattr(torch, "__version__", "2.9.0+rocm7.1.1")
+ monkeypatch.setenv("HIP_VISIBLE_DEVICES", "2,3")
+ monkeypatch.setenv("CUDA_VISIBLE_DEVICES", "0,1,2,3")
+ assert pup._child_device_mask(1) == {"HIP_VISIBLE_DEVICES": "3"}
+
+
+def test_warm_and_spawn_share_one_vulkan_probe(monkeypatch):
+ from core.inference import llama_cpp
+
+ calls = []
+ monkeypatch.setattr(
+ llama_cpp.LlamaCppBackend,
+ "_run_vulkan_probe",
+ staticmethod(lambda b = None: calls.append(b) or list(_VULKAN_ROWS)),
+ )
+ monkeypatch.setattr(pup, "_vulkan_rows_memo", {})
+ assert (
+ pup._vulkan_rows("/x/llama-server") == pup._vulkan_rows("/x/llama-server") == _VULKAN_ROWS
+ )
+ assert calls == ["/x/llama-server"]
+
+
def test_references_follow_the_generate_decoders_side_limit():
with pytest.raises(ValueError):
pup.prepare_references([_png_url((4100, 64))])
@@ -1807,3 +2063,173 @@ def test_a_renamed_row_matches_the_first_valid_locked_box():
caption, rows = pup.split_box_table(pup.reconcile_layout_caption(answer, locked))
assert caption == "A red balloon <obj_1>."
assert [row["id"] for row in rows] == ["obj_1"] and rows[0]["desc"] == "A red balloon."
+
+
+def test_the_launch_reprobes_a_cached_empty_vulkan_answer(monkeypatch):
+ # A transient empty probe in warm() must not leave the real launch unpinned for the TTL.
+ from core.inference import llama_cpp
+
+ answers = [[], list(_VULKAN_ROWS)]
+ monkeypatch.setattr(
+ llama_cpp.LlamaCppBackend, "_run_vulkan_probe", staticmethod(lambda b = None: answers.pop(0))
+ )
+ monkeypatch.setattr(pup, "_vulkan_rows_memo", {})
+ assert pup._vulkan_rows("/x/llama-server") == []
+ assert pup._vulkan_rows("/x/llama-server") == []
+ assert pup._vulkan_rows("/x/llama-server", retry_empty = True) == _VULKAN_ROWS
+
+
+ "var, value", [("LLAMA_ARG_DEVICE", "CUDA1"), ("LLAMA_ARG_DEVICE", "ROCm1")]
+)
[email protected]("count, expected", [(2, "placement"), (1, "started")])
+def test_a_user_device_pick_declines_the_warm_start_beside_other_cards(
+ warmable, monkeypatch, var, value, count, expected
+):
+ # The memory probe reads the image model's card, not the one the user picked.
+ sidecar, _launched, _memory, model, _mmproj = warmable
+ monkeypatch.setattr(pup, "_resident_cuda_ordinal", lambda: 0)
+ monkeypatch.setattr(pup, "_cuda_device_count", lambda: count)
+ assert sidecar.warm(binary = "b", model = model, mmproj = None) == "started"
+ sidecar._cancel_idle_locked()
+ sidecar._process = sidecar._key = None
+ monkeypatch.setenv(var, value)
+ assert sidecar.warm(binary = "b", model = model, mmproj = None) == expected
+ sidecar._cancel_idle_locked()
+
+
[email protected]("count, expected", [(2, None), (1, [])])
+def test_an_external_backend_path_is_unknown_placement_beside_other_cards(
+ monkeypatch, count, expected
+):
+ import torch
+ from core.inference import llama_cpp
+
+ monkeypatch.setattr(
+ llama_cpp.LlamaCppBackend, "_is_vulkan_backend", staticmethod(lambda b = None: False)
+ )
+ monkeypatch.setattr(torch.cuda, "device_count", lambda: count)
+ monkeypatch.setenv("GGML_BACKEND_PATH", "/opt/ggml/libggml-vulkan.so")
+ assert pup._vulkan_device_args("b", 0) == expected
+ monkeypatch.delenv("GGML_BACKEND_PATH")
+ assert pup._vulkan_device_args("b", 0) == []
+
+
+def test_the_vulkan_probe_runs_before_the_render_slot(warmable, monkeypatch):
+ # A slow probe under the slot would hold renders and handovers until its timeout.
+ from core.inference import llama_cpp
+
+ sidecar, _launched, _memory, model, _mmproj = warmable
+ order = []
+ take = pup._take_render_slot
+ monkeypatch.setattr(pup, "_take_render_slot", lambda: order.append("slot") or take())
+ monkeypatch.setattr(
+ llama_cpp.LlamaCppBackend, "_is_vulkan_backend", staticmethod(lambda b = None: True)
+ )
+ monkeypatch.setattr(
+ pup, "_vulkan_rows", lambda b, retry_empty = False: order.append("probe") or []
+ )
+ sidecar.warm(binary = "b", model = model, mmproj = None)
+ assert order[:2] == ["probe", "slot"]
+ sidecar._cancel_idle_locked()
+
+
+def test_repeated_hip_entries_do_not_shift_the_pin(monkeypatch):
+ # clr keeps the first of a repeated HIP entry, so HIP=0,0,1 exposes GPUs 0 and 1.
+ import torch
+
+ monkeypatch.setattr(torch.cuda, "device_count", lambda: 2)
+ monkeypatch.setattr(torch.version, "hip", "6.2", raising = False)
+ monkeypatch.setenv("HIP_VISIBLE_DEVICES", "0,0,1")
+ monkeypatch.setenv("CUDA_VISIBLE_DEVICES", "0,1")
+ assert pup._child_device_mask(1) == {"HIP_VISIBLE_DEVICES": "1"}
+ monkeypatch.setattr(torch.version, "hip", None, raising = False)
+ monkeypatch.delenv("HIP_VISIBLE_DEVICES")
+ monkeypatch.setenv("CUDA_VISIBLE_DEVICES", "4,5")
+ assert pup._child_device_mask(1) == {"CUDA_VISIBLE_DEVICES": "5"}
+
+
[email protected]("vulkan, expected", [(False, "started"), (True, "placement")])
+def test_a_vulkan_mask_declines_the_warm_start_only_for_a_vulkan_build(
+ warmable, monkeypatch, vulkan, expected
+):
+ # CUDA and HIP builds ignore GGML_VK_VISIBLE_DEVICES; their launch is pinned by the visibility mask.
+ from core.inference import llama_cpp
+
+ sidecar, _launched, _memory, model, _mmproj = warmable
+ monkeypatch.setattr(pup, "_resident_cuda_ordinal", lambda: 0)
+ monkeypatch.setattr(pup, "_cuda_device_count", lambda: 2)
+ monkeypatch.setattr(
+ llama_cpp.LlamaCppBackend, "_is_vulkan_backend", staticmethod(lambda b = None: vulkan)
+ )
+ monkeypatch.setattr(pup, "_vulkan_rows", lambda b, retry_empty = False: [])
+ monkeypatch.setenv("GGML_VK_VISIBLE_DEVICES", "1")
+ assert sidecar.warm(binary = "b", model = model, mmproj = None) == expected
+ sidecar._cancel_idle_locked()
+
+
[email protected]("hip, probed", [(None, False), ("6.2", True)])
+def test_a_hip_mask_on_a_cuda_torch_never_steers_the_vulkan_pin(
+ spawn_argv, monkeypatch, hip, probed
+):
+ # Only ROCm applies HIP_VISIBLE_DEVICES; on a CUDA torch the card lookup would name another card of the pair.
+ import torch
+
+ state, _run = spawn_argv
+ calls = []
+ monkeypatch.setattr(pup, "_vulkan_rows", lambda b, retry_empty = False: calls.append(b) or [])
+ monkeypatch.setattr(torch.cuda, "device_count", lambda: 2)
+ monkeypatch.setattr(torch.version, "hip", hip, raising = False)
+ monkeypatch.setenv("HIP_VISIBLE_DEVICES", "2,3")
+ assert pup._vulkan_device_args("b", 0) is None
+ assert bool(calls) is probed
+
+
+def test_a_negative_ordinal_is_never_pinned():
+ assert pup._child_device_mask(-1) == {}
+ assert pup._vulkan_device_args("b", -1) == []
+
+
+ "row, pinned",
+ [("AMD Radeon RX 7600 XT (RADV NAVI33)", False), ("AMD Radeon RX 7600 (RADV NAVI33)", True)],
+)
+def test_a_loose_name_match_beside_other_vulkan_devices_is_unknown(
+ spawn_argv, monkeypatch, row, pinned
+):
+ # An iGPU beside the XT must not make the XT stand in for the RX 7600 the memory probe read.
+ import torch
+
+ state, _run = spawn_argv
+ monkeypatch.setattr(torch.cuda, "device_count", lambda: 1)
+ state["names"] = ["AMD Radeon RX 7600"]
+ state["ordinal"] = 0
+ state["rows"] = [_VULKAN_ROWS[0], {"index": 1, "name": row}]
+ assert pup._vulkan_device_args("b", 0) == (["--device", "Vulkan1"] if pinned else None)
+
+
[email protected]("vulkan", [True, False])
+def test_an_external_backend_path_is_unknown_even_for_a_vulkan_bundle(monkeypatch, vulkan):
+ # The probe would list the bundled Vulkan library, not the backends GGML_BACKEND_PATH loads.
+ import torch
+ from core.inference import llama_cpp
+
+ monkeypatch.setattr(
+ llama_cpp.LlamaCppBackend, "_is_vulkan_backend", staticmethod(lambda b = None: vulkan)
+ )
+ monkeypatch.setattr(torch.cuda, "device_count", lambda: 2)
+ calls = []
+ monkeypatch.setattr(
+ pup, "_vulkan_rows", lambda b, retry_empty = False: calls.append(b) or list(_VULKAN_ROWS)
+ )
+ monkeypatch.setenv("GGML_BACKEND_PATH", "/opt/ggml/backends")
+ assert pup._vulkan_device_args("b", 0) is None
+ assert calls == []
+
+
+def test_a_user_main_gpu_is_a_device_pick(monkeypatch):
+ # A one-device --device list would leave LLAMA_ARG_MAIN_GPU=1 out of range under split mode none.
+ monkeypatch.delenv("LLAMA_ARG_DEVICE", raising = False)
+ monkeypatch.setenv("LLAMA_ARG_MAIN_GPU", "1")
+ assert pup._user_device_pick() is True
+ assert pup._vulkan_device_args("b", 0) == []
diff --git a/studio/backend/tests/test_sd_cpp_rocm_vulkan_fallback.py b/studio/backend/tests/test_sd_cpp_rocm_vulkan_fallback.py
index cc0dbb312ef..6b91d1fc91c 100644
--- a/studio/backend/tests/test_sd_cpp_rocm_vulkan_fallback.py
+++ b/studio/backend/tests/test_sd_cpp_rocm_vulkan_fallback.py
@@ -2756,6 +2756,34 @@ class TestSelectedCardIndexSpaces:
# Composing the stale ROCR mask in would have made this 3 rather than 2.
assert sd_cpp_backend._physical_index_of(0, env = env) == (2, True)
+ def test_an_empty_hip_mask_does_not_shadow_the_cuda_mask(self, monkeypatch):
+ """ROCm ignores an empty HIP_VISIBLE_DEVICES and reads CUDA_VISIBLE_DEVICES."""
+ from core.inference import sd_cpp_backend
+
+ monkeypatch.setattr(sd_cpp_backend.sys, "platform", "linux")
+ env = {"HIP_VISIBLE_DEVICES": "", "CUDA_VISIBLE_DEVICES": "4,5"}
+ assert sd_cpp_backend._physical_index_of(1, env = env) == (5, True)
+ # Every present mask empty still hides every card.
+ assert sd_cpp_backend._physical_index_of(0, env = {"HIP_VISIBLE_DEVICES": ""}) == (None, True)
+
+ def test_repeated_mask_entries_follow_hip_and_rocr_rules(self, monkeypatch):
+ """clr keeps the first of a repeated HIP entry; ROCr ends the list at a repeat."""
+ from core.inference import sd_cpp_backend
+
+ monkeypatch.setattr(sd_cpp_backend.sys, "platform", "linux")
+ assert sd_cpp_backend._physical_index_of(1, env = {"HIP_VISIBLE_DEVICES": "0,0,1"}) == (
+ 1,
+ True,
+ )
+ assert sd_cpp_backend._physical_index_of(0, env = {"ROCR_VISIBLE_DEVICES": "2,2,3"}) == (
+ 2,
+ True,
+ )
+ assert sd_cpp_backend._physical_index_of(1, env = {"ROCR_VISIBLE_DEVICES": "2,2,3"}) == (
+ None,
+ True,
+ )
+
def _recorded_proven(store: dict, klass: str = "rocm") -> bool:
record = (store.get("sd_cpp_accelerator_runtime_failures") or {}).get(klass) or {}