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
fix(amd): gate ROCm GPU selection and crash recovery on the build's arch coverage (#7670)
Leo Borcherding5a3e9fc7a685
diff --git a/studio/backend/core/inference/llama_cpp.py b/studio/backend/core/inference/llama_cpp.pyindex e9bfded9f56..fd2e4b2625c 100644--- a/studio/backend/core/inference/llama_cpp.py+++ b/studio/backend/core/inference/llama_cpp.py@@ -3419,6 +3419,15 @@ class LlamaCppBackend:# Relative model share per GPU (--tensor-split), in GPU order; None =# default (llama.cpp splits by free VRAM).self._tensor_split: Optional[List[float]] = None+ # Ratio the arch gate dropped from this argv, so the duplicate-load check+ # knows the live server already IS this request normalized (#7624).+ self._arch_gate_dropped_tensor_split: Optional[tuple[float, ...]] = None+ # Same for the split MODE: the gate drops --split-mode tensor when it forces+ # CPU or leaves one survivor, and the request still asks for it.+ self._arch_gate_dropped_tensor_parallel: bool = False+ # Gate masked every device away, so an AUTOMATIC request became a zero-VRAM+ # launch (#7624), which is why holds_no_vram cannot demand manual mode.+ self._arch_gate_forced_cpu: bool = False# User-picked physical GPU indices (None = automatic selection).self._gpu_ids: Optional[List[int]] = None# RAW requested GPU pin, before the fit narrowed it. self._gpu_ids records the@@ -4033,14 +4042,18 @@ class LlamaCppBackend:@propertydef holds_no_vram(self) -> bool:- """Whether the resident server is a confirmed zero-VRAM launch.-- True only for a deliberate manual zero-offload load whose launched argv carried no GPU- companion, pin or tensor mode, so the child was started with the GPUs hidden. The GPU- arbiter uses this to leave an image/video pipeline alone when re-asserting ownership for- such a model. ``_gpu_offload_active`` is None when no GPU was detected at all (nothing to- arbitrate) and True when something still reached the GPU, so both keep the normal path.- """+ """Whether the resident server is a confirmed zero-VRAM launch, so the GPU+ arbiter can leave an image/video pipeline alone when re-asserting ownership.++ True for a manual zero-offload load whose argv carried no GPU companion, pin+ or tensor mode (``_gpu_offload_active`` None or True keeps the normal path),+ and for an arch-gated launch masked onto the CPU by the "-1" sentinel+ (#7624). The latter arrives through an AUTOMATIC request, so demanding manual+ mode would answer False for the case routes/inference.py:8206 documents and+ leave a VRAM-less server holding the CHAT claim, unloadable by an owner it+ never competed with."""+ if self._arch_gate_forced_cpu:+ return Truereturn (self._gpu_memory_mode == "manual"and self._gpu_layers == 0@@ -4159,7 +4172,11 @@ class LlamaCppBackend:elif not _tensor_parallel_matches_loaded(extra_args, intent.tensor_parallel, self._tensor_parallel):- return False+ # A mode the gate normalised away is this request normalized, not a+ # different one. Guarded on a RECORDED drop, so a launch that dropped+ # nothing cannot excuse a live tensor server against a layer request.+ if not (self._arch_gate_dropped_tensor_parallel and not self._tensor_parallel):+ return Falseif (self._layer_preserves_tensor_intentand not _effective_tensor_parallel(extra_args, intent.tensor_parallel)@@ -4190,8 +4207,18 @@ class LlamaCppBackend:intent.gpu_layers >= 0and (self._n_cpu_moe != intent.n_cpu_moe- or (tuple(self._tensor_split) if self._tensor_split else None)- != (intent.tensor_split or None)+ or (+ (tuple(self._tensor_split) if self._tensor_split else None)+ != (intent.tensor_split or None)+ # Same rule as the mode above: a dropped ratio is this+ # request normalized. Guarded on a RECORDED drop, never+ # None == None. Any other ratio reloads.+ and not (+ self._arch_gate_dropped_tensor_split is not None+ and self._arch_gate_dropped_tensor_split+ == (intent.tensor_split or None)+ )+ )))):@@ -4951,28 +4978,25 @@ class LlamaCppBackend:return "vulkan" in backends and not backends.intersection({"cuda", "hip"})@staticmethod- def _resolve_visible_physical_ids() -> Optional[list[int]]:- """Physical GPU ids behind the active visibility mask (HIP/ROCR/CUDA on- ROCm, CUDA otherwise). None when no mask is set; empty list for an empty- mask. Shared by the APU / datacenter / free-memory probes so they agree- on the ordinal->physical mapping."""+ def _active_gpu_visibility_mask() -> Optional[str]:+ """The raw visibility mask in force (HIP, then ROCR, then CUDA on ROCm; CUDA+ otherwise), or None when unset. Split out so a caller can tell "no mask" from+ "a mask I cannot map to physical ids"."""try:import torch- # Same ROCm detection as _emit_child_gpu_visibility: AMD SDK wheels- # leave version.hip unset but encode "rocm" in __version__. The two- # must agree, else an inherited ROCR mask reads back as "no mask",- # ordinal 0 is labelled physical 0, and the child's new ROCR pin- # re-exposes the GPU the inherited mask was hiding.+ # Same ROCm detection as _emit_child_gpu_visibility (AMD SDK wheels leave+ # version.hip unset but encode "rocm" in __version__). If the two+ # disagree an inherited ROCR mask reads back as "no mask" and the child's+ # new pin re-exposes the GPU it was hiding.is_rocm = LlamaCppBackend._torch_is_rocm(torch)except Exception:is_rocm = Falseif is_rocm:hip_v = os.environ.get("HIP_VISIBLE_DEVICES")- # ROCR_VISIBLE_DEVICES is a Linux ROCr variable; Windows HIP has no- # ROCr layer, so a stray ROCR var there does not mask the runtime and- # must not be read as the ordinal->physical mapping (mirrors the- # Windows gate in _emit_child_gpu_visibility).+ # ROCR_VISIBLE_DEVICES is Linux-only: Windows HIP has no ROCr layer, so a+ # stray ROCR var there masks nothing and must not be read as the+ # ordinal->physical mapping (mirrors _emit_child_gpu_visibility).rocr_v = None if sys.platform == "win32" else os.environ.get("ROCR_VISIBLE_DEVICES")cvd = (hip_v@@ -4983,6 +5007,14 @@ class LlamaCppBackend:)else:cvd = os.environ.get("CUDA_VISIBLE_DEVICES")+ return cvd++ @staticmethod+ def _resolve_visible_physical_ids() -> Optional[list[int]]:+ """Physical GPU ids behind the active visibility mask (HIP/ROCR/CUDA on+ ROCm, CUDA otherwise). None when unset, [] for an empty mask. Shared by the+ APU / datacenter / free-memory probes so they agree on the mapping."""+ cvd = LlamaCppBackend._active_gpu_visibility_mask()if cvd is None:return Nonetry:@@ -4990,6 +5022,19 @@ class LlamaCppBackend:except ValueError:return None+ @staticmethod+ def _visibility_mask_is_unmappable() -> bool:+ """True when a mask IS set but does not resolve to physical ids: ROCr and CUDA+ accept UUID tokens (ROCR_VISIBLE_DEVICES="0,GPU-DEADBEEF..."), CUDA also MIG+ ids. Torch ordinals cannot be mapped back, so re-emitting them numerically+ would REPLACE the mask with ids the runtime resolves against the whole host,+ handing the child cards the parent hid, including one a gate just dropped.+ Callers that would pin fail open. False when unset and for an empty mask."""+ return (+ LlamaCppBackend._active_gpu_visibility_mask() is not None+ and LlamaCppBackend._resolve_visible_physical_ids() is None+ )+@staticmethoddef _emit_child_gpu_visibility(env: dict,@@ -5001,20 +5046,23 @@ class LlamaCppBackend:(masking only CUDA_VISIBLE_DEVICES leaves an AMD child seeing every GPU).Default: HIP_VISIBLE_DEVICES, clearing any inherited ROCR mask so the two- can't stack (ROCR re-indexes from 0, then a non-zero HIP pin points out of+ cannot stack (ROCR re-indexes from 0, a non-zero HIP pin then points out ofrange, HIP sees 0 devices, and llama.cpp falls back to CPU).- prefer_rocr masks at the ROCr/HSA layer instead (clearing HIP). A HIP mask+ prefer_rocr masks at the ROCr/HSA layer instead (clearing HIP): a HIP maskfilters only AFTER the HSA runtime enumerates every agent, and that- enumeration segfaults at startup on a GPU the build has no kernels for- (e.g. a gfx1036 iGPU under a gfx103X prebuilt: that bundle maps only- gfx1030/1031/1032/1034), before llama-server logs a line. ROCR drops the- device at the driver layer, consuming physical ids.- The CPU-only sentinel ("-1") has no portable ROCR spelling, so it keeps- the HIP mask. Windows keeps the HIP mask too: ROCR_VISIBLE_DEVICES is a- Linux ROCr variable (Windows HIP has no ROCr layer), so the ROCR pin- would be dead there while the cleared HIP mask stops selecting."""+ enumeration segfaults on a GPU the build has no kernels for (gfx1036 iGPU+ under a gfx103X prebuilt) before llama-server logs a line.++ The CPU sentinel ("-1") keeps the HIP mask and leaves an inherited ROCR mask+ alone: HIP sees zero devices either way, so the anti-stacking clear buys+ nothing while dropping the mask re-exposes hidden agents to that same+ enumeration. Windows keeps the HIP mask too, ROCR being Linux-only."""env["CUDA_VISIBLE_DEVICES"] = pinned+ if pinned == "-1":+ # An inherited LLAMA_ARG_DEVICE / LLAMA_ARG_MAIN_GPU naming a device that+ # no longer enumerates makes llama.cpp exit rather than use our CPU.+ LlamaCppBackend._clear_device_placement_env(env)try:import torch as _torch@@ -5037,7 +5085,8 @@ class LlamaCppBackend:)else:env["HIP_VISIBLE_DEVICES"] = pinned- env.pop("ROCR_VISIBLE_DEVICES", None)+ if pinned != "-1":+ env.pop("ROCR_VISIBLE_DEVICES", None)except Exception as e:logger.debug("Failed to set ROCm visibility env vars for child: %s", e)@@ -5225,6 +5274,17 @@ class LlamaCppBackend:or "rocm" in getattr(torch, "__version__", "").lower())+ @staticmethod+ def _host_torch_is_rocm() -> bool:+ """Whether torch here is a ROCm build, without the caller importing torch.+ False when torch is missing or unreadable. Cheap guard so a CUDA or+ CPU-only host does not pay for ROCm-only work (#7624)."""+ try:+ import torch+ return LlamaCppBackend._torch_is_rocm(torch)+ except Exception:+ return False+@staticmethoddef _rocm_unified_memory_gpu_ids() -> set[int]:"""PHYSICAL ids of visible ROCm GPUs whose "VRAM" is shared system RAM.@@ -5266,6 +5326,48 @@ class LlamaCppBackend:except Exception:return set()+ @staticmethod+ def _rocm_arch_by_physical_id() -> dict[int, str]:+ """Base gfx arch (lowercased, ``:xnack`` stripped) per PHYSICAL device id,+ honoring the active ROCm visibility mask (HIP, then ROCR, then CUDA).++ Read through the training worker's classifier so the alternate spellings+ AMD SDK / Radeon wheels use (``gcn_arch_name``, ``arch_name``,+ ``gfx_arch_name``) are covered as well as canonical ``gcnArchName``;+ reading only the canonical name would leave the map empty on those wheels+ and silently fail the gate open. Devices torch cannot describe are omitted;+ empty off ROCm and on any error."""+ arch_by_id: dict[int, str] = {}+ try:+ import torch++ if not LlamaCppBackend._torch_is_rocm(torch):+ return arch_by_id+ if not (hasattr(torch, "cuda") and torch.cuda.is_available()):+ return arch_by_id+ from core.training.worker import _rocm_classify_unified_memory++ physical_ids = LlamaCppBackend._resolve_visible_physical_ids()+ for ordinal in range(torch.cuda.device_count()):+ try:+ _arch, _is_unified = _rocm_classify_unified_memory(+ torch.cuda.get_device_properties(ordinal)+ )+ except Exception:+ continue+ _base = (_arch or "").split(":")[0].strip().lower()+ if not _base:+ continue+ pid = (+ physical_ids[ordinal]+ if physical_ids is not None and ordinal < len(physical_ids)+ else ordinal+ )+ arch_by_id[pid] = _base+ except Exception:+ return arch_by_id+ return arch_by_id+@staticmethoddef _amd_apu_wants_unified_memory(gpu_indices = None) -> bool:"""True only for AMD unified-memory APUs, where GGML_CUDA_ENABLE_UNIFIED_MEMORY@@ -5440,12 +5542,102 @@ class LlamaCppBackend:strip_device = True,)+ # A concrete per-device gfx arch: "gfx" plus digits, with the trailing hex letter+ # real parts carry (gfx90a, gfx90c), which a digits-only pattern would reject.+ # Deliberately does NOT match generic code objects (gfx11-generic) or family+ # labels (gfx110X); no device reports either, and the gate fails open on them.+ _CONCRETE_GFX_ARCH = re.compile(r"^gfx[0-9][0-9a-f]{2,4}$")+@staticmethod- def _get_gpu_free_memory(binary: Optional[str] = None) -> list[tuple[int, int]]:- """Query free memory per GPU. Returns ``(gpu_index, free_mib)`` sorted by- index; empty if no supported GPU is reachable. Thin wrapper over- ``_get_gpu_memory`` for callers that only need free VRAM."""- return [(idx, free) for idx, free, _total in LlamaCppBackend._get_gpu_memory(binary)]+ def _installed_llama_gfx_archs(binary: Optional[str] = None) -> Optional[frozenset]:+ """Concrete gfx archs the installed ROCm prebuilt was built for+ (``mapped_targets`` in UNSLOTH_PREBUILT_INFO.json). None when unknown (no+ marker, non-ROCm bundle), so callers fail open and keep every device+ (#7624). Never raises."""+ try:+ from utils.llama_cpp_freshness import read_install_marker++ marker = read_install_marker(binary or LlamaCppBackend._find_llama_server_binary())+ if not marker:+ return None+ targets = marker.get("mapped_targets")+ if not isinstance(targets, list):+ return None+ archs = frozenset(+ str(t).split(":")[0].strip().lower() for t in targets if str(t).strip()+ )+ if not archs:+ return None+ # Exact-set membership against what the device reports, so it only means+ # anything while every token is concrete. One token no device can report+ # (generic code object, family label, malformed marker) matches nothing,+ # dropping EVERY GPU and silently forcing CPU, worse than not gating.+ # mapped_targets is remote data versioned independently of this code, so+ # an unrecognised list is "unknown" and fails open, all or nothing:+ # dropping just the odd token would under-report the build's coverage.+ unknown = sorted(a for a in archs if not LlamaCppBackend._CONCRETE_GFX_ARCH.match(a))+ if unknown:+ logger.warning(+ f"install marker mapped_targets has non-concrete arch tokens "+ f"{unknown}; skipping the GPU arch gate"+ )+ return None+ return archs+ except Exception as e:+ logger.debug(f"install marker arch read failed: {e}")+ return None++ @classmethod+ def _arch_gate_survivors(cls, binary: Optional[str] = None) -> list[int]:+ """Physical ids the ROCm arch gate leaves, or [] when there is nothing to+ mask: unknown coverage, a non-ROCm host, a build covering every card, or an+ inherited mask whose ids we cannot name back to the child.++ For callers that must PIN the answer, not just rank by it: the child+ enumerates every ROCm agent, and that HSA enumeration is what dies on an+ uncovered arch, so a mixed host (unsupported iGPU + supported dGPU) passes+ the gate and still crashes unless the survivors are masked in. Lazy, and+ never raises."""+ try:+ # Coverage first: a cached marker read, where _host_torch_is_rocm imports+ # torch (~1.3s cold). Non-ROCm bundles record no mapped_targets, so they+ # answer [] without that import.+ if cls._installed_llama_gfx_archs(binary) is None:+ return [] # unknown coverage: fail open, same as the probe+ if not cls._host_torch_is_rocm():+ return []+ if cls._visibility_mask_is_unmappable():+ # A UUID/MIG mask leaves ordinals unmapped, so pinning would swap it+ # for numbers the runtime resolves against the whole host, possibly+ # re-exposing the dropped card. Fail open (pre-#7624).+ logger.info(+ "Not pinning the arch gate's survivors: the inherited GPU "+ "visibility mask is not index based, so they cannot be named "+ "to the child."+ )+ return []+ gated = [+ idx for idx, _free, _total in cls._get_gpu_memory(binary, for_llama_server = True)+ ]+ everything = [idx for idx, _free, _total in cls._get_gpu_memory(binary)]+ return gated if gated and len(gated) < len(everything) else []+ except Exception as e:+ logger.debug(f"arch gate survivor probe failed: {e}")+ return []++ @staticmethod+ def _get_gpu_free_memory(+ binary: Optional[str] = None, *, for_llama_server: bool = False+ ) -> list[tuple[int, int]]:+ """Free memory per GPU as ``(gpu_index, free_mib)`` sorted by index; empty+ if no supported GPU is reachable. Thin wrapper over ``_get_gpu_memory``,+ which also documents ``for_llama_server`` (forwarded verbatim)."""+ return [+ (idx, free)+ for idx, free, _total in LlamaCppBackend._get_gpu_memory(+ binary, for_llama_server = for_llama_server+ )+ ]@staticmethoddef _apple_metal_memory_budget_bytes() -> int:@@ -5476,29 +5668,32 @@ class LlamaCppBackend:return int(rec_bytes * _APPLE_UNIFIED_MEMORY_FRACTION)@staticmethod- def _get_gpu_memory(binary: Optional[str] = None) -> list[tuple[int, int, int]]:+ def _get_gpu_memory(+ binary: Optional[str] = None, *, for_llama_server: bool = False+ ) -> list[tuple[int, int, int]]:"""Query free AND total memory per GPU.- Order:- 1. ``nvidia-smi`` (NVIDIA CUDA hosts) -- respects- ``CUDA_VISIBLE_DEVICES``.- 2. ``torch.cuda.mem_get_info`` -- universal fallback that works- on AMD ROCm too (HIP runtime reuses the ``torch.cuda.*``- namespace). Covers the AMD case for issue #5106 (nvidia-smi- probe returned [] on AMD) and NVIDIA hosts missing- ``nvidia-smi`` from PATH.-- On a Vulkan build the ggml Vulkan probe is authoritative, so the indices- are ggml's compact Vulkan ordinals (the space the pin selects via- ``--device Vulkan<i>``). It reports ``total`` for discrete cards and 0- for an iGPU (shared RAM) so the fit falls back to free*frac there.- Otherwise nvidia-smi / torch cover NVIDIA + AMD ROCm. The torch branch- gives an AMD unified-memory APU the same treatment by arch name, since- ROCm reports no iGPU flag of its own.+ Order: ``nvidia-smi`` (NVIDIA, respects ``CUDA_VISIBLE_DEVICES``), then+ ``torch.cuda.mem_get_info``, a universal fallback that works on ROCm too+ (HIP reuses the ``torch.cuda.*`` namespace). The fallback covers #5106+ (nvidia-smi returned [] on AMD) and NVIDIA hosts without nvidia-smi on PATH.++ On a Vulkan build the ggml Vulkan probe is authoritative, so the indices are+ ggml's compact Vulkan ordinals (what ``--device Vulkan<i>`` selects). It+ reports ``total`` for discrete cards and 0 for an iGPU (shared RAM) so the+ fit falls back to free*frac. The torch branch treats an AMD unified-memory+ APU the same way by arch name, ROCm having no iGPU flag of its own.++ ``for_llama_server`` opts into the ROCm arch gate: devices whose gfx arch is+ not in the prebuilt's built-arch list are dropped, so auto placement cannot+ pick a GPU that binary has no kernels for (#7624). Off by default because+ this probe also backs ``core/rag/embeddings.py::_resolve_auto``, where such a+ device is usually still fine under PyTorch and filtering it would push+ sentence-transformers onto the CPU for no reason. Pass it only where a+ llama-server process is about to be placed.Returns (gpu_index, free_mib, total_mib) sorted by index; empty if no- supported GPU is reachable.- """+ supported GPU is reachable."""binary = binary or LlamaCppBackend._find_llama_server_binary()if LlamaCppBackend._is_vulkan_backend(binary):return LlamaCppBackend._get_gpu_free_memory_vulkan(binary)@@ -5572,6 +5767,17 @@ class LlamaCppBackend:# Shared-pool APU: same as the Vulkan iGPU path. Hold back the host# margin, and report total 0 since that "total" is system RAM.unified_ids = LlamaCppBackend._rocm_unified_memory_gpu_ids()+ # llama-server placement only: gate on the prebuilt's built-arch list so+ # the free-memory rank cannot pick a GPU the binary has no kernels for+ # (#7624: an iGPU reporting shared RAM outranks the dGPU and the child+ # dies with "device kernel image is invalid"). Unknown coverage, or a+ # device with no reported arch, keeps every device.+ supported_archs = None+ arch_by_id: dict[int, str] = {}+ if for_llama_server and LlamaCppBackend._torch_is_rocm(torch):+ supported_archs = LlamaCppBackend._installed_llama_gfx_archs(binary)+ if supported_archs is not None:+ arch_by_id = LlamaCppBackend._rocm_arch_by_physical_id()gpus = []# Windows ROCm's free reading is an over-report on discrete cards too,# not only on the shared pool handled below (#8403). It is capped@@ -5586,6 +5792,14 @@ class LlamaCppBackend:if physical_ids is not None and ordinal < len(physical_ids)else ordinal)+ if supported_archs is not None:+ _base = arch_by_id.get(idx, "")+ if _base and _base not in supported_archs:+ logger.warning(+ f"Skipping GPU {idx} ({_base}): installed llama.cpp "+ f"prebuilt only covers {sorted(supported_archs)}"+ )+ continueshared = idx in unified_idsraw_mib = free_bytes // (1024 * 1024)if shared:@@ -6069,6 +6283,18 @@ class LlamaCppBackend:for name in ("LLAMA_ARG_DEVICE", "LLAMA_ARG_MAIN_GPU"):env.pop(name, None)+ @classmethod+ def _clear_split_placement_env(cls, env: dict[str, str]) -> None:+ """Remove an inherited split mode / ratio when the arch gate drops ours.++ These are the env spelling of --split-mode / --tensor-split, so stripping the+ tokens alone leaves the inherited value in force. It matters more here: a+ tensor split aborts a child with no visible device, and a narrowed set+ re-indexes the survivors so an inherited positional ratio lands on the wrong+ card."""+ for name in ("LLAMA_ARG_SPLIT_MODE", "LLAMA_ARG_TENSOR_SPLIT"):+ env.pop(name, None)+@staticmethoddef _select_gpus(model_size_bytes: int,@@ -7984,6 +8210,10 @@ class LlamaCppBackend:# the unload reset) so /status doesn't misreport TP and an identical# re-Apply doesn't reload against stale tensor-parallel state.self._tensor_parallel = False+ # Same reason, sharper consequence: a diffusion runner DOES hold VRAM, so a+ # leftover arch-gate flag would answer holds_no_vram True and let the arbiter+ # run a competing workload into its memory (#7624).+ self._arch_gate_forced_cpu = False# The single-device runner records only the lowest selected GPU (chosen# above), not the whole pick, and clears any explicit pin from a prior# chat load; a multi-GPU list would misreport placement and mis-dedup.@@ -9957,6 +10187,82 @@ class LlamaCppBackend:cls._is_signal_crash(returncode) or cls._is_abort_exit(returncode))+ # ROCm's arch-mismatch crash: no compiled kernels for the device it launched on+ # (#7624). Deterministic, so only a different device helps, not a fit / flash-attn+ # retry. Four spellings because clr returns four codes for "no code object for+ # THIS device": hip_fatbin.cpp raises them, hip_platform.cpp propagates them out+ # of the launch path, and ggml reprints hipGetErrorString verbatim. Matching only+ # hipErrorInvalidImage (what both field logs show) would leave a build raising+ # hipErrorNoBinaryForGpu on the misleading GGUF/memory error.+ _KERNEL_IMAGE_INVALID_MARKERS = (+ "device kernel image is invalid", # hipErrorInvalidImage+ "no kernel image is available for execution", # hipErrorNoBinaryForGpu+ "invalid kernel file", # hipErrorInvalidKernelFile+ "invalid device function", # hipErrorInvalidDeviceFunction+ )++ @classmethod+ def _kernel_image_invalid(cls, output: str) -> bool:+ # Case-folded: hipGetErrorString is lowercase, but the layers that+ # reprint it are not consistent about that.+ text = (output or "").lower()+ return any(marker in text for marker in cls._KERNEL_IMAGE_INVALID_MARKERS)++ @classmethod+ def _arch_crash_retry_gpu_ids(cls, selected, enumerated) -> list[int]:+ """Devices to retry on after a "device kernel image is invalid" crash.++ Prefer the enumerated GPUs the failed launch never touched. When it used every+ one the crash does not name the offending card, so narrow instead: drop the+ unified-memory devices, where this mismatch keeps landing (#7624, the+ shared-pool APU's system-RAM "free memory" outranked the dGPU). Empty when+ nothing would change, when narrowing leaves no device, or on a single-GPU+ host."""+ _selected = set(selected or ())+ if not _selected:+ return []+ remaining = sorted(i for i in set(enumerated or ()) if i not in _selected)+ if remaining or len(_selected) < 2:+ return remaining+ try:+ discrete = sorted(_selected - cls._rocm_unified_memory_gpu_ids())+ except Exception:+ return []+ return discrete if 0 < len(discrete) < len(_selected) else []++ @staticmethod+ def _without_tensor_split(cmd: list[str]) -> Optional[list[str]]:+ """Return cmd with ``--tensor-split``/``-ts`` removed (both spellings and the+ ``--tensor-split=1,2`` form), or None when it carries none.++ The shares are positional over the child's VISIBLE device list, so a respawn+ that masks a device out re-indexes the survivors while keeping the old+ weights, handing card N the share sized for card N-1. Dropping the flag falls+ back to llama.cpp's free-VRAM split, correct for any device set."""+ return LlamaCppBackend._without_flags(cmd, ("--tensor-split", "-ts"))++ @staticmethod+ def _without_flags(cmd: list[str], names: Collection[str]) -> Optional[list[str]]:+ """Return cmd with every ``names`` flag (and its value) dropped, or None when+ it carries none. ``_flag_name`` peels ``--key=value`` and underscore+ spellings; only the two-token form swallows the next entry. Pass VALUE-TAKING+ flags only: valueless ones (``--mlock``, ``--no-mmap``, bare ``-fa``) would+ drop whatever argv entry follows."""+ out: list[str] = []+ found = False+ skip = False+ for tok in cmd:+ if skip:+ skip = False+ continue+ token = str(tok)+ if _flag_name(token) in names:+ found = True+ skip = "=" not in token+ continue+ out.append(token)+ return out if found else None+@staticmethoddef _with_flash_attn_off(cmd: list[str]) -> Optional[list[str]]:"""Return cmd with flash attention forced off, or None when its effective@@ -11239,7 +11545,10 @@ class LlamaCppBackend:self._gpu_memory_mode = gpu_memory_mode# The layer/MoE/split knobs apply only with an explicit offload# (manual + gpu_layers >= 0); else record defaults so /status and- # /load don't report knobs the server never applied.+ # /load don't report knobs the server never applied. Reset before the+ # branch so an earlier launch's recorded drop cannot excuse this one.+ self._arch_gate_dropped_tensor_split = None+ self._arch_gate_dropped_tensor_parallel = Falseif gpu_memory_mode == "manual" and gpu_layers >= 0:self._gpu_layers = gpu_layersself._n_cpu_moe = n_cpu_moe@@ -11386,6 +11695,11 @@ class LlamaCppBackend:# empty `gpus` so the speculative defaults stay GPU-aware and the# CPU-fallback check still knows GPUs were present._detected_gpus: list[tuple[int, int]] = []+ # Set when the arch gate emptied a non-empty GPU pool, so the env+ # block below masks the child onto the CPU. Bound before the try for+ # the same reason as _detected_gpus: the except path (--fit on) falls+ # through to the launch, which reads it.+ _arch_gate_forced_cpu = Falsetotal_by_idx: dict[int, int] = {}model_size = None # set in the fit try; used by the APU RAM guard# Layer-fallback min GPUs; raised below on a tensor downgrade. Bound@@ -11410,7 +11724,55 @@ class LlamaCppBackend:# 2-tuple gpus for existing logic + a total map for the absolute# per-GPU headroom (correct when the GPU is already partly used).# Pass binary so a Vulkan build probes ggml's Vulkan ordinals.- _gpu_mem = self._get_gpu_memory(binary)+ # AUTOMATIC placement only. Gating an explicit pin would leave+ # `gpus` empty, skipping the fit and layer plan and forcing+ # `--fit on`, yet `gpu_indices` is restored from `gpu_ids` below+ # so the pin happens anyway. A pinned uncovered GPU is the user's+ # call and already reports "device kernel image is invalid".+ _gpu_mem = self._get_gpu_memory(binary, for_llama_server = not gpu_ids)+ # Every present device gated out (#7624). Left alone the launch+ # takes the `--fit on` arm with `gpu_indices` still None, so no+ # mask is written, the child enumerates every unsupported card and+ # dies, and the reactive retry cannot help (its guard needs a+ # truthy `gpu_indices`). CPU is the only placement that runs here.+ # ROCm auto only; the guard spares CUDA and CPU-only hosts, where+ # an empty probe just means "no GPU".+ if (+ not gpu_ids+ and not _gpu_mem+ and not is_vulkan_backend+ and self._host_torch_is_rocm()+ ):+ _ungated = self._get_gpu_memory(binary)+ # Re-derive the verdict rather than infer it from the empty+ # result: _get_gpu_memory turns any probe error into [], so+ # "gated empty, ungated not" also describes a one-shot failure+ # of the FIRST probe on a host the gate never filters, and+ # masking that onto CPU is a silent, permanent cliff. Unknown+ # coverage or an unreadable arch keeps every device.+ _coverage = self._installed_llama_gfx_archs(binary)+ _arch_by_id = self._rocm_arch_by_physical_id() if _ungated else {}+ _all_uncovered = (+ bool(_ungated)+ and _coverage is not None+ and all(+ (_arch_by_id.get(idx) or "") not in ("", *_coverage)+ for idx, _free, _total in _ungated+ )+ )+ if _all_uncovered:+ _arch_gate_forced_cpu = True+ _present = ", ".join(+ f"{idx} ({_arch_by_id.get(idx) or 'unknown arch'})"+ for idx, _free, _total in _ungated+ )+ logger.warning(+ "The installed llama.cpp build has no kernels for "+ "any GPU on this host (%s), so inference falls back "+ "to CPU. Reinstall llama.cpp for these devices to "+ "get GPU inference back.",+ _present,+ )if is_vulkan_backend and not gpu_ids and gpu_memory_mode != "manual":_gpu_mem = self._vulkan_auto_gpu_memory(_gpu_mem)gpus = [(idx, free) for idx, free, _t in _gpu_mem]@@ -12690,6 +13052,21 @@ class LlamaCppBackend:_ram_msg = self._apu_ram_shortfall_message(model_size, self._available_system_memory_mib())+ # gpu_indices is None for a launch nothing pinned, so the guard+ # priced every visible card, including an APU the gate is about to+ # drop and whose shared pool the narrowed child never touches.+ # Re-ask for the set the child will actually see. Refusal branch+ # only, so a passing launch pays for no probe; an empty answer+ # keeps the refusal.+ if _ram_msg and gpu_indices is None and not gpu_ids:+ _gated_pin = self._arch_gate_survivors(binary)+ if _gated_pin and not self._amd_apu_wants_unified_memory(_gated_pin):+ logger.info(+ "Skipping the APU RAM refusal: the arch gate pins "+ "this launch to discrete GPU(s) %s.",+ _gated_pin,+ )+ _ram_msg = Noneif _ram_msg:raise RuntimeError(_ram_msg)@@ -13340,14 +13717,20 @@ class LlamaCppBackend:# counts and a later user --fit still wins by last-arg.fit_active = fit_is_effectively_on([*cmd, *(_mem_extra_args or [])], _mem_env),)+ # The gate masks every device away, so the child runs from host RAM+ # whatever was asked, while _weights_in_host_memory answered for the+ # ORIGINAL placement. Without this the page-lock is skipped and+ # _memory_mlock_applicable records that as deliberate, which no+ # relaunch undoes.+ if _arch_gate_forced_cpu:+ _mem_host_resident = True_mem_managed, _mem_extras = apply_model_memory_policy(extra_args,supports_load_mode = bool(server_caps.get("supports_load_mode")),weights_in_host_memory = _mem_host_resident,)- # Remembered so the reload hint and the duplicate-load- # comparator don't demand an mlock this launch deliberately- # skipped, which no relaunch could ever satisfy.+ # Remembered so the reload hint and the duplicate-load comparator do+ # not demand an mlock this launch deliberately skipped.self._memory_mlock_applicable = _mem_host_residentif should_mlock() and not _mem_host_resident:logger.info(@@ -13434,6 +13817,16 @@ class LlamaCppBackend:extra_args or [])self._memory_policy_active = bool(_mem_managed) or _mem_policy_touched_extras+ # What `cmd` itself means, snapshotted before any respawn edits it.+ # _spawn_and_wait's --fit retries append a page-lock to THEIR argv+ # and write the policy back; the arch-crash retry (#7624) respawns+ # `cmd`, which never carried that lock, so it restores these.+ _mem_policy_for_cmd = (+ _mem_host_resident,+ self._memory_state,+ self._memory_policy_active,+ self._memory_mlock_applicable,+ )# Omitting --threads relies on llama.cpp's physical-core default, so# drop an inherited LLAMA_ARG_THREADS that would otherwise feed the# arg handler and silently force hardware_concurrency(). #5692@@ -13523,10 +13916,14 @@ class LlamaCppBackend:if not threads_overridden:env.setdefault("OMP_NUM_THREADS", "2")- # AMD unified-memory APUs (gfx1150/gfx1151): let llama.cpp use- # shared system RAM. setdefault so a user value wins. Not on Vulkan- # (nor DC below): gpu_indices are ggml ordinals, not CUDA/ROCm ids.+ # AMD unified-memory APUs (gfx1150/gfx1151): let llama.cpp use shared+ # system RAM. setdefault so a user value wins. Not on Vulkan (nor DC+ # below): gpu_indices are ggml ordinals, not CUDA/ROCm ids. Tracked by+ # OWNERSHIP, so the arch-crash retry withdraws it only when THIS launch+ # set it.+ _unified_env_applied = Falseif not is_vulkan_backend and self._amd_apu_wants_unified_memory(gpu_indices):+ _unified_env_applied = "GGML_CUDA_ENABLE_UNIFIED_MEMORY" not in envenv.setdefault("GGML_CUDA_ENABLE_UNIFIED_MEMORY", "1")logger.info("AMD unified-memory APU: set GGML_CUDA_ENABLE_UNIFIED_MEMORY=1")@@ -13542,29 +13939,61 @@ class LlamaCppBackend:# On ROCm, narrowing only CUDA_VISIBLE_DEVICES leaves the AMD child# seeing the full set, so set HIP_VISIBLE_DEVICES too. Vulkan is pinned# via --device (above), not here.- # A deliberate zero-offload load with no GPU companions runs- # entirely on CPU, yet a visible CUDA device still costs the child- # ~0.5 GB (context + compute scratch) that the CPU-only- # classification below reports as free. Hide the GPUs so the load- # is exactly what it claims: zero VRAM (verified: GPU stays at idle- # baseline and generation runs). Companion loads keep the normal- # masking, and a user device pin (in extras or an inherited- # LLAMA_ARG_DEVICE) keeps control of its own devices -- the child- # aborts on a pin it can't see. The draft-device forms count too:- # llama-server parses them even with no drafter loaded.+ # A deliberate zero-offload load with no GPU companions runs entirely+ # on CPU, yet a visible CUDA device still costs the child ~0.5 GB+ # (context + compute scratch) that the CPU-only classification below+ # reports as free. Hide the GPUs so the load is exactly what it+ # claims. Companion loads keep the normal masking, and a user device+ # pin (extras or an inherited LLAMA_ARG_DEVICE) keeps control of its+ # own devices, the child aborting on a pin it cannot see. The+ # draft-device forms count too: parsed with no drafter loaded._cpu_only_zero_offload = (gpu_memory_mode == "manual"and gpu_layers == 0and not is_vulkan_backendand not self._zero_offload_keeps_gpu_visible(cmd, env))- if _cpu_only_zero_offload:+ # The arch gate emptying the pool lands here for the same reason+ # (#7624): no device set this binary can launch on, so the child must+ # not see the cards it would enumerate and abort on. gpu_indices is+ # None there, so this branch writes the mask.+ if _cpu_only_zero_offload or _arch_gate_forced_cpu:self._emit_child_gpu_visibility(env, "-1")+ # Manual mode admits tensor parallelism on the FULL device count,+ # which still counts the dropped cards, so --split-mode tensor can+ # reach a child that sees none. llama_prepare_model_devices then+ # fails with "LLAMA_SPLIT_MODE_TENSOR needs >= 1 devices" and+ # llama-server exits 1 rather than falling back, so normalise to+ # layer/CPU. Gate-scoped: the zero-offload arm already dropped+ # Studio's flags, and a user --split-mode there is overridden.+ _cpu_cmd = (+ self._without_flags(cmd, ("--split-mode", "-sm", "--tensor-split", "-ts"))+ if _arch_gate_forced_cpu+ else None+ )+ if _cpu_cmd is not None:+ logger.info(+ "Forced-CPU launch: dropped the split-mode/tensor-split "+ "flags, which abort a server with no visible device."+ )+ cmd = _cpu_cmd+ # Recorded, or the next Apply reads the normalized server as a+ # different one and rebuilds a multi-GB model every time.+ if self._tensor_parallel:+ self._arch_gate_dropped_tensor_parallel = True+ if self._tensor_split:+ self._arch_gate_dropped_tensor_split = tuple(self._tensor_split)+ self._tensor_parallel = False+ self._tensor_split = None+ if _arch_gate_forced_cpu:+ # Not gated on the argv strip: llama.cpp reads the LLAMA_ARG_*+ # twins whether or not we emitted the flags, so an inherited+ # tensor mode aborts a child with no visible device on its own.+ self._clear_split_placement_env(env)elif gpu_indices is not None and not is_vulkan_backend:- # When the user picked GPUs by index, align CUDA's ordering- # with the PCI-bus order the picker enumerated (nvidia-smi),- # so "GPU 1" in the UI is GPU 1 to llama.cpp -- not CUDA's- # default FASTEST_FIRST order (#5025).+ # When the user picked GPUs by index, align CUDA's ordering with+ # the PCI-bus order the picker enumerated, so "GPU 1" in the UI is+ # GPU 1 to llama.cpp, not CUDA's FASTEST_FIRST default (#5025).if gpu_ids:env["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID"# Mask on AMD at the ROCr/HSA layer: HIP-only masking still@@ -13573,13 +14002,83 @@ class LlamaCppBackend:self._emit_child_gpu_visibility(env, ",".join(str(i) for i in gpu_indices), prefer_rocr = True)- elif manual_tensor_split_emitted and not is_vulkan_backend:- # A manual per-GPU ratio across ALL GPUs (no explicit pick, so- # no CUDA_VISIBLE_DEVICES mask above): the UI built the- # --tensor-split list in ascending physical/PCI index order,- # so pin the child's enumeration to that order too. The whole- # visible set stays in use; only its ordering is fixed.- self._pin_visible_gpu_order_for_split(env)+ elif not is_vulkan_backend and not gpu_ids:+ # Nothing above pinned the child. Two shapes land here and the gate+ # breaks both the same way, so they share one probe: `--fit on`+ # owning placement, and a manual per-GPU ratio across ALL GPUs.+ # Either way gpu_indices is None, the reactive retry's guard cannot+ # fire, and an uncovered card reaches the child. gpu_ids is falsy+ # by construction, an explicit pick taking the arm above.+ _survivors = self._arch_gate_survivors(binary)+ if _survivors:+ # The manual ratio was validated against the FULL visible+ # count and masking re-indexes the survivors under it -- the+ # positional mismatch _without_tensor_split exists for. Drop it+ # and let llama.cpp split the survivors by free VRAM.+ _gated_cmd = self._without_tensor_split(cmd)+ if _gated_cmd is not None:+ logger.warning(+ "Dropping the manual --tensor-split: it was sized "+ "for every visible GPU, and the installed build "+ "has no kernels for some of them."+ )+ cmd = _gated_cmd+ # The argv lost the ratio but the request still carries+ # it and the next Apply re-sends it verbatim. Record it, or+ # the duplicate-load check reads the normalized server as a+ # different one and rebuilds it on every Apply.+ self._arch_gate_dropped_tensor_split = (+ tuple(self._tensor_split) if self._tensor_split else None+ )+ self._tensor_split = None+ # Narrowing to one survivor leaves --split-mode tensor a no-op+ # still REPORTED as active (tensor_parallel drives the UI and+ # arms the MTP crash watchdog), manual mode having admitted it+ # on the FULL device count. _without_tensor_split takes only the+ # ratio, so drop the mode too, as the arch-crash retry does.+ if len(_survivors) < 2 and self._tensor_parallel:+ _no_tensor_mode = self._without_flags(cmd, ("--split-mode", "-sm"))+ if _no_tensor_mode is not None:+ cmd = _no_tensor_mode+ self._arch_gate_dropped_tensor_parallel = True+ self._tensor_parallel = False+ logger.info(+ "The arch gate leaves one GPU; dropped tensor "+ "parallelism, which needs at least two."+ )+ logger.info(+ "The installed llama.cpp build has no kernels for GPU(s) "+ "left visible; pinning the child to %s.",+ _survivors,+ )+ # The argv strips above cannot reach an inherited split+ # mode or ratio, and the mask re-indexes the survivors+ # under both.+ self._clear_split_placement_env(env)+ # GGML_CUDA_ENABLE_UNIFIED_MEMORY was decided against+ # gpu_indices, None here, so an uncovered APU anywhere on the+ # host turned it on -- and this narrowing hands the child only+ # discrete cards, where _amd_apu_wants_unified_memory's docstring+ # calls it harmful. Same withdrawal and ownership check as the+ # arch-crash retry: only the value THIS launch set.+ if _unified_env_applied and not self._amd_apu_wants_unified_memory(+ _survivors+ ):+ env.pop("GGML_CUDA_ENABLE_UNIFIED_MEMORY", None)+ _unified_env_applied = False+ logger.info(+ "Arch gate narrowed the launch to discrete GPU(s); "+ "dropped GGML_CUDA_ENABLE_UNIFIED_MEMORY."+ )+ self._emit_child_gpu_visibility(+ env, ",".join(str(i) for i in _survivors), prefer_rocr = True+ )+ elif manual_tensor_split_emitted:+ # A manual per-GPU ratio across ALL GPUs (no explicit pick, so+ # no mask above): the UI built --tensor-split in ascending+ # physical/PCI order, so pin the child's enumeration to match.+ # The whole visible set stays in use, only its order is fixed.+ self._pin_visible_gpu_order_for_split(env)# Captured before any text-only fallback strips it from cmd.launched_with_mmproj = "--mmproj" in cmd@@ -13965,6 +14464,176 @@ class LlamaCppBackend:"llama-server aborted on --split-mode tensor ""(split-axis geometry); retrying with layer split.")+ # "device kernel image is invalid": the auto-pinned device's arch has+ # no kernels in this binary (#7624: an iGPU whose shared-RAM "free+ # memory" outranked the dGPU). The proactive mapped_targets gate cannot+ # see custom-linked builds, so catch the crash and retry once on a+ # narrowed set. Auto selection only; an explicit pick keeps its error.+ if (+ not healthy+ and not self._cancel_event.is_set()+ and not gpu_ids+ and not is_vulkan_backend+ and gpu_indices+ and self._kernel_image_invalid("\n".join(self._stdout_lines[-80:]))+ ):+ _crashed = sorted(set(gpu_indices))+ # _detected_gpus, not gpus: the post-picker enumeration this launch+ # planned against, and unlike `gpus` it survives the manual mode that+ # empties the pool to bypass the planner.+ _remaining = self._arch_crash_retry_gpu_ids(+ gpu_indices, [i for i, _free in _detected_gpus]+ )+ if _remaining:+ _retry_wants_unified = self._amd_apu_wants_unified_memory(_remaining)+ # The APU RAM preflight upstream ran against the CRASHED+ # selection, discrete on this arm by construction, so it never+ # fired. The mirror shape (crash on the dGPU, retry on the+ # unified-memory sibling) makes the respawn the first load into+ # system RAM. Unchecked, an oversized GGUF is OOM-killed+ # mid-load instead of getting the refusal the same host gives+ # when the APU is picked first.+ if model_size is not None and _retry_wants_unified:+ _retry_ram_msg = self._apu_ram_shortfall_message(+ model_size, self._available_system_memory_mib()+ )+ if _retry_ram_msg:+ self._kill_process()+ raise RuntimeError(_retry_ram_msg)+ logger.warning(+ f"llama-server crashed with a HIP kernel-image error on "+ f"GPU(s) {_crashed} -- the llama.cpp build has no kernels "+ f"for that arch. Retrying on GPU(s) {_remaining}."+ )+ self._kill_process()+ gpu_indices = _remaining+ # GGML_CUDA_ENABLE_UNIFIED_MEMORY was decided for the CRASHED+ # set. The canonical #7624 shape crashes on the APU and retries+ # on the dGPU, where it is harmful, so withdraw it, but only+ # the value this launch set. Both directions: a markerless+ # mixed host can as easily crash on the dGPU and land on the+ # APU, which needs it.+ if _unified_env_applied and not _retry_wants_unified:+ env.pop("GGML_CUDA_ENABLE_UNIFIED_MEMORY", None)+ _unified_env_applied = False+ logger.info(+ "Arch-crash retry targets discrete GPU(s); dropped "+ "GGML_CUDA_ENABLE_UNIFIED_MEMORY for the respawn."+ )+ elif _retry_wants_unified and "GGML_CUDA_ENABLE_UNIFIED_MEMORY" not in env:+ env["GGML_CUDA_ENABLE_UNIFIED_MEMORY"] = "1"+ _unified_env_applied = True+ logger.info(+ "Arch-crash retry targets a unified-memory APU; set "+ "GGML_CUDA_ENABLE_UNIFIED_MEMORY=1 for the respawn."+ )+ self._emit_child_gpu_visibility(+ env, ",".join(str(i) for i in _remaining), prefer_rocr = True+ )+ # Same for the inherited env twins of the flags dropped+ # below: the new mask re-indexes the survivors under them.+ self._clear_split_placement_env(env)+ # The mask re-indexes the survivors from 0, so a --tensor-split+ # sized for the crashed set weights the wrong cards (see+ # _without_tensor_split). Drop it and let llama.cpp split by+ # free VRAM over the narrowed set.+ _arch_retry_cmd = self._without_tensor_split(cmd)+ if _arch_retry_cmd is not None:+ logger.info(+ "Dropped --tensor-split for the arch-crash retry: "+ "its shares are positional over the visible "+ "devices and the narrowed set re-indexes them."+ )+ cmd = _arch_retry_cmd+ # No ratio record, unlike the proactive gate: _tensor_split+ # is non-None only in manual mode, which leaves gpu_indices+ # None, and this arm needs it truthy.+ self._tensor_split = None+ # A tensor split needs two devices, so narrowing to one makes+ # --split-mode tensor a no-op still REPORTED as active+ # (tensor_parallel drives the UI and the MTP watchdog). Strip it.+ if len(_remaining) < 2 and self._tensor_parallel:+ _no_tensor_mode = self._without_flags(cmd, ("--split-mode", "-sm"))+ if _no_tensor_mode is not None:+ cmd = _no_tensor_mode+ self._arch_gate_dropped_tensor_parallel = True+ self._tensor_parallel = False+ logger.info(+ "Arch-crash retry leaves one GPU; dropped tensor "+ "parallelism, which needs at least two."+ )+ # This respawn starts from `cmd`, but the crashed launch may+ # have taken _spawn_and_wait's --fit retry, which appends a+ # page-lock to its OWN argv and records it. `cmd` never carried+ # that lock, so leaving the record alone lets+ # memory_state_satisfies_settings judge the launch satisfied and+ # dedupe away the reload that would apply the user's page-lock.+ # Restore what `cmd` means (a no-op when no retry fired).+ (+ _mem_host_resident,+ self._memory_state,+ self._memory_policy_active,+ self._memory_mlock_applicable,+ ) = _mem_policy_for_cmd+ # Residency is a property of the DEVICES, which the retry just+ # changed: crash on the discrete card, land on the+ # unified-memory APU, and the weights are host-backed after+ # all, so the lock the first launch skipped is the one the user+ # asked for. Left alone the respawn runs unlocked AND records+ # _memory_mlock_applicable False, reading the missing lock as+ # deliberate and deduping away the reload that would apply it.+ # Through the same helpers, so the two cannot drift.+ _retry_host_resident = self._weights_in_host_memory(+ fully_gpu_offloaded = fully_gpu_offloaded,+ gpu_memory_mode = gpu_memory_mode,+ gpu_layers = gpu_layers,+ extra_args = _mem_extra_args,+ gpu_indices = _remaining,+ is_vulkan_backend = is_vulkan_backend,+ binary = binary,+ env = env,+ probe_vulkan = should_mlock(),+ fit_active = fit_is_effectively_on([*cmd, *(_mem_extra_args or [])], env),+ )+ # Lock-ADDING direction only: `cmd` carries a policy-emitted+ # lock only when the first launch found the weights+ # host-resident, so this is the one direction that adds without+ # taking anything back off argv. Removing flags would mean+ # scanning for --mlock/--no-mmap, VALUELESS in llama.cpp's+ # parser, so the scan would eat the user extra after them. The+ # reverse direction leaves the crashed launch's lock in place,+ # which stays truthful: the child does hold it.+ if _retry_host_resident and not _mem_host_resident:+ _retry_managed, _ = apply_model_memory_policy(+ extra_args,+ supports_load_mode = bool(server_caps.get("supports_load_mode")),+ weights_in_host_memory = _retry_host_resident,+ )+ if _retry_managed:+ # After the user extras, so llama.cpp's last-wins parse+ # gives it the final say over any hand-written memory+ # flag. Nothing is stripped, so kept extras survive.+ cmd.extend(_retry_managed)+ _mem_host_resident = _retry_host_resident+ self._memory_mlock_applicable = _retry_host_resident+ # Stays active if it already was: the flag also+ # covers extras this policy touched and env it+ # scrubbed, neither of which the respawn undoes.+ self._memory_policy_active = (+ bool(_retry_managed) or self._memory_policy_active+ )+ # In argv order -- extras first, then the appended+ # lock -- because the resolver is last-wins too.+ self._memory_state = resolve_effective_memory_state(+ list(_mem_extras) + list(_retry_managed), env+ )+ logger.info(+ "Arch-crash retry changed where the weights live; "+ "recomputed Model Memory (%s).",+ " ".join(_retry_managed) if _retry_managed else "no page-lock",+ )+ healthy = _spawn_and_wait(cmd, label = "-archfallback")+# Flash-attention kernels hard-crash at startup on some ROCm/GPU# builds (frequently inside the vision tower). Disabling FA keeps# both vision and MTP, so retry that way before dropping either.@@ -14350,11 +15019,25 @@ class LlamaCppBackend:# offload (no picker) leaves gpu_indices None and use_fit False, so# include its GPU-layer intent; use the preserved probe since# auto-layers/manual empty `gpus`. A deliberate zero-offload load- # classifies by its launched argv instead: the main model is- # CPU-only by construction and must read False (not None), or- # training needlessly unloads a server holding no VRAM.- _deliberate_cpu_only = gpu_memory_mode == "manual" and gpu_layers == 0- if _deliberate_cpu_only:+ # classifies by its launched argv instead: CPU-only by construction, it+ # must read False (not None) or training needlessly unloads a server+ # holding no VRAM. An arch-gated launch is CPU-only for a stronger+ # reason still: the env block masked every device away ("-1").+ _deliberate_cpu_only = (+ gpu_memory_mode == "manual" and gpu_layers == 0+ ) or _arch_gate_forced_cpu+ # Published on EVERY load, not only when true: load_model phase 1 only+ # kills the old process, so a stale value would answer holds_no_vram+ # for the child that replaced it. A host that gains coverage (a+ # llama.cpp update) would then report a VRAM-holding server as holding+ # none, and the arbiter leave it unclaimed.+ self._arch_gate_forced_cpu = bool(_arch_gate_forced_cpu)+ if _arch_gate_forced_cpu:+ # False, never None: _classify_gpu_offload answers None here (the+ # gated probe left _detected_gpus empty) and training spares only an+ # exactly-False server, so None unloads one that frees no VRAM.+ self._gpu_offload_active = False+ elif _deliberate_cpu_only:self._gpu_offload_active = self._zero_offload_gpu_flag(_last_spawn_cmd, _detected_gpus, env)@@ -15159,6 +15842,7 @@ class LlamaCppBackend:self._gpu_layers = -1self._n_cpu_moe = 0self._tensor_split = None+ self._arch_gate_forced_cpu = Falseself._layer_preserves_tensor_intent = Falseself._speculative_type = Noneself._requested_spec_mode = Nonediff --git a/studio/backend/core/rag/embed_llama_server.py b/studio/backend/core/rag/embed_llama_server.pyindex f043df21293..687b574bdfa 100644--- a/studio/backend/core/rag/embed_llama_server.py+++ b/studio/backend/core/rag/embed_llama_server.py@@ -219,16 +219,32 @@ class LlamaServerBackend:def _gpu_available() -> bool:"""Apple Metal, or an NVIDIA/ROCm GPU with enough free VRAM. Reusesllama_cpp's static probe (nvidia-smi first, so the common path needs no- torch)."""+ torch). This backend IS llama-server, so it opts into the ROCm arch gate: an+ uncovered device crashes the embedding server as it does a chat load+ (#7624)."""from utils.hardware import is_apple_siliconif is_apple_silicon():return True # bundled mac build offloads to Metalfrom core.inference.llama_cpp import LlamaCppBackend- gpus = LlamaCppBackend._get_gpu_free_memory() # [(idx, free_mib)], honors CVD+ # [(idx, free_mib)], honors CVD+ gpus = LlamaCppBackend._get_gpu_free_memory(for_llama_server = True)return any(free >= LlamaServerBackend._MIN_GPU_FREE_MIB for _, free in gpus)+ @staticmethod+ def _arch_gated_gpu_ids(binary: str) -> list[int]:+ """GPU ids to pin the embedding child to, or [] when it needs no mask.++ Knowing a supported device exists is not enough: the child enumerates every+ ROCm agent, and that HSA enumeration is what dies on an uncovered GPU (#7624),+ so on a mixed host the gate passes on the dGPU and the server still crashes on+ the iGPU. Pin the survivors instead. Empty unless the gate is both known and+ actually narrowing: NVIDIA, CPU, Vulkan and macOS have no mapped_targets+ marker, and a build covering every card needs no pin."""+ from core.inference.llama_cpp import LlamaCppBackend+ return LlamaCppBackend._arch_gate_survivors(binary)+def _build_cmd(self, binary: str, model_path: str, port: int, *, use_gpu: bool) -> list[str]:# No --embd-normalize (not in every build; we normalize in Python to match# the ST path). --fit off: don't auto-resize ctx/offload to device memory.@@ -255,9 +271,33 @@ class LlamaServerBackend:env["LLAMA_SET_ROWS"] = "1" # ggml set_rows fast pathif use_gpu:self._add_linux_cuda_libs(env, str(Path(binary).parent))+ _pinned = self._arch_gated_gpu_ids(binary)+ if _pinned:+ from core.inference.llama_cpp import LlamaCppBackend++ # prefer_rocr: a HIP-only mask still lets HSA enumerate (and die+ # on) the unsupported agent; ROCR drops it at the driver layer.+ LlamaCppBackend._emit_child_gpu_visibility(+ env, ",".join(str(i) for i in _pinned), prefer_rocr = True+ )+ logger.info("pinning the embed server to arch-supported GPU(s) %s", _pinned)else:# Blank devices so a CUDA build stays on CPU and reserves no VRAM.env["CUDA_VISIBLE_DEVICES"] = ""+ # HIP reads CUDA_VISIBLE_DEVICES only when HIP_VISIBLE_DEVICES is unset,+ # so an inherited HIP mask would keep a device (and the ~0.5 GB context it+ # costs) visible to a child we just put on the CPU. Same "-1" sentinel the+ # chat forced-CPU path uses. An inherited ROCR mask is left alone: it hides+ # agents below HIP, so clearing it would expose MORE of them to the HSA+ # enumeration that dies on an uncovered arch (#7624).+ env["HIP_VISIBLE_DEVICES"] = "-1"+ # LLAMA_ARG_DEVICE / LLAMA_ARG_MAIN_GPU are the env spelling of --device /+ # --main-gpu. Hiding every device while leaving that pick in place makes+ # llama.cpp reject the name that no longer enumerates and exit instead of+ # running on the CPU. Same clear the chat sentinel makes.+ from core.inference.llama_cpp import LlamaCppBackend++ LlamaCppBackend._clear_device_placement_env(env)return env@staticmethoddiff --git a/studio/backend/core/rag/embeddings.py b/studio/backend/core/rag/embeddings.pyindex cab2b81dbd6..10fd9301b6a 100644--- a/studio/backend/core/rag/embeddings.py+++ b/studio/backend/core/rag/embeddings.py@@ -535,6 +535,10 @@ def _resolve_auto() -> str:-- or ST if its binary is missing. GPU check is torch-free (nvidia-smi)."""from core.inference.llama_cpp import LlamaCppBackend+ # Unfiltered probe on purpose: the winner here runs under PyTorch, so the+ # ROCm arch gate (which asks what the installed llama.cpp prebuilt was built+ # for, #7624) must not apply. A device that prebuilt lacks kernels for is+ # usually still a perfectly good sentence-transformers device.if LlamaCppBackend._get_gpu_free_memory():return "sentence-transformers"if LlamaCppBackend._find_llama_server_binary():diff --git a/studio/backend/tests/test_gpu_arch_gate_7624.py b/studio/backend/tests/test_gpu_arch_gate_7624.pynew file mode 100644index 00000000000..cf16eb5fce8--- /dev/null+++ b/studio/backend/tests/test_gpu_arch_gate_7624.py@@ -0,0 +1,518 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Regression tests for #7624 / #7669: multi-GPU auto-selection on ROCm must not+pick a device the installed llama.cpp prebuilt has no kernels for.++Covers _installed_llama_gfx_archs (mapped_targets from the install marker),+_rocm_arch_by_physical_id, the opt-in per-device gate in _get_gpu_memory's torch+fallback, the crash marker, and the retry set. Also pins the two things the gate+must NOT do: filter the probe for torch callers, and displace the unified-memory+APU accounting that shares this loop.+"""++import json+import subprocess+import sys+import types++import pytest++# Imported eagerly so the fake torch below cannot be in place when the real+# module graph is first loaded.+from core.inference.llama_cpp import _IGPU_HOST_RESERVE_MIB, LlamaCppBackend+from core.training.worker import _rocm_classify_unified_memory # noqa: F401+++def _binary_with_marker(tmp_path, payload):+ """Lay out <root>/UNSLOTH_PREBUILT_INFO.json with a binary path below it,+ matching the managed install layout the marker walk-up covers."""+ (tmp_path / "UNSLOTH_PREBUILT_INFO.json").write_text(json.dumps(payload), encoding = "utf-8")+ return str(tmp_path / "build" / "bin" / "llama-server")+++class TestInstalledLlamaGfxArchs:+ def test_reads_mapped_targets(self, tmp_path):+ binary = _binary_with_marker(+ tmp_path, {"mapped_targets": ["gfx1100", "GFX1101", "gfx1102:xnack-"]}+ )+ archs = LlamaCppBackend._installed_llama_gfx_archs(binary)+ assert archs == frozenset({"gfx1100", "gfx1101", "gfx1102"})++ def test_no_marker_is_unknown(self, tmp_path):+ # Source build / custom-linked dir: no marker anywhere above the binary.+ assert LlamaCppBackend._installed_llama_gfx_archs(str(tmp_path / "llama-server")) is None++ def test_no_binary_is_unknown(self, monkeypatch):+ monkeypatch.setattr(+ LlamaCppBackend, "_find_llama_server_binary", staticmethod(lambda: None)+ )+ assert LlamaCppBackend._installed_llama_gfx_archs() is None++ def test_pre_7669_install_is_unknown(self, tmp_path):+ # Older installs have no mapped_targets key: fail open.+ binary = _binary_with_marker(tmp_path, {"asset": "app-windows-x64-rocm-gfx110X.zip"})+ assert LlamaCppBackend._installed_llama_gfx_archs(binary) is None++ def test_empty_targets_is_unknown(self, tmp_path):+ # Non-ROCm bundles record []: fail open rather than drop every GPU.+ binary = _binary_with_marker(tmp_path, {"mapped_targets": []})+ assert LlamaCppBackend._installed_llama_gfx_archs(binary) is None++ def test_unreadable_marker_is_unknown(self, tmp_path, monkeypatch):+ # A raising marker read must answer "unknown", never propagate: it runs+ # inside the GPU probe, where an exception would drop every device.+ import utils.llama_cpp_freshness as freshness++ def _boom(_binary):+ raise OSError("marker read failed")++ monkeypatch.setattr(freshness, "read_install_marker", _boom)+ assert LlamaCppBackend._installed_llama_gfx_archs(str(tmp_path / "llama-server")) is None+++# Every shape the install marker can arrive in, as (label, contents). It is read+# back after arbitrary upgrades, partial writes, disk damage and hand-editing, so+# the reader parses untrusted input. A callable lays out a non-JSON-file shape.+_MARKER_CORPUS = [+ ("absent_file", None),+ ("empty_file", ""),+ ("invalid_json", "{not json"),+ ("truncated_json", '{"mapped_targets": ["gfx1030"'),+ ("marker_is_a_list", '["gfx1030"]'),+ ("marker_is_null", "null"),+ ("marker_is_a_string", '"hello"'),+ ("marker_is_empty_dict", "{}"),+ ("targets_null", '{"mapped_targets": null}'),+ ("targets_empty_string", '{"mapped_targets": ""}'),+ ("targets_bare_string", '{"mapped_targets": "gfx1030"}'),+ ("targets_empty_list", '{"mapped_targets": []}'),+ ("targets_list_of_null", '{"mapped_targets": [null]}'),+ ("targets_list_of_int", '{"mapped_targets": [123]}'),+ ("targets_blank_strings", '{"mapped_targets": ["", " "]}'),+ ("targets_dict", '{"mapped_targets": {"a": "gfx1030"}}'),+ ("targets_huge_list", json.dumps({"mapped_targets": [f"gfx{i:04d}" for i in range(5000)]})),+ ("cuda_bundle", '{"asset": "app-linux-x64-cuda12.tar.gz"}'),+ ("vulkan_bundle", '{"asset": "app-linux-x64-vulkan.tar.gz", "mapped_targets": []}'),+ ("non_utf8_bytes", lambda p: p.write_bytes(b"\xff\xfe\x00garbage")),+ ("directory_in_place_of_file", lambda p: p.mkdir()),+ (+ "permission_denied",+ lambda p: (p.write_text(json.dumps({"mapped_targets": ["gfx1030"]})), p.chmod(0o000)),+ ),+ # Forwards compatibility: mapped_targets is remote data (it comes from the+ # release manifest, which versions independently of this code), so a future+ # publish can put a token in it that no device will ever report.+ ("future_generic_target", '{"mapped_targets": ["gfx11-generic"]}'),+ ("future_generic_target_dashed", '{"mapped_targets": ["gfx10-3-generic"]}'),+ ("future_family_label", '{"mapped_targets": ["gfx110X"]}'),+ ("future_mixed_concrete_and_generic", '{"mapped_targets": ["gfx1100", "gfx11-generic"]}'),+]+++class TestInstalledLlamaGfxArchsCorpus:+ """The gate must degrade to "unknown" on every malformed marker. Raising is fatal+ (this runs inside the GPU probe); a non-None set no device can match is quieter+ and just as fatal, dropping every GPU. None or concrete archs, nothing between."""++ @pytest.mark.parametrize("label,payload", _MARKER_CORPUS, ids = [c[0] for c in _MARKER_CORPUS])+ def test_never_raises_and_never_fails_closed(self, label, payload, tmp_path):+ import utils.llama_cpp_freshness as freshness++ root = tmp_path / label+ root.mkdir()+ marker = root / "UNSLOTH_PREBUILT_INFO.json"+ if callable(payload):+ payload(marker)+ elif payload is not None:+ marker.write_text(payload, encoding = "utf-8")+ # The walk-up memoizes per binary path; each case gets its own root.+ freshness._marker_cache.clear()++ archs = LlamaCppBackend._installed_llama_gfx_archs(+ str(root / "build" / "bin" / "llama-server")+ )++ if archs is None:+ return+ assert isinstance(archs, frozenset)+ # Not merely non-empty: every token must be one a device can report,+ # otherwise the set gates every GPU off the host.+ assert archs, f"{label} returned an empty set, which would drop every GPU"+ assert all(+ LlamaCppBackend._CONCRETE_GFX_ARCH.match(a) for a in archs+ ), f"{label} returned unmatchable tokens {sorted(archs)}"++ def test_empty_set_is_converted_to_none(self, tmp_path):+ # `return archs or None` is what does this. Pinned explicitly because a+ # frozenset() return would type-check fine and fail closed at runtime.+ binary = _binary_with_marker(tmp_path, {"mapped_targets": ["", " ", ":"]})+ assert LlamaCppBackend._installed_llama_gfx_archs(binary) is None++ def test_non_list_targets_are_rejected_before_iteration(self, tmp_path, monkeypatch):+ # Pins the isinstance(targets, list) guard alone: every non-list json.loads+ # can produce is ALSO caught downstream, so the corpus cannot tell the guard+ # from its absence. A tuple is not JSON-reachable, which is the point.+ import utils.llama_cpp_freshness as freshness+ monkeypatch.setattr(+ freshness, "read_install_marker", lambda _b: {"mapped_targets": ("gfx1030",)}+ )+ assert LlamaCppBackend._installed_llama_gfx_archs(str(tmp_path / "llama-server")) is None++ def test_concrete_targets_still_gate(self, tmp_path):+ # The corpus is all about degrading safely; this pins that the normal+ # case is untouched, so "never fails closed" cannot be met by gutting+ # the feature.+ binary = _binary_with_marker(tmp_path, {"mapped_targets": ["gfx1030", "gfx90a"]})+ assert LlamaCppBackend._installed_llama_gfx_archs(binary) == frozenset(+ {"gfx1030", "gfx90a"}+ )+++class TestForwardsCompatibleArchTokens:+ """A future manifest may record a non-concrete target: ROCm 6.3+ generic code+ objects, or the umbrella labels this repo already carries in gfx_target. Devices+ still report the CONCRETE arch, so exact-set membership against a generic token+ matches nothing and would drop every GPU. Fail open on anything uninterpretable."""++ @pytest.mark.parametrize(+ "token",+ [+ "gfx11-generic",+ "gfx10-3-generic",+ "gfx9-4-generic",+ "gfx110X",+ "gfx120X",+ "gfx103X",+ "generic",+ "all",+ "native",+ ],+ )+ def test_non_concrete_token_disables_the_gate(self, token, tmp_path):+ binary = _binary_with_marker(tmp_path, {"mapped_targets": [token]})+ assert LlamaCppBackend._installed_llama_gfx_archs(binary) is None++ def test_one_bad_token_disables_the_whole_gate(self, tmp_path):+ # Deliberately all-or-nothing. Keeping just the concrete half of+ # ["gfx1100", "gfx11-generic"] would gate a gfx1101 device off a build+ # that the generic object actually covers.+ binary = _binary_with_marker(tmp_path, {"mapped_targets": ["gfx1100", "gfx11-generic"]})+ assert LlamaCppBackend._installed_llama_gfx_archs(binary) is None++ @pytest.mark.parametrize(+ "token", ["gfx803", "gfx900", "gfx906", "gfx908", "gfx90a", "gfx90c", "gfx942", "gfx950"]+ )+ def test_real_concrete_archs_are_accepted(self, token, tmp_path):+ # The published manifest's mapped_targets entries, plus the CDNA parts+ # whose trailing hex letter a digits-only pattern would wrongly reject.+ binary = _binary_with_marker(tmp_path, {"mapped_targets": [token]})+ assert LlamaCppBackend._installed_llama_gfx_archs(binary) == frozenset({token})++ def test_every_published_mapped_target_is_accepted(self, tmp_path):+ # Verbatim from llama-prebuilt-manifest.json (b10360-mix-87da1a2): the union+ # of every ROCm bundle's mapped_targets. A pattern rejecting any of these+ # turns the gate off for real installs.+ published = [+ "gfx908", "gfx90a",+ "gfx1030", "gfx1031", "gfx1032", "gfx1034",+ "gfx1100", "gfx1101", "gfx1102", "gfx1103",+ "gfx1150", "gfx1151",+ "gfx1200", "gfx1201",+ ] # fmt: skip+ binary = _binary_with_marker(tmp_path, {"mapped_targets": published})+ assert LlamaCppBackend._installed_llama_gfx_archs(binary) == frozenset(published)++ def test_generic_target_keeps_every_gpu(self, tmp_path, monkeypatch, rocm_probe_env):+ # End to end: without the guard this host loses BOTH cards and drops to+ # CPU, because neither gfx1100 nor gfx1101 equals "gfx11-generic".+ _binary_with_marker(tmp_path, {"mapped_targets": ["gfx11-generic"]})+ monkeypatch.setitem(+ sys.modules, "torch", _fake_torch(["gfx1100", "gfx1101"], [12000, 13000])+ )+ assert LlamaCppBackend._get_gpu_free_memory(for_llama_server = True) == [+ (0, 12000),+ (1, 13000),+ ]+++class TestKernelImageInvalidMarker:+ def test_detects_rocm_arch_mismatch(self):+ tail = (+ "load_model: loading model 'x.gguf'\n"+ "E ROCm error: device kernel image is invalid\n"+ "E current device: 0, in function ggml_cuda_kernel_launch"+ )+ assert LlamaCppBackend._kernel_image_invalid(tail)++ def test_detects_the_no_binary_for_gpu_spelling(self):+ # hipErrorNoBinaryForGpu: the same arch mismatch, and the code whose+ # documented cause IS "compiled for a different GPU architecture". A+ # build that raises this one must reach the retry too.+ tail = (+ "ggml-cuda.cu:76: ROCm error\n"+ " no kernel image is available for execution on the device\n"+ " current device: 1"+ )+ assert LlamaCppBackend._kernel_image_invalid(tail)++ def test_ignores_other_crashes(self):+ assert not LlamaCppBackend._kernel_image_invalid("out of memory")+ assert not LlamaCppBackend._kernel_image_invalid("")+ assert not LlamaCppBackend._kernel_image_invalid(None)+++class _FakeProps:+ """hipDeviceProp_t stand-in exposing the canonical arch attribute."""++ _ATTR = "gcnArchName"++ def __init__(self, arch):+ setattr(self, self._ATTR, arch)+++def _fake_torch(+ archs,+ free_mib,+ *,+ props_cls = _FakeProps,+ hip = "7.1.0",+ version_str = "",+):+ torch = types.ModuleType("torch")+ torch.version = types.SimpleNamespace() if hip is None else types.SimpleNamespace(hip = hip)+ torch.__version__ = version_str+ torch.cuda = types.SimpleNamespace(+ is_available = lambda: True,+ device_count = lambda: len(archs),+ mem_get_info = lambda o: (free_mib[o] * 1024 * 1024, 32 * 1024**3),+ get_device_properties = lambda o: props_cls(archs[o]),+ )+ return torch+++def rocm_probe_env(tmp_path, monkeypatch):+ """Force _get_gpu_memory down the torch/ROCm fallback, hermetically.+ The fake binary lives under tmp_path so a test can plant an install+ marker there (or not, for the unknown-coverage case)."""++ def _no_nvidia_smi(*args, **kwargs):+ raise FileNotFoundError("nvidia-smi")++ monkeypatch.setattr(subprocess, "run", _no_nvidia_smi)+ fake_binary = str(tmp_path / "build" / "bin" / "llama-server")+ monkeypatch.setattr(+ LlamaCppBackend, "_find_llama_server_binary", staticmethod(lambda: fake_binary)+ )+ for var in ("HIP_VISIBLE_DEVICES", "ROCR_VISIBLE_DEVICES", "CUDA_VISIBLE_DEVICES"):+ monkeypatch.delenv(var, raising = False)+++class TestGpuArchGate:+ def test_igpu_dropped_when_arch_unsupported(self, tmp_path, monkeypatch, rocm_probe_env):+ # dGPU (gfx1101) + iGPU (gfx1036) whose shared-RAM "free memory"+ # outranks the dGPU's free VRAM -- the #7624 / #7669 shape. Only the+ # dGPU may survive enumeration.+ _binary_with_marker(+ tmp_path, {"mapped_targets": ["gfx1100", "gfx1101", "gfx1102", "gfx1103"]}+ )+ monkeypatch.setitem(+ sys.modules, "torch", _fake_torch(["gfx1101", "gfx1036"], [12049, 12176])+ )+ assert LlamaCppBackend._get_gpu_free_memory(for_llama_server = True) == [(0, 12049)]++ def test_unknown_coverage_keeps_all_devices(self, tmp_path, monkeypatch, rocm_probe_env):+ # No install marker (source build / custom link): behavior unchanged.+ monkeypatch.setitem(+ sys.modules, "torch", _fake_torch(["gfx1101", "gfx1036"], [12049, 12176])+ )+ assert LlamaCppBackend._get_gpu_free_memory(for_llama_server = True) == [+ (0, 12049),+ (1, 12176),+ ]++ def test_unknown_device_arch_fails_open(self, tmp_path, monkeypatch, rocm_probe_env):+ # A device torch can't describe is kept, never silently dropped.+ _binary_with_marker(tmp_path, {"mapped_targets": ["gfx1101"]})+ monkeypatch.setitem(sys.modules, "torch", _fake_torch(["gfx1101", ""], [12049, 12176]))+ assert LlamaCppBackend._get_gpu_free_memory(for_llama_server = True) == [+ (0, 12049),+ (1, 12176),+ ]++ @pytest.mark.parametrize("attr", ["gcn_arch_name", "arch_name", "gfx_arch_name"])+ def test_alternate_arch_attribute_spellings(self, attr, tmp_path, monkeypatch, rocm_probe_env):+ # AMD SDK / Radeon wheels may omit the canonical gcnArchName. Reading+ # only that attribute would leave the arch map empty and fail the gate+ # open, which is exactly the crash this PR exists to prevent.+ props_cls = type("_AltProps", (_FakeProps,), {"_ATTR": attr})+ _binary_with_marker(tmp_path, {"mapped_targets": ["gfx1101"]})+ monkeypatch.setitem(+ sys.modules,+ "torch",+ _fake_torch(["gfx1101", "gfx1036"], [12049, 12176], props_cls = props_cls),+ )+ assert LlamaCppBackend._rocm_arch_by_physical_id() == {0: "gfx1101", 1: "gfx1036"}+ assert LlamaCppBackend._get_gpu_free_memory(for_llama_server = True) == [(0, 12049)]++ def test_amd_sdk_wheel_without_version_hip_is_gated(+ self, tmp_path, monkeypatch, rocm_probe_env+ ):+ # AMD SDK / Radeon ROCm wheels can leave torch.version.hip unset while+ # __version__ still identifies ROCm. A bare version.hip test would skip+ # the gate there; the shared _torch_is_rocm predicate does not.+ _binary_with_marker(tmp_path, {"mapped_targets": ["gfx1101"]})+ monkeypatch.setitem(+ sys.modules,+ "torch",+ _fake_torch(+ ["gfx1101", "gfx1036"], [12049, 12176], hip = None, version_str = "2.6.0+rocm6.4"+ ),+ )+ assert LlamaCppBackend._get_gpu_free_memory(for_llama_server = True) == [(0, 12049)]++ def test_non_rocm_wheel_is_never_gated(self, tmp_path, monkeypatch, rocm_probe_env):+ # A CUDA wheel must not consult a ROCm marker at all.+ _binary_with_marker(tmp_path, {"mapped_targets": ["gfx1101"]})+ monkeypatch.setitem(+ sys.modules,+ "torch",+ _fake_torch(+ ["gfx1101", "gfx1036"], [12049, 12176], hip = None, version_str = "2.6.0+cu124"+ ),+ )+ assert LlamaCppBackend._get_gpu_free_memory(for_llama_server = True) == [+ (0, 12049),+ (1, 12176),+ ]+++class TestTorchCallersStayUnfiltered:+ """The gate answers "what can llama-server run on", not "what GPUs exist".+ _get_gpu_memory also backs the RAG pick, which resolves to sentence-transformers,+ where such a device is usually still fine, so gating it would move embeddings to+ the CPU: a working path broken by the fix."""++ def test_probe_is_unfiltered_by_default(self, tmp_path, monkeypatch, rocm_probe_env):+ _binary_with_marker(tmp_path, {"mapped_targets": ["gfx1101"]})+ monkeypatch.setitem(+ sys.modules, "torch", _fake_torch(["gfx1101", "gfx1036"], [12049, 12176])+ )+ assert LlamaCppBackend._get_gpu_free_memory() == [(0, 12049), (1, 12176)]+ assert LlamaCppBackend._get_gpu_memory() == [(0, 12049, 32768), (1, 12176, 32768)]++ def test_rag_auto_still_picks_sentence_transformers(+ self, tmp_path, monkeypatch, rocm_probe_env+ ):+ # Every visible device is unsupported by the prebuilt; the torch caller+ # must still see a GPU and choose the torch backend.+ from core.rag import embeddings++ _binary_with_marker(tmp_path, {"mapped_targets": ["gfx1101"]})+ monkeypatch.setitem(sys.modules, "torch", _fake_torch(["gfx1036"], [12176]))+ assert embeddings._resolve_auto() == "sentence-transformers"++ def test_embed_llama_server_probe_opts_in(self, tmp_path, monkeypatch, rocm_probe_env):+ # The GGUF embedding backend IS llama-server, so the same unsupported+ # device must not count as an available GPU there.+ import utils.hardware as uh+ from core.rag.embed_llama_server import LlamaServerBackend++ monkeypatch.setattr(uh, "is_apple_silicon", lambda: False)+ _binary_with_marker(tmp_path, {"mapped_targets": ["gfx1101"]})+ monkeypatch.setitem(sys.modules, "torch", _fake_torch(["gfx1036"], [12176]))+ assert LlamaServerBackend._gpu_available() is False+ # Same host, supported arch: still a GPU.+ monkeypatch.setitem(sys.modules, "torch", _fake_torch(["gfx1101"], [12176]))+ assert LlamaServerBackend._gpu_available() is True+++class TestArchGateCoexistsWithUnifiedMemory:+ """Both behaviours share the torch fallback loop and neither may displace+ the other: the APU keeps its host-RAM reserve and its total-0 reporting,+ while the unsupported device is still dropped."""++ def test_apu_reserve_and_arch_gate_together(self, tmp_path, monkeypatch, rocm_probe_env):+ # gfx1151 Strix Halo (unified memory, supported by the bundle),+ # gfx1101 dGPU (supported), gfx1036 (NOT in the bundle).+ _binary_with_marker(tmp_path, {"mapped_targets": ["gfx1101", "gfx1151"]})+ monkeypatch.setitem(+ sys.modules,+ "torch",+ _fake_torch(["gfx1151", "gfx1101", "gfx1036"], [20000, 12049, 12176]),+ )+ monkeypatch.setattr(+ LlamaCppBackend, "_available_system_memory_mib", staticmethod(lambda: 30000)+ )+ assert LlamaCppBackend._get_gpu_memory(for_llama_server = True) == [+ # Shared pool: host reserve held back, total reported 0.+ (0, 20000 - _IGPU_HOST_RESERVE_MIB, 0),+ # Discrete supported card: untouched.+ (1, 12049, 32768),+ # gfx1036 dropped by the arch gate.+ ]++ def test_apu_reserve_survives_unknown_coverage(self, tmp_path, monkeypatch, rocm_probe_env):+ # No marker: the gate fails open, and the APU accounting still applies.+ monkeypatch.setitem(sys.modules, "torch", _fake_torch(["gfx1151"], [20000]))+ monkeypatch.setattr(+ LlamaCppBackend, "_available_system_memory_mib", staticmethod(lambda: 30000)+ )+ assert LlamaCppBackend._get_gpu_memory(for_llama_server = True) == [+ (0, 20000 - _IGPU_HOST_RESERVE_MIB, 0)+ ]+++class TestArchCrashRetrySet:+ """The reactive recovery for markerless / custom-linked builds, where the+ proactive gate cannot know what the binary covers."""++ def test_prefers_never_selected_devices(self):+ assert LlamaCppBackend._arch_crash_retry_gpu_ids([0], [0, 1, 2]) == [1, 2]++ def test_narrows_to_discrete_when_every_gpu_was_selected(self, monkeypatch):+ # The planner took both cards, so there is no untouched device left.+ # Dropping the shared-pool APU still leaves a launchable dGPU (#7624).+ monkeypatch.setattr(+ LlamaCppBackend, "_rocm_unified_memory_gpu_ids", staticmethod(lambda: {0})+ )+ assert LlamaCppBackend._arch_crash_retry_gpu_ids([0, 1], [0, 1]) == [1]++ def test_no_retry_when_nothing_would_change(self, monkeypatch):+ # No unified device among the selection: the respawn would be identical.+ monkeypatch.setattr(+ LlamaCppBackend, "_rocm_unified_memory_gpu_ids", staticmethod(lambda: set())+ )+ assert LlamaCppBackend._arch_crash_retry_gpu_ids([0, 1], [0, 1]) == []++ def test_no_retry_when_narrowing_empties_the_selection(self, monkeypatch):+ monkeypatch.setattr(+ LlamaCppBackend, "_rocm_unified_memory_gpu_ids", staticmethod(lambda: {0, 1})+ )+ assert LlamaCppBackend._arch_crash_retry_gpu_ids([0, 1], [0, 1]) == []++ def test_single_gpu_host_has_no_retry(self, monkeypatch):+ """#7624: the one selected GPU IS the whole host, so the narrowing must be+ skipped outright. The spy counts rather than raises: the branch runs under+ ``except Exception: return []``, which would swallow an AssertionError and+ return the very [] the guard should produce, passing either way."""+ calls = []++ def _spy():+ calls.append(1)+ return set()++ monkeypatch.setattr(LlamaCppBackend, "_rocm_unified_memory_gpu_ids", staticmethod(_spy))+ assert LlamaCppBackend._arch_crash_retry_gpu_ids([0], [0]) == []+ assert calls == [], "single-GPU host must not reach the unified-memory probe"++ def test_empty_selection_is_a_no_op(self):+ assert LlamaCppBackend._arch_crash_retry_gpu_ids([], [0, 1]) == []++ def test_classifier_failure_is_not_fatal(self, monkeypatch):+ def _boom():+ raise RuntimeError("hip enumeration failed")++ monkeypatch.setattr(LlamaCppBackend, "_rocm_unified_memory_gpu_ids", staticmethod(_boom))+ assert LlamaCppBackend._arch_crash_retry_gpu_ids([0, 1], [0, 1]) == []diff --git a/studio/backend/tests/test_gpu_arch_gate_consumers_7624.py b/studio/backend/tests/test_gpu_arch_gate_consumers_7624.pynew file mode 100644index 00000000000..c19a9901280--- /dev/null+++ b/studio/backend/tests/test_gpu_arch_gate_consumers_7624.py@@ -0,0 +1,1049 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Consumer-side pins for the #7624 / #7669 ROCm arch gate.++``test_gpu_arch_gate_7624.py`` pins the gate itself; this file pins the routing+around it. Three load-bearing claims, none obvious from the call sites: the gate is+INERT on a Vulkan build, which is what lets the Vulkan-ordinal preflight and the+route-level checks stay unfiltered; placement opts in for AUTOMATIC selection only,+so an explicit pin still reaches its device and its own crash message; and+``_wait_for_vram_settle`` stays unfiltered, since it measures driver reclaim.++Mock-based throughout: there is no AMD hardware or ROCm CI here.+"""++from __future__ import annotations++import os+import struct+import subprocess+import sys+import types+from pathlib import Path+from unittest.mock import patch++import pytest++_BACKEND_DIR = str(Path(__file__).resolve().parent.parent)+if _BACKEND_DIR not in sys.path:+ sys.path.insert(0, _BACKEND_DIR)++from core.inference.llama_cpp import GgufLoadIntent, LlamaCppBackend # noqa: E402++_REAL_POPEN = subprocess.Popen+++# ── Vulkan inertness ────────────────────────────────────────────────+++def vulkan_probe(monkeypatch):+ """A Vulkan build with one discrete device and one iGPU, and every ROCm+ arch helper booby-trapped: reaching one of them means the gate ran on a+ code path that has no gfx arches to speak of."""++ def _explode(*_args, **_kwargs):+ raise AssertionError("ROCm arch gate consulted on a Vulkan build")++ monkeypatch.setattr(LlamaCppBackend, "_is_vulkan_backend", staticmethod(lambda _b = None: True))+ monkeypatch.setattr(+ LlamaCppBackend, "_find_llama_server_binary", staticmethod(lambda: "/fake/llama-server")+ )+ monkeypatch.setattr(+ LlamaCppBackend,+ "_run_vulkan_probe",+ staticmethod(+ lambda _b = None: [+ {+ "index": 0,+ "free_mib": 12049,+ "is_igpu": False,+ "total_mib": 16384,+ "name": "RX 7800 XT",+ },+ {+ "index": 1,+ "free_mib": 12176,+ "is_igpu": True,+ "total_mib": 65536,+ "name": "Radeon Graphics",+ },+ ]+ ),+ )+ monkeypatch.setattr(LlamaCppBackend, "_installed_llama_gfx_archs", staticmethod(_explode))+ monkeypatch.setattr(LlamaCppBackend, "_rocm_arch_by_physical_id", staticmethod(_explode))+ monkeypatch.setattr(LlamaCppBackend, "_torch_is_rocm", staticmethod(_explode))+++class TestGateIsInertOnVulkanBuilds:+ """The Vulkan branch returns before ``for_llama_server`` is read, so the three+ unfiltered call sites are unaffected by the flag they do not pass. Verified+ rather than assumed, since the case for leaving them unfiltered rests on it."""++ def test_flag_changes_nothing_on_a_vulkan_build(self, vulkan_probe):+ gated = LlamaCppBackend._get_gpu_memory("/fake/llama-server", for_llama_server = True)+ plain = LlamaCppBackend._get_gpu_memory("/fake/llama-server")+ assert gated == plain+ # Real rows, not two empty lists agreeing with each other.+ assert [row[0] for row in plain] == [0, 1]++ def test_free_memory_wrapper_is_inert_too(self, vulkan_probe):+ assert LlamaCppBackend._get_gpu_free_memory(+ "/fake/llama-server", for_llama_server = True+ ) == LlamaCppBackend._get_gpu_free_memory("/fake/llama-server")++ def test_vulkan_ordinal_preflight_sees_every_ordinal(self, vulkan_probe):+ # The preflight's issubset check (#7239) must keep enumerating the iGPU+ # ordinal, or a legitimate explicit pin on it would 400.+ assert {g[0] for g in LlamaCppBackend._get_gpu_memory("/fake/llama-server")} == {0, 1}+++# ── Placement: automatic only ───────────────────────────────────────+++def _write_gguf(path: Path, architecture: str = "llama") -> Path:+ def string(value: str) -> bytes:+ data = value.encode()+ return struct.pack("<Q", len(data)) + data++ metadata = string("general.architecture") + struct.pack("<I", 8) + string(architecture)+ path.write_bytes(struct.pack("<IIQQ", 0x46554747, 3, 0, 1) + metadata)+ return path+++def _backend(+ tmp_path: Path,+ memory,+ *,+ gated_out = frozenset(),+):+ """Placement harness whose GPU probe HONORS ``for_llama_server``. ``gated_out``+ stands in for devices absent from mapped_targets, so the test sees the gate's real+ consequence for placement. Calls are recorded in ``backend._probe_calls``."""+ backend = LlamaCppBackend()+ calls: list[bool] = []+ backend._probe_calls = calls++ def _probe(_binary = None, *, for_llama_server = False):+ calls.append(for_llama_server)+ rows = list(memory)+ if for_llama_server:+ rows = [row for row in rows if row[0] not in gated_out]+ return rows++ backend._get_gpu_memory = _probe+ backend._get_gpu_free_memory = lambda _binary = None, **kw: [+ (index, free) for index, free, _total in _probe(_binary, **kw)+ ]+ backend._read_gguf_metadata = lambda _path: None+ backend._can_estimate_kv = lambda: False+ backend._get_gguf_size_bytes = lambda _path: 1024+ backend._mmproj_vram_bytes = lambda _path: 0+ backend._resolve_launch_mmproj_path = lambda **kwargs: None+ backend._apu_ram_shortfall_message = lambda *args, **kwargs: None+ backend._amd_apu_wants_unified_memory = lambda *args, **kwargs: False+ backend._find_llama_server_binary = lambda include_denied = False: "/fake/llama-server"+ backend._is_vulkan_backend = lambda _binary = None: False+ backend._wait_for_health = lambda timeout: True+ backend._detect_audio_type_strict = lambda: None+ backend._apply_detected_audio = lambda _detected: True+ return backend, _write_gguf(tmp_path / "model.gguf")+++def _launch(backend, gguf, **load_kwargs):+ captured: dict = {}++ def fake_popen(cmd, **kwargs):+ if not cmd or str(cmd[0]) != "/fake/llama-server":+ return _REAL_POPEN(cmd, **kwargs)+ captured["cmd"] = list(cmd)+ captured["env"] = kwargs.get("env") or dict(os.environ)+ return type(+ "Process",+ (),+ {+ "pid": 123,+ "stdout": (),+ "poll": lambda self: None,+ "terminate": lambda self: None,+ "wait": lambda self, timeout = None: 0,+ "kill": lambda self: None,+ },+ )()++ with patch.object(subprocess, "Popen", side_effect = fake_popen):+ assert backend.load_model(+ GgufLoadIntent(gguf_path = str(gguf), model_identifier = "test", **load_kwargs)+ )+ return captured+++class TestPlacementOptsInForAutoOnly:+ """``for_llama_server = not gpu_ids`` at the placement probe."""++ def test_automatic_placement_opts_in(self, tmp_path):+ backend, gguf = _backend(tmp_path, [(0, 12049, 16384), (1, 40000, 65536)])+ _launch(backend, gguf)+ assert backend._probe_calls, "placement never probed the GPUs"+ assert any(backend._probe_calls), "automatic placement did not opt into the arch gate"++ def test_explicit_pin_does_not_opt_in(self, tmp_path):+ backend, gguf = _backend(tmp_path, [(0, 12049, 16384), (1, 40000, 65536)])+ _launch(backend, gguf, gpu_ids = [1])+ assert backend._probe_calls, "placement never probed the GPUs"+ assert not any(backend._probe_calls), "an explicit pin was silently arch-gated"++ def test_explicit_pin_on_an_uncovered_gpu_still_reaches_that_gpu(self, tmp_path):+ # GPU 1 is the device the prebuilt has no kernels for, and the user pinned+ # it anyway. The child must still get it, so llama-server produces its own+ # "device kernel image is invalid" and the user learns which card is wrong,+ # rather than being relocated onto GPU 0 or dropped to CPU behind their back.+ backend, gguf = _backend(+ tmp_path, [(0, 12049, 16384), (1, 40000, 65536)], gated_out = frozenset({1})+ )+ captured = _launch(backend, gguf, gpu_ids = [1])+ env = captured["env"]+ assert env.get("HIP_VISIBLE_DEVICES") == "1" or env.get("CUDA_VISIBLE_DEVICES") == "1", (+ f"explicit pin on the uncovered GPU did not reach the child: "+ f"HIP={env.get('HIP_VISIBLE_DEVICES')!r} CUDA={env.get('CUDA_VISIBLE_DEVICES')!r}"+ )++ def test_automatic_placement_avoids_the_uncovered_gpu(self, tmp_path):+ # The #7624 shape: the uncovered device reports the larger free pool and+ # would win the free-VRAM rank. Automatic placement must land on GPU 0.+ backend, gguf = _backend(+ tmp_path, [(0, 12049, 16384), (1, 40000, 65536)], gated_out = frozenset({1})+ )+ captured = _launch(backend, gguf)+ env = captured["env"]+ pinned = env.get("HIP_VISIBLE_DEVICES") or env.get("CUDA_VISIBLE_DEVICES")+ assert pinned is None or "1" not in pinned.split(+ ","+ ), f"automatic placement selected the uncovered GPU: {pinned!r}"+++# ── Unfiltered by design ────────────────────────────────────────────+++class TestWaitForVramSettleStaysUnfiltered:+ """The settle poll measures the driver reclaiming a dead child's allocations.+ It places nothing, so it must not pay for a marker read and an arch enumeration+ per sample -- and narrowing its device list would change the+ ``len(curr) != len(prev)`` short-circuit it relies on."""++ def test_probe_is_never_gated(self, monkeypatch):+ import time as _time++ seen: list[dict] = []++ def _probe(binary = None, **kwargs):+ seen.append(dict(kwargs))+ return [(0, 12049)]++ monkeypatch.setattr(LlamaCppBackend, "_get_gpu_free_memory", staticmethod(_probe))+ LlamaCppBackend._wait_for_vram_settle(+ max_wait = 0.05, interval = 0.01, since_kill = _time.monotonic()+ )+ assert seen, "the settle poll never probed"+ assert all(+ not call.get("for_llama_server", False) for call in seen+ ), f"the settle poll opted into the arch gate: {seen}"+++class TestRagAutoStaysUnfiltered:+ """``core/rag/embeddings.py::_resolve_auto`` picks between sentence-transformers+ (PyTorch) and llama-server. The PyTorch winner runs on devices the prebuilt knows+ nothing about, so gating this probe would push bulk indexing to the CPU."""++ def test_resolve_auto_never_gates(self, monkeypatch):+ from core.rag import embeddings++ seen: list[dict] = []++ def _probe(binary = None, **kwargs):+ seen.append(dict(kwargs))+ return [(0, 12049)]++ monkeypatch.setattr(LlamaCppBackend, "_get_gpu_free_memory", staticmethod(_probe))+ assert embeddings._resolve_auto() == "sentence-transformers"+ assert seen, "_resolve_auto never probed"+ assert all(+ not call.get("for_llama_server", False) for call in seen+ ), f"_resolve_auto opted into the arch gate: {seen}"+++class TestEmbedLlamaServerOptsIn:+ """The GGUF embedding backend IS a llama-server process, so it is the one+ RAG-side probe that must be gated."""++ def test_gpu_available_opts_in(self, monkeypatch):+ import utils.hardware as uh+ from core.rag.embed_llama_server import LlamaServerBackend++ monkeypatch.setattr(uh, "is_apple_silicon", lambda: False)+ seen: list[dict] = []++ def _probe(binary = None, **kwargs):+ seen.append(dict(kwargs))+ return [(0, 12049)]++ monkeypatch.setattr(LlamaCppBackend, "_get_gpu_free_memory", staticmethod(_probe))+ assert LlamaServerBackend._gpu_available() is True+ assert seen and all(+ call.get("for_llama_server") is True for call in seen+ ), f"the embedding llama-server probe was not gated: {seen}"+++# ── Crash recovery edge cases ───────────────────────────────────────+++def _unified(monkeypatch, ids):+ monkeypatch.setattr(+ LlamaCppBackend, "_rocm_unified_memory_gpu_ids", staticmethod(lambda: set(ids))+ )+++class TestArchCrashRetryEdgeCases:+ """``_arch_crash_retry_gpu_ids`` decides where a "device kernel image is+ invalid" crash respawns. Every answer it gives must be a strict improvement+ on the set that just crashed, or empty."""++ def test_none_inputs(self):+ assert LlamaCppBackend._arch_crash_retry_gpu_ids(None, None) == []+ assert LlamaCppBackend._arch_crash_retry_gpu_ids(None, [0, 1]) == []+ assert LlamaCppBackend._arch_crash_retry_gpu_ids([0], None) == []++ def test_empty_enumeration_with_a_multi_gpu_selection(self, monkeypatch):+ # Nothing enumerated (the probe failed after the crash) but two devices+ # were selected: narrowing is still the honest answer.+ _unified(monkeypatch, {1})+ assert LlamaCppBackend._arch_crash_retry_gpu_ids([0, 1], []) == [0]++ def test_duplicates_collapse(self, monkeypatch):+ _unified(monkeypatch, {0})+ assert LlamaCppBackend._arch_crash_retry_gpu_ids([0, 0, 1, 1], [0, 0, 1, 1]) == [1]+ assert LlamaCppBackend._arch_crash_retry_gpu_ids([0, 0], [0, 0, 1, 1, 2]) == [1, 2]++ def test_selected_ids_absent_from_the_enumeration(self, monkeypatch):+ # A stale selection naming a device the post-crash probe no longer sees.+ # The untouched enumerated device is still the right retry.+ _unified(monkeypatch, set())+ assert LlamaCppBackend._arch_crash_retry_gpu_ids([5], [0, 1]) == [0, 1]+ # ... and when the enumeration is a strict subset of the selection there+ # is no untouched device, so it falls through to the narrowing.+ _unified(monkeypatch, {7})+ assert LlamaCppBackend._arch_crash_retry_gpu_ids([7, 8], [7]) == [8]++ def test_single_gpu_host_never_probes_and_never_retries(self, monkeypatch):+ # A raising spy would be vacuous here: the narrowing branch swallows+ # every exception into []. Count the calls instead, so "took the short+ # circuit" and "took the long way and failed" stay distinguishable.+ calls: list[int] = []++ def _counting():+ calls.append(1)+ return set()++ monkeypatch.setattr(+ LlamaCppBackend, "_rocm_unified_memory_gpu_ids", staticmethod(_counting)+ )+ assert LlamaCppBackend._arch_crash_retry_gpu_ids([0], [0]) == []+ assert LlamaCppBackend._arch_crash_retry_gpu_ids([3], [3]) == []+ assert calls == [], "a single-GPU host enumerated devices it cannot use"++ def test_all_devices_unified(self, monkeypatch):+ _unified(monkeypatch, {0, 1, 2})+ # Every selected device is unified: narrowing empties the set, no retry.+ assert LlamaCppBackend._arch_crash_retry_gpu_ids([0, 1, 2], [0, 1, 2]) == []++ def test_no_device_unified(self, monkeypatch):+ _unified(monkeypatch, set())+ # Narrowing changes nothing, so the respawn would crash identically.+ assert LlamaCppBackend._arch_crash_retry_gpu_ids([0, 1, 2], [0, 1, 2]) == []++ def test_retry_set_never_contains_a_device_that_just_crashed_alone(self, monkeypatch):+ # The narrowing branch may only ever return a strict subset.+ _unified(monkeypatch, {0})+ selected = [0, 1, 2]+ out = LlamaCppBackend._arch_crash_retry_gpu_ids(selected, selected)+ assert out == [1, 2]+ assert set(out) < set(selected)++ @pytest.mark.parametrize(+ "selected,enumerated,unified",+ [+ ([0], [0], set()),+ ([0], [0, 1], set()),+ ([0, 1], [0, 1], {0}),+ ([0, 1], [0, 1], set()),+ ([0, 1], [0, 1], {0, 1}),+ ([0, 1, 2], [0, 1, 2, 3], {0}),+ ([5], [0, 1], {0}),+ ([0, 1], [], {1}),+ ],+ )+ def test_every_answer_differs_from_the_set_that_crashed(+ self, selected, enumerated, unified, monkeypatch+ ):+ """The one guarantee the single retry needs: the respawn is never the+ launch that just died. Either a different device set, or nothing."""+ _unified(monkeypatch, unified)+ out = LlamaCppBackend._arch_crash_retry_gpu_ids(selected, enumerated)+ assert not out or set(out) != set(+ selected+ ), f"retry would respawn the identical selection {sorted(set(selected))}"++ def test_the_decision_is_stateless_and_so_must_not_be_looped(self, monkeypatch):+ """A hazard note, not a bug: ``_arch_crash_retry_gpu_ids`` has no memory of+ what failed, so on a two-GPU host [0] maps to [1] and [1] back to [0]. Safe+ only because the launch path applies it exactly once; a retry loop that did+ not thread the already-tried set through would ping-pong forever."""+ _unified(monkeypatch, set())+ assert LlamaCppBackend._arch_crash_retry_gpu_ids([0], [0, 1]) == [1]+ assert LlamaCppBackend._arch_crash_retry_gpu_ids([1], [0, 1]) == [0]+++class TestKernelImageInvalidDoesNotFalsePositive:+ """The marker gates a device-narrowing respawn, so a false positive would+ silently move an unrelated failure onto a different card."""++ @pytest.mark.parametrize(+ "output",+ [+ # Realistic llama.cpp / ggml output that mentions the words but is+ # not the arch mismatch.+ "ggml_cuda_compute_forward: RMS_NORM failed\nCUDA error: invalid argument",+ "load_model: error loading model: invalid model file magic",+ "llama_model_load: error loading model: check_tensor_dims: tensor "+ "'blk.0.attn_q.weight' has wrong shape",+ "ggml-cuda.cu: kernel launch failed",+ "error: invalid value for --n-gpu-layers",+ "ROCm error: out of memory",+ "warning: the kernel module amdgpu is out of date",+ # Near misses for the two codes added below: neither is the message.+ "load_model: error loading model: invalid model file magic",+ "error: invalid device id 3",+ "srv load_model: the image is invalid",+ "device kernel image is valid",+ "common_init_from_params: failed to load model 'x.gguf'",+ ],+ )+ def test_unrelated_output_does_not_match(self, output):+ assert not LlamaCppBackend._kernel_image_invalid(output)++ @pytest.mark.parametrize(+ "output",+ [+ "ROCm error: device kernel image is invalid",+ "ggml-cuda.cu:76: ROCm error\n device kernel image is invalid\n current device: 1",+ "DEVICE KERNEL IMAGE IS INVALID".lower(),+ # hipErrorNoBinaryForGpu: HIP's other code for the same mismatch, and+ # the one documented as code compiled for a different arch. Neither field+ # log showed it, but another ROCm or ggml build raises it for this pick.+ "ROCm error: no kernel image is available for execution on the device",+ "ggml-cuda.cu:76: ROCm error\n"+ " no kernel image is available for execution on the device\n"+ " current device: 1",+ # The same code raised during backend init rather than at a kernel+ # launch: ggml prints it through a different format string, so the+ # match has to be on the message and not on the "ROCm error:" prefix.+ "ggml_cuda_init: failed to initialize ROCm: "+ "no kernel image is available for execution on the device",+ # cudaErrorNoKernelImageForDevice. Same string, same defect, and the+ # retry is not ROCm-gated, so an NVIDIA host with a build that has+ # no kernels for one of its cards recovers the same way.+ "CUDA error: no kernel image is available for execution on the device",+ # hipErrorInvalidKernelFile / hipErrorInvalidDeviceFunction: clr raises+ # them from the same fat-binary load as the two above and propagates+ # them out of the launch path, so a build that surfaces either would+ # otherwise be left on the misleading GGUF error.+ "ROCm error: invalid kernel file",+ "hipErrorInvalidDeviceFunction: invalid device function",+ "ggml-cuda.cu:76: ROCm error\n invalid device function\n current device: 1",+ # cudaErrorInvalidDeviceFunction, the NVIDIA spelling of the same thing.+ "CUDA error: invalid device function",+ ],+ )+ def test_the_real_crash_matches(self, output):+ assert LlamaCppBackend._kernel_image_invalid(output)++ @pytest.mark.parametrize(+ "output",+ [+ "Device Kernel Image Is Invalid",+ "ROCm error: DEVICE KERNEL IMAGE IS INVALID",+ "No kernel image is available for execution on the device",+ "ROCM ERROR: NO KERNEL IMAGE IS AVAILABLE FOR EXECUTION ON THE DEVICE",+ "ROCm error: Invalid Kernel File",+ "CUDA ERROR: INVALID DEVICE FUNCTION",+ ],+ )+ def test_matching_is_case_insensitive(self, output):+ # hipGetErrorString is lowercase but the layers reprinting it are not+ # consistent, and a missed match costs the whole recovery. Safe because the+ # markers are specific enough that folding case pulls nothing unrelated in.+ assert LlamaCppBackend._kernel_image_invalid(output)++ def test_non_string_input_is_not_a_match(self):+ assert not LlamaCppBackend._kernel_image_invalid(None)+ assert not LlamaCppBackend._kernel_image_invalid("")+++class TestArchCrashRetryFiresAtMostOnce:+ """The recovery is one straight-line ``if`` in the launch path, not a loop.+ Pinned here so a future refactor into a retry loop has to notice."""++ def test_source_has_a_single_archfallback_spawn(self):+ source = Path(LlamaCppBackend.__module__.replace(".", "/"))+ path = Path(__file__).resolve().parent.parent / "core" / "inference" / "llama_cpp.py"+ assert path.exists(), source+ text = path.read_text(encoding = "utf-8")+ assert text.count('label = "-archfallback"') == 1+ assert text.count("_arch_crash_retry_gpu_ids(") == 2 # definition + the one call site++ def test_a_second_pass_over_the_same_state_yields_nothing(self, monkeypatch):+ # After the retry narrows [0, 1] to [1], re-running the decision on the+ # narrowed set is a single-GPU selection and answers [].+ _unified(monkeypatch, {0})+ first = LlamaCppBackend._arch_crash_retry_gpu_ids([0, 1], [0, 1])+ assert first == [1]+ assert LlamaCppBackend._arch_crash_retry_gpu_ids(first, [0, 1]) == [0]+ assert LlamaCppBackend._arch_crash_retry_gpu_ids([0], [0]) == []+++class TestArchRetryDropsTensorSplit:+ """``--tensor-split`` weights are positional over the child's VISIBLE devices, so+ the retry masking one out re-indexes the survivors and the crashed set's shares+ land on the wrong cards. The retry drops the flag."""++ def test_the_two_token_form_goes_with_its_value(self):+ cmd = ["llama-server", "-m", "x.gguf", "--tensor-split", "10,20,30", "-ngl", "-1"]+ assert LlamaCppBackend._without_tensor_split(cmd) == [+ "llama-server",+ "-m",+ "x.gguf",+ "-ngl",+ "-1",+ ]++ def test_the_short_and_equals_forms_go_too(self):+ assert LlamaCppBackend._without_tensor_split(["s", "-ts", "1,2", "-ngl", "-1"]) == [+ "s",+ "-ngl",+ "-1",+ ]+ # An "=" form carries its value in the token, so nothing may be skipped+ # after it -- dropping the next token would eat --ngl's flag.+ assert LlamaCppBackend._without_tensor_split(["s", "--tensor-split=1,2", "-ngl"]) == [+ "s",+ "-ngl",+ ]+ # llama.cpp normalises long-option underscores; _flag_name mirrors it.+ assert LlamaCppBackend._without_tensor_split(["s", "--tensor_split", "1,2"]) == ["s"]++ def test_a_command_without_a_split_reports_nothing_to_do(self):+ cmd = ["llama-server", "-m", "x.gguf", "--split-mode", "tensor", "-ngl", "-1"]+ assert LlamaCppBackend._without_tensor_split(cmd) is None+ # Known limitation, pinned not fixed: the scan is positional, so a VALUE+ # spelled exactly like the flag is removed as if it were one and the+ # two-token form then swallows the argument after it. No Studio-built argv+ # can reach this -- the only free-text values are the model path and the+ # HF-derived --alias, llama.cpp's own value tokens being numbers or enum+ # words -- so teaching the scanner every flag's arity is not worth it. If a+ # caller-supplied value can ever be "-ts" or "--split-mode", it breaks here.+ assert LlamaCppBackend._without_tensor_split(["s", "--alias", "-ts"]) == ["s", "--alias"]++ def test_only_the_split_is_removed(self):+ cmd = [+ "llama-server",+ "-m",+ "x.gguf",+ "--split-mode",+ "tensor",+ "--tensor-split",+ "10,20,30",+ "--flash-attn",+ "on",+ "-ngl",+ "-1",+ ]+ out = LlamaCppBackend._without_tensor_split(cmd)+ assert "--tensor-split" not in out and "10,20,30" not in out+ assert out == [+ "llama-server",+ "-m",+ "x.gguf",+ "--split-mode",+ "tensor",+ "--flash-attn",+ "on",+ "-ngl",+ "-1",+ ]++ def test_the_retry_call_site_drops_it_before_respawning(self):+ # Source-level, like test_source_has_a_single_archfallback_spawn: the+ # respawn is one straight-line block with no test seam, so pin that the+ # drop happens between narrowing the device set and the respawn.+ path = Path(__file__).resolve().parent.parent / "core" / "inference" / "llama_cpp.py"+ text = path.read_text(encoding = "utf-8")+ # Two call sites: the arch-crash retry, and the manual-split launch the+ # gate narrows. Both mask devices out from under a positional ratio.+ assert text.count("self._without_tensor_split(") == 2+ block = text.split("_arch_crash_retry_gpu_ids(\n")[-1].split('label = "-archfallback"')[0]+ assert "_without_tensor_split(cmd)" in block+ assert "self._tensor_split = None" in block # /status must not report a dropped split+++class TestArchRetryRestoresTheMemoryPolicy:+ """The --fit retry appends a page-lock to its OWN argv and records it, but the+ arch-crash respawn starts from `cmd`, which never carried it, so without a restore+ the backend reports page-locking on an unlocked child."""++ @staticmethod+ def _source():+ path = Path(__file__).resolve().parent.parent / "core" / "inference" / "llama_cpp.py"+ return path.read_text(encoding = "utf-8")++ def test_the_launch_snapshots_what_cmd_means(self):+ text = self._source()+ # Snapshotted at the launch, not re-derived at the retry: re-probing+ # residency for the SURVIVORS would mark an APU survivor mlock-applicable+ # against a lock-free argv, turning every later duplicate load into a reload.+ assert "_mem_policy_for_cmd = (" in text+ _snap = [+ _line.strip().rstrip(",")+ for _line in text.split("_mem_policy_for_cmd = (")[1].split(")")[0].splitlines()+ if _line.strip()+ ]+ assert _snap == [+ "_mem_host_resident",+ "self._memory_state",+ "self._memory_policy_active",+ "self._memory_mlock_applicable",+ ]++ def test_the_retry_call_site_restores_it_before_respawning(self):+ text = self._source()+ block = text.split("_arch_crash_retry_gpu_ids(\n")[-1].split('label = "-archfallback"')[0]+ assert "= _mem_policy_for_cmd" in block+ _restored = [+ _line.strip().rstrip(",")+ for _line in block.split(") = _mem_policy_for_cmd")[0].split("(")[-1].splitlines()+ if _line.strip()+ ]+ # Exact names, in the snapshot's order: a tuple unpack cannot report a+ # mismatch, so a renamed or reordered target restores the wrong field.+ # _mem_host_resident is included, or the respawn's own --fit retry reads the+ # crashed launch's re-armed lock as held and skips re-arming.+ assert _restored == [+ "_mem_host_resident",+ "self._memory_state",+ "self._memory_policy_active",+ "self._memory_mlock_applicable",+ ]+++class TestEmbedLlamaServerPinsTheGatedGpus:+ """Knowing a supported GPU EXISTS is not the same as launching on it: the child+ enumerates every ROCm agent, and that enumeration is what dies, so a mixed host+ passes the gate and still crashes unless the survivors reach the launch env."""++ @staticmethod+ def _probes(+ monkeypatch,+ *,+ gated,+ everything,+ archs = frozenset({"gfx1030"}),+ ):+ """Stub a ROCm host, the gate marker, and both probes. Returns the+ per-call kwargs seen, so a test can COUNT calls -- raising inside a spy+ here would be swallowed by the caller's ``except Exception``."""+ seen: list[dict] = []++ def _probe(binary = None, *, for_llama_server = False):+ seen.append({"binary": binary, "for_llama_server": for_llama_server})+ rows = gated if for_llama_server else everything+ return [(idx, free, 0) for idx, free in rows]++ monkeypatch.setattr(LlamaCppBackend, "_host_torch_is_rocm", staticmethod(lambda: True))+ monkeypatch.setattr(+ LlamaCppBackend, "_installed_llama_gfx_archs", staticmethod(lambda _b = None: archs)+ )+ monkeypatch.setattr(LlamaCppBackend, "_get_gpu_memory", staticmethod(_probe))+ return seen++ def test_a_narrowing_gate_yields_the_surviving_ids(self, monkeypatch):+ self._probes(monkeypatch, gated = [(1, 24000)], everything = [(0, 60000), (1, 24000)])+ from core.rag.embed_llama_server import LlamaServerBackend+ assert LlamaServerBackend._arch_gated_gpu_ids("/fake/llama-server") == [1]++ def test_full_coverage_needs_no_mask(self, monkeypatch):+ self._probes(+ monkeypatch, gated = [(0, 60000), (1, 24000)], everything = [(0, 60000), (1, 24000)]+ )+ from core.rag.embed_llama_server import LlamaServerBackend+ assert LlamaServerBackend._arch_gated_gpu_ids("/fake/llama-server") == []++ def test_unknown_coverage_fails_open_without_probing(self, monkeypatch):+ # NVIDIA, CPU-only, Vulkan and macOS have no mapped_targets marker. The+ # marker check comes first, so neither probe may run at all.+ seen = self._probes(+ monkeypatch, gated = [(1, 24000)], everything = [(0, 1), (1, 24000)], archs = None+ )+ from core.rag.embed_llama_server import LlamaServerBackend++ assert LlamaServerBackend._arch_gated_gpu_ids("/fake/llama-server") == []+ assert seen == [], f"the GPU probe ran despite unknown arch coverage: {seen}"++ def test_a_non_rocm_host_never_probes(self, monkeypatch):+ seen = self._probes(monkeypatch, gated = [(1, 24000)], everything = [(0, 1), (1, 24000)])+ monkeypatch.setattr(LlamaCppBackend, "_host_torch_is_rocm", staticmethod(lambda: False))+ from core.rag.embed_llama_server import LlamaServerBackend++ assert LlamaServerBackend._arch_gated_gpu_ids("/fake/llama-server") == []+ assert seen == [], f"a non-ROCm host paid for the gate probes: {seen}"++ def test_a_probe_failure_never_blocks_the_spawn(self, monkeypatch):+ monkeypatch.setattr(LlamaCppBackend, "_host_torch_is_rocm", staticmethod(lambda: True))+ monkeypatch.setattr(+ LlamaCppBackend,+ "_installed_llama_gfx_archs",+ staticmethod(lambda _b = None: (_ for _ in ()).throw(RuntimeError("marker"))),+ )+ from core.rag.embed_llama_server import LlamaServerBackend++ assert LlamaServerBackend._arch_gated_gpu_ids("/fake/llama-server") == []++ @staticmethod+ def _spy_visibility(monkeypatch):+ calls: list[tuple] = []+ monkeypatch.setattr(+ LlamaCppBackend,+ "_emit_child_gpu_visibility",+ staticmethod(lambda env, pinned, **kw: calls.append((pinned, kw))),+ )+ return calls++ def test_the_launch_env_masks_the_child_to_them(self, monkeypatch):+ self._probes(monkeypatch, gated = [(1, 24000)], everything = [(0, 60000), (1, 24000)])+ calls = self._spy_visibility(monkeypatch)+ from core.rag.embed_llama_server import LlamaServerBackend++ env = LlamaServerBackend()._build_env("/fake/llama-server", use_gpu = True)+ # prefer_rocr: a HIP-only mask still lets HSA enumerate the unsupported+ # agent, which is the segfault the pin exists to avoid.+ assert calls == [("1", {"prefer_rocr": True})], calls+ assert env.get("CUDA_VISIBLE_DEVICES") != "" # the CPU sentinel, not this path++ def test_an_ungated_host_leaves_the_env_alone(self, monkeypatch):+ self._probes(+ monkeypatch, gated = [(0, 60000), (1, 24000)], everything = [(0, 60000), (1, 24000)]+ )+ calls = self._spy_visibility(monkeypatch)+ from core.rag.embed_llama_server import LlamaServerBackend++ LlamaServerBackend()._build_env("/fake/llama-server", use_gpu = True)+ assert calls == [], f"an unnarrowed host was masked anyway: {calls}"++ def test_a_uuid_mask_leaves_the_inherited_mask_in_place(self, monkeypatch):+ """A ROCr mask may name UUIDs rather than indices+ (ROCR_VISIBLE_DEVICES="0,GPU-DEADBEEF..."). The gate's ids are then torch+ ordinals with no physical mapping, and pinning them would replace the mask+ with numbers ROCr resolves against the whole host, exposing cards the parent+ hid -- the dropped one included."""+ self._probes(monkeypatch, gated = [(1, 24000)], everything = [(0, 60000), (1, 24000)])+ calls = self._spy_visibility(monkeypatch)+ # torch must be importable, not just _torch_is_rocm patched:+ # _active_gpu_visibility_mask reads the ROCr mask only inside its `import+ # torch` try, so without torch it answers from CUDA_VISIBLE_DEVICES and an+ # unmappable ROCr mask reads back as "no mask" -- the wrong branch, failing+ # on any runner whose dependency set omits torch.+ monkeypatch.setitem(sys.modules, "torch", types.SimpleNamespace())+ monkeypatch.setattr(LlamaCppBackend, "_torch_is_rocm", staticmethod(lambda _t: True))+ monkeypatch.setattr(sys, "platform", "linux")+ monkeypatch.delenv("CUDA_VISIBLE_DEVICES", raising = False)+ monkeypatch.delenv("HIP_VISIBLE_DEVICES", raising = False)+ monkeypatch.setenv("ROCR_VISIBLE_DEVICES", "GPU-DEADBEEFDEADBEEF")+ from core.rag.embed_llama_server import LlamaServerBackend++ env = LlamaServerBackend()._build_env("/fake/llama-server", use_gpu = True)+ assert calls == [], f"an unmappable mask was rewritten with ordinals: {calls}"+ assert env["ROCR_VISIBLE_DEVICES"] == "GPU-DEADBEEFDEADBEEF"++ def test_the_cpu_path_hides_devices_at_both_layers(self, monkeypatch):+ """CPU has to mean CPU on ROCm too. HIP consults CUDA_VISIBLE_DEVICES only+ when HIP_VISIBLE_DEVICES is unset, so a blank CUDA mask alone leaves an+ inherited HIP pin in charge and the child keeps a device, and the VRAM its+ context costs, on a load that chose the CPU."""+ self._probes(monkeypatch, gated = [(1, 24000)], everything = [(0, 60000), (1, 24000)])+ calls = self._spy_visibility(monkeypatch)+ monkeypatch.setenv("HIP_VISIBLE_DEVICES", "0")+ monkeypatch.setenv("ROCR_VISIBLE_DEVICES", "0")+ from core.rag.embed_llama_server import LlamaServerBackend++ env = LlamaServerBackend()._build_env("/fake/llama-server", use_gpu = False)+ assert calls == [] # no pin: the gate has nothing to narrow on a CPU load+ assert env["CUDA_VISIBLE_DEVICES"] == ""+ assert env["HIP_VISIBLE_DEVICES"] == "-1"+ # ROCR hides agents BELOW HIP, so clearing it would expose more of them+ # to the enumeration that dies on an uncovered arch. Left as inherited.+ assert env["ROCR_VISIBLE_DEVICES"] == "0"+++class TestTheGateNeverRewritesAnUnmappableMask:+ """ROCr and CUDA accept UUID/MIG tokens, which resolve to no physical ids, so the+ probe falls back to torch ordinals. Fine for RANKING, unusable as a PIN since the+ runtime resolves them against the whole host, so the survivor pin fails open."""++ @staticmethod+ def _rocm_host(monkeypatch, *, gated, everything):+ seen: list[bool] = []++ def _probe(binary = None, *, for_llama_server = False):+ seen.append(for_llama_server)+ rows = gated if for_llama_server else everything+ return [(idx, free, 0) for idx, free in rows]++ monkeypatch.setattr(LlamaCppBackend, "_host_torch_is_rocm", staticmethod(lambda: True))+ monkeypatch.setattr(+ LlamaCppBackend,+ "_installed_llama_gfx_archs",+ staticmethod(lambda _b = None: frozenset({"gfx1030"})),+ )+ monkeypatch.setattr(LlamaCppBackend, "_get_gpu_memory", staticmethod(_probe))+ for _var in ("HIP_VISIBLE_DEVICES", "ROCR_VISIBLE_DEVICES", "CUDA_VISIBLE_DEVICES"):+ monkeypatch.delenv(_var, raising = False)+ return seen++ def test_an_unmappable_mask_stops_the_pin_before_either_probe(self, monkeypatch):+ seen = self._rocm_host(monkeypatch, gated = [(1, 24000)], everything = [(0, 60000), (1, 24000)])+ monkeypatch.setenv("CUDA_VISIBLE_DEVICES", "GPU-deadbeefdeadbeef")++ assert LlamaCppBackend._arch_gate_survivors("/fake/llama-server") == []+ assert seen == [], f"the host paid for the probes it cannot use: {seen}"++ def test_an_index_mask_still_narrows(self, monkeypatch):+ # The fail-open must key on "set but unparseable", not on "unset": an+ # ordinary numeric mask still maps back, so the gate keeps working.+ self._rocm_host(monkeypatch, gated = [(1, 24000)], everything = [(0, 60000), (1, 24000)])+ monkeypatch.setenv("CUDA_VISIBLE_DEVICES", "0,1")++ assert LlamaCppBackend._arch_gate_survivors("/fake/llama-server") == [1]++ def test_no_mask_at_all_still_narrows(self, monkeypatch):+ self._rocm_host(monkeypatch, gated = [(1, 24000)], everything = [(0, 60000), (1, 24000)])++ assert LlamaCppBackend._arch_gate_survivors("/fake/llama-server") == [1]++ @pytest.mark.parametrize(+ "mask, unmappable",+ [+ (None, False), # no mask: nothing inherited to lose+ ("", False), # empty mask: resolves to "no devices", not unknown+ ("0,1", False),+ (" 2 ", False),+ ("GPU-DEADBEEFDEADBEEF", True),+ ("0,GPU-DEADBEEFDEADBEEF", True), # the mixed form ROCm documents+ ("MIG-GPU-4a2b/1/0", True),+ ],+ )+ def test_which_masks_count_as_unmappable(self, monkeypatch, mask, unmappable):+ monkeypatch.delenv("HIP_VISIBLE_DEVICES", raising = False)+ monkeypatch.delenv("ROCR_VISIBLE_DEVICES", raising = False)+ if mask is None:+ monkeypatch.delenv("CUDA_VISIBLE_DEVICES", raising = False)+ else:+ monkeypatch.setenv("CUDA_VISIBLE_DEVICES", mask)++ assert LlamaCppBackend._visibility_mask_is_unmappable() is unmappable+++class TestCpuSentinelDropsAnInheritedDevicePick:+ """LLAMA_ARG_DEVICE / LLAMA_ARG_MAIN_GPU are the env spelling of --device /+ --main-gpu, which neither CPU launch passes. Masking every device away while+ leaving an inherited pick in place is the one combination llama.cpp cannot serve:+ it rejects a device that no longer enumerates and exits."""++ def test_the_cpu_sentinel_clears_the_pick(self):+ env = {"LLAMA_ARG_DEVICE": "HIP0", "LLAMA_ARG_MAIN_GPU": "1", "PATH": "/usr/bin"}+ LlamaCppBackend._emit_child_gpu_visibility(env, "-1")+ assert "LLAMA_ARG_DEVICE" not in env+ assert "LLAMA_ARG_MAIN_GPU" not in env+ assert env["CUDA_VISIBLE_DEVICES"] == "-1"+ assert env["PATH"] == "/usr/bin" # nothing else touched++ @pytest.mark.parametrize("pinned", ["0", "1,2", ""])+ def test_a_real_pin_keeps_it(self, pinned):+ """Only the CPU sentinel clears the pick. With devices visible the+ inherited selection is still the user's, and it still resolves."""+ env = {"LLAMA_ARG_DEVICE": "HIP0"}+ LlamaCppBackend._emit_child_gpu_visibility(env, pinned)+ assert env["LLAMA_ARG_DEVICE"] == "HIP0"++ def test_the_embedding_cpu_launch_clears_it_too(self, tmp_path, monkeypatch):+ from core.rag.embed_llama_server import LlamaServerBackend++ monkeypatch.setenv("LLAMA_ARG_DEVICE", "HIP0")+ monkeypatch.setenv("LLAMA_ARG_MAIN_GPU", "0")+ backend = LlamaServerBackend.__new__(LlamaServerBackend)+ env = backend._build_env(str(tmp_path / "llama-server"), use_gpu = False)+ assert "LLAMA_ARG_DEVICE" not in env+ assert "LLAMA_ARG_MAIN_GPU" not in env+ assert env["CUDA_VISIBLE_DEVICES"] == ""+ assert env["HIP_VISIBLE_DEVICES"] == "-1"++ def test_the_embedding_gpu_launch_keeps_it(self, tmp_path, monkeypatch):+ from core.rag.embed_llama_server import LlamaServerBackend++ monkeypatch.setenv("LLAMA_ARG_DEVICE", "HIP0")+ monkeypatch.setattr(+ LlamaCppBackend, "_arch_gate_survivors", staticmethod(lambda _b = None: [])+ )+ backend = LlamaServerBackend.__new__(LlamaServerBackend)+ env = backend._build_env(str(tmp_path / "llama-server"), use_gpu = True)+ assert env["LLAMA_ARG_DEVICE"] == "HIP0"+++class TestArchForcedCpuHoldsNoVram:+ """An arch-gated launch is a zero-VRAM launch arriving through an AUTOMATIC+ request, exactly what routes/inference.py:8206 describes. Without it in+ holds_no_vram the CPU-only server keeps the CHAT claim and blocks a pipeline."""++ def _backend(self):+ backend = LlamaCppBackend()+ backend._gpu_memory_mode = "auto"+ backend._gpu_layers = -1+ backend._gpu_offload_active = False+ return backend++ def test_an_automatic_arch_gated_launch_holds_no_vram(self):+ backend = self._backend()+ assert backend.holds_no_vram is False, "precondition: auto mode alone is not zero-VRAM"+ backend._arch_gate_forced_cpu = True+ assert backend.holds_no_vram is True++ def test_the_manual_zero_offload_rule_is_unchanged(self):+ backend = LlamaCppBackend()+ backend._gpu_memory_mode = "manual"+ backend._gpu_layers = 0+ backend._gpu_offload_active = False+ assert backend.holds_no_vram is True+ backend._gpu_offload_active = True+ assert backend.holds_no_vram is False+ backend._gpu_offload_active = None+ assert backend.holds_no_vram is False++ def test_an_ordinary_gpu_load_still_holds_vram(self):+ backend = self._backend()+ backend._gpu_offload_active = True+ assert backend.holds_no_vram is False+++# ── The gated split still dedupes an identical repeat load ─────────────────+++class _StubProcess:+ """``is_loaded`` only asks "is not None"; nothing here is ever spawned."""++ def terminate(self):+ pass++ def wait(self, timeout = None):+ return 0++ def kill(self):+ pass++ def poll(self):+ return 0+++_GATED_REQUEST = dict(+ model_identifier = "owner/repo",+ hf_variant = "Q4_K_M",+ n_ctx = 8192,+ gpu_memory_mode = "manual",+ gpu_layers = 99,+ tensor_split = (0.5, 0.5),+)+++def _post_gate_backend(dropped, *, live_split = None):+ """Live state after a manual-split launch the arch gate normalized: the ratio+ left the argv (``_tensor_split`` is None), and the drop was recorded."""+ backend = LlamaCppBackend()+ backend._process = _StubProcess()+ backend._healthy = True+ backend._model_identifier = "owner/repo"+ backend._hf_variant = "Q4_K_M"+ backend._requested_n_ctx = 8192+ backend._requested_n_parallel = 1+ backend._requested_spec_mode = "auto"+ backend._gpu_memory_mode = "manual"+ backend._gpu_layers = 99+ backend._tensor_split = live_split+ backend._arch_gate_dropped_tensor_split = dropped+ return backend+++class TestGatedSplitStillDeduplicates:+ """The gate drops a ratio the UI re-sends on every Apply, so without the recorded+ drop each identical request reads as new and reloads a multi-GB model, forever."""++ def test_identical_repeat_request_matches(self):+ backend = _post_gate_backend((0.5, 0.5))+ assert backend.adopt_load_intent_if_matched(GgufLoadIntent(**_GATED_REQUEST)) is True++ def test_a_different_ratio_still_reloads(self):+ """The excuse is for the ratio that was dropped, not for any ratio."""+ backend = _post_gate_backend((0.5, 0.5))+ changed = dict(_GATED_REQUEST, tensor_split = (0.9, 0.1))+ assert backend.adopt_load_intent_if_matched(GgufLoadIntent(**changed)) is False++ def test_a_launch_that_dropped_nothing_records_nothing(self):+ """No recorded drop means no excuse: a live server with no split must+ still reload for a request that asks for one."""+ backend = _post_gate_backend(None)+ assert backend.adopt_load_intent_if_matched(GgufLoadIntent(**_GATED_REQUEST)) is False++ def test_no_drop_never_excuses_a_live_split(self):+ """Both sides None must not read as "the gate dropped this": a server+ RUNNING a ratio has to reload for a request that asks for none."""+ backend = _post_gate_backend(None, live_split = [0.5, 0.5])+ no_split = dict(_GATED_REQUEST, tensor_split = None)+ assert backend.adopt_load_intent_if_matched(GgufLoadIntent(**no_split)) is False+++class TestGatedTensorModeStillDeduplicates:+ """Same rule for the split MODE: without the record an identical Apply reloads the+ same normalized model."""++ def _backend(self, dropped_mode):+ backend = _post_gate_backend((0.5, 0.5))+ backend._tensor_parallel = False # normalized away at launch+ backend._arch_gate_dropped_tensor_parallel = dropped_mode+ return backend++ def test_identical_repeat_request_matches(self):+ request = dict(_GATED_REQUEST, tensor_parallel = True)+ backend = self._backend(True)+ assert backend.adopt_load_intent_if_matched(GgufLoadIntent(**request)) is True++ def test_a_launch_that_dropped_nothing_still_reloads(self):+ """No recorded drop means no excuse: a layer server has to reload for a+ request that genuinely asks for tensor parallelism."""+ request = dict(_GATED_REQUEST, tensor_parallel = True)+ backend = self._backend(False)+ assert backend.adopt_load_intent_if_matched(GgufLoadIntent(**request)) is False++ def test_the_excuse_never_runs_the_other_way(self):+ """One direction only. A server RUNNING tensor parallelism must still reload+ for a request that asks for none, whatever an earlier launch recorded."""+ backend = self._backend(True)+ backend._tensor_parallel = True+ request = dict(_GATED_REQUEST, tensor_parallel = False)+ assert backend.adopt_load_intent_if_matched(GgufLoadIntent(**request)) is Falsediff --git a/studio/backend/tests/test_gpu_arch_gate_os_matrix_7624.py b/studio/backend/tests/test_gpu_arch_gate_os_matrix_7624.pynew file mode 100644index 00000000000..cacdcbf1a9a--- /dev/null+++ b/studio/backend/tests/test_gpu_arch_gate_os_matrix_7624.py@@ -0,0 +1,2493 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""OS x GPU-vendor matrix for the #7624 ROCm arch gate in ``_get_gpu_memory``.++The gate drops a device whose gfx arch is missing from the prebuilt's+``mapped_targets``, and runs on exactly one shape of host (ROCm torch build,+``for_llama_server = True``). Every other cell asserts it is *inert*, which+matching output alone cannot show (a gate that ran and kept everything looks+identical), so the marker reader is spied and asserted un-called.++Matrix: [Windows, Linux, WSL, macOS] x [NVIDIA, AMD, CPU-only]. macOS has no ROCm,+so its "AMD" cell is the two real Apple shapes (Apple Silicon MPS, Intel Mac+Radeon), neither enumerating a ``torch.cuda`` device. WSL is its own cell: ROCm+reports through the same torch path yet ``sys.platform`` is "linux", so the+Windows-only free-VRAM cap (#8403) must NOT engage.++No AMD GPU or ROCm runtime exists here, so every AMD result is mock-based: torch+and its arch attributes, ``sys.platform`` / ``platform.system``,+``utils.hardware.IS_ROCM``, the marker and the HIP/ROCR/CUDA masks are faked in the+shapes #7072 / #7624 / #8403 document (AMD SDK wheels leaving ``torch.version.hip``+unset; the ``gcn_arch_name`` / ``arch_name`` / ``gfx_arch_name`` spellings;+``gfx103X`` omitting the gfx1033/1035/1036 iGPUs; Windows over-reporting free VRAM).+"""++from __future__ import annotations++import json+import os+import struct+import subprocess+import sys+import types+from pathlib import Path++import pytest++# Imported eagerly so a fake torch can never be in place when the real module+# graph is first loaded.+from core.inference import llama_cpp+from core.inference.llama_cpp import (+ _IGPU_HOST_RESERVE_MIB,+ GgufLoadIntent,+ LlamaCppBackend,+)+from utils.hardware import hardware as hw++MiB = 1024 * 1024+_TOTAL_BYTES = 32 * 1024**3++# Concrete tokens the published ROCm manifest records for these bundles. gfx103X+# omits the gfx1033/1035/1036 iGPUs, which is the whole of #7624: they enumerate,+# outrank the dGPU on "free memory", and have no kernels in the binary.+GFX103X = ["gfx1030", "gfx1031", "gfx1032", "gfx1034"]+GFX110X = ["gfx1100", "gfx1101", "gfx1102", "gfx1103"]+GFX120X = ["gfx1200", "gfx1201"]++# platform.system() / sys.platform pair per simulated host.+_OS_CELLS = {+ "windows": ("win32", "Windows"),+ "linux": ("linux", "Linux"),+ "wsl": ("linux", "Linux"),+ "macos": ("darwin", "Darwin"),+}+OS_KEYS = list(_OS_CELLS)+++def _device(+ arch = "",+ *,+ free_mib = 12000,+ total_bytes = _TOTAL_BYTES,+ name = "AMD Radeon RX 6800",+ is_integrated = 0,+ arch_attr = "gcnArchName",+ describe_error = None,+):+ """One fake enumerated device. ``describe_error`` makes+ ``get_device_properties`` raise for it (a card torch cannot describe)."""+ return {+ "arch": arch,+ "free_mib": free_mib,+ "total_bytes": total_bytes,+ "name": name,+ "is_integrated": is_integrated,+ "arch_attr": arch_attr,+ "describe_error": describe_error,+ }+++class _Props:+ """hipDeviceProp_t / cudaDeviceProp stand-in. Only the arch attribute the+ device asks for is set, so the AMD SDK wheels that populate none of the+ canonical spellings can be reproduced."""++ def __init__(self, spec):+ self.name = spec["name"]+ self.total_memory = spec["total_bytes"]+ self.is_integrated = spec["is_integrated"]+ if spec["arch"]:+ setattr(self, spec["arch_attr"], spec["arch"])+++def _fake_torch(+ devices,+ *,+ vendor = "amd",+ cuda_available = None,+ reserved_bytes = 0,+):+ """A fake ``torch``.++ vendor:+ "amd" -- ROCm wheel (``version.hip`` set).+ "amd_sdk" -- AMD SDK / Radeon wheel: ``version.hip`` unset, "rocm" only+ in ``__version__`` (the shape ``_torch_is_rocm`` exists for).+ "nvidia" -- CUDA wheel.+ "cpu" -- CPU-only wheel.+ "mps" -- Apple Silicon: a Metal backend, no ``torch.cuda`` devices.+ """+ devices = list(devices)+ torch = types.ModuleType("torch")+ if vendor == "amd":+ torch.version = types.SimpleNamespace(hip = "7.1.0", cuda = None)+ torch.__version__ = "2.9.0+rocm7.1"+ elif vendor == "amd_sdk":+ torch.version = types.SimpleNamespace()+ torch.__version__ = "2.6.0+rocm6.4"+ elif vendor == "nvidia":+ torch.version = types.SimpleNamespace(hip = None, cuda = "12.4")+ torch.__version__ = "2.6.0+cu124"+ else:+ torch.version = types.SimpleNamespace(hip = None, cuda = None)+ torch.__version__ = "2.6.0+cpu"+ if vendor == "mps":+ torch.backends = types.SimpleNamespace(mps = types.SimpleNamespace(is_available = lambda: True))++ available = bool(devices) if cuda_available is None else cuda_available++ def _get_device_properties(ordinal):+ spec = devices[ordinal]+ if spec["describe_error"] is not None:+ raise spec["describe_error"]+ return _Props(spec)++ torch.cuda = types.SimpleNamespace(+ is_available = lambda: available,+ device_count = lambda: len(devices),+ mem_get_info = lambda o: (devices[o]["free_mib"] * MiB, devices[o]["total_bytes"]),+ memory_reserved = lambda o = None: reserved_bytes,+ get_device_properties = _get_device_properties,+ )+ return torch+++def _binary_with_marker(tmp_path, payload):+ """Lay out ``<root>/UNSLOTH_PREBUILT_INFO.json`` with the binary path below+ it, matching the managed install layout the marker walk-up covers."""+ (tmp_path / "UNSLOTH_PREBUILT_INFO.json").write_text(json.dumps(payload), encoding = "utf-8")+ return str(tmp_path / "build" / "bin" / "llama-server")+++def _apply_os(+ monkeypatch,+ os_key,+ *,+ is_rocm = False,+):+ """Pin the simulated host OS. ``IS_ROCM`` is the backend's own detection+ flag and gates the Windows free-VRAM cap, so it travels with the vendor."""+ platform_name, system_name = _OS_CELLS[os_key]+ monkeypatch.setattr(llama_cpp.sys, "platform", platform_name)+ monkeypatch.setattr(hw.sys, "platform", platform_name)+ monkeypatch.setattr(hw.platform, "system", lambda: system_name)+ monkeypatch.setattr(hw, "IS_ROCM", is_rocm)+ if os_key == "wsl":+ # The WSL prebuilts load the system ROCm libs before the bundled HIP.+ # Nothing in the probe branches on it; pinned so the cell is a real WSL+ # host rather than a relabelled Linux one.+ monkeypatch.setattr(llama_cpp, "_wsl_system_rocm_lib_dirs", lambda: ["/opt/rocm/lib"])++[email protected](autouse = True)+def _clear_marker_cache():+ """read_install_marker memoizes per binary path with no invalidation, so a+ stale entry from another test would answer for this one."""+ import utils.llama_cpp_freshness as freshness++ freshness._marker_cache.clear()+ yield+ freshness._marker_cache.clear()+++def marker_spy(monkeypatch):+ """Records every install-marker read. The inertness claim for non-ROCm+ hosts is "the gate never ran", which only this can show."""+ import utils.llama_cpp_freshness as freshness++ real = freshness.read_install_marker+ calls: list = []++ def _spy(binary_path):+ calls.append(binary_path)+ return real(binary_path)++ monkeypatch.setattr(freshness, "read_install_marker", _spy)+ return calls+++def arch_map_spy(monkeypatch):+ """Records every per-device arch enumeration (the gate's second input)."""+ real = LlamaCppBackend._rocm_arch_by_physical_id+ calls: list = []++ def _spy():+ calls.append(True)+ return real()++ monkeypatch.setattr(LlamaCppBackend, "_rocm_arch_by_physical_id", staticmethod(_spy))+ return calls+++def probe_env(tmp_path, monkeypatch):+ """Force ``_get_gpu_memory`` down the torch fallback, hermetically: no+ nvidia-smi, a binary under tmp_path so a marker can be planted beside it,+ and no inherited visibility mask."""++ def _no_nvidia_smi(*args, **kwargs):+ raise FileNotFoundError("nvidia-smi")++ monkeypatch.setattr(subprocess, "run", _no_nvidia_smi)+ fake_binary = str(tmp_path / "build" / "bin" / "llama-server")+ monkeypatch.setattr(+ LlamaCppBackend, "_find_llama_server_binary", staticmethod(lambda: fake_binary)+ )+ for var in ("HIP_VISIBLE_DEVICES", "ROCR_VISIBLE_DEVICES", "CUDA_VISIBLE_DEVICES"):+ monkeypatch.delenv(var, raising = False)+ return fake_binary+++def _install_cell(monkeypatch, tmp_path, os_key, vendor):+ """Set up one matrix cell and return the expected ``_get_gpu_free_memory``+ result. Every cell plants a marker covering NOTHING its devices report, so a+ gate that runs where it should not shows up as a dropped device."""+ if vendor == "nvidia":+ _apply_os(monkeypatch, os_key, is_rocm = False)+ _binary_with_marker(tmp_path, {"mapped_targets": GFX110X})+ if os_key == "macos":+ # No CUDA on any Mac torch build: the probe enumerates nothing.+ torch = _fake_torch([], vendor = "nvidia", cuda_available = False)+ expected = []+ else:+ torch = _fake_torch(+ [+ _device(name = "NVIDIA GeForce RTX 4090", free_mib = 22000),+ _device(name = "NVIDIA GeForce RTX 3090", free_mib = 18000),+ ],+ vendor = "nvidia",+ )+ expected = [(0, 22000), (1, 18000)]+ elif vendor == "amd":+ if os_key == "macos":+ # Apple ships no ROCm. The Apple Silicon shape is Metal-only; the+ # Intel shape is a Radeon behind a CPU/MPS torch build. Neither+ # enumerates a torch.cuda device, so neither can reach the gate.+ _apply_os(monkeypatch, os_key, is_rocm = False)+ _binary_with_marker(tmp_path, {"mapped_targets": GFX103X})+ torch = _fake_torch([], vendor = "mps", cuda_available = False)+ expected = []+ else:+ # The #7624 shape: a covered dGPU plus an iGPU the gfx103X bundle+ # has no kernels for, whose shared-RAM "free memory" outranks it.+ _apply_os(monkeypatch, os_key, is_rocm = True)+ _binary_with_marker(tmp_path, {"mapped_targets": GFX103X})+ torch = _fake_torch(+ [+ _device("gfx1030", free_mib = 12049, name = "AMD Radeon RX 6800"),+ _device(+ "gfx1036",+ free_mib = 12176,+ name = "AMD Radeon Graphics",+ is_integrated = 1,+ ),+ ],+ vendor = "amd",+ )+ # Plenty of system RAM, so the iGPU's shared-pool cap never binds+ # and the only thing that can change its figure is the host reserve.+ monkeypatch.setattr(+ LlamaCppBackend, "_available_system_memory_mib", staticmethod(lambda: 60000)+ )+ expected = [(0, 12049)]+ else:+ _apply_os(monkeypatch, os_key, is_rocm = False)+ _binary_with_marker(tmp_path, {"mapped_targets": GFX103X})+ torch = _fake_torch([], vendor = "cpu", cuda_available = False)+ expected = []+ monkeypatch.setitem(sys.modules, "torch", torch)+ return expected+++CELLS = [(os_key, vendor) for os_key in OS_KEYS for vendor in ("nvidia", "amd", "cpu")]+++class TestOsVendorMatrix:+ """The 12 cells, against the llama-server (gated) probe."""++ @pytest.mark.parametrize("os_key,vendor", CELLS)+ def test_cell_outcome(+ self, os_key, vendor, tmp_path, monkeypatch, probe_env, marker_spy, arch_map_spy+ ):+ expected = _install_cell(monkeypatch, tmp_path, os_key, vendor)+ assert LlamaCppBackend._get_gpu_free_memory(for_llama_server = True) == expected+ if vendor == "amd" and os_key != "macos":+ # The only cells where the gate is allowed to do anything.+ assert marker_spy, "the ROCm cell must consult the install marker"+ assert arch_map_spy, "the ROCm cell must enumerate device archs"+ else:+ assert marker_spy == [], f"{os_key}/{vendor} read the install marker"+ assert arch_map_spy == [], f"{os_key}/{vendor} enumerated device archs"++ @pytest.mark.parametrize("os_key,vendor", CELLS)+ def test_cell_is_unfiltered_by_default(+ self, os_key, vendor, tmp_path, monkeypatch, probe_env, marker_spy, arch_map_spy+ ):+ """The backwards-compatibility guarantee: every pre-existing caller+ (``for_llama_server`` off, the PyTorch RAG embedding picker included) keeps+ every device on every cell, the AMD one whose iGPU the gate drops too."""+ expected = _install_cell(monkeypatch, tmp_path, os_key, vendor)+ if vendor == "amd" and os_key != "macos":+ # The iGPU is kept, still with its unified-memory host reserve: the+ # gate is what must not apply here, not the APU accounting.+ expected = [(0, 12049), (1, 12176 - _IGPU_HOST_RESERVE_MIB)]+ assert LlamaCppBackend._get_gpu_free_memory() == expected+ assert marker_spy == [], f"{os_key}/{vendor} read the install marker unasked"+ assert arch_map_spy == [], f"{os_key}/{vendor} enumerated device archs unasked"++ @pytest.mark.parametrize("os_key", OS_KEYS)+ def test_nvidia_smi_path_never_reaches_the_gate(+ self, os_key, tmp_path, monkeypatch, marker_spy, arch_map_spy+ ):+ """The common NVIDIA host answers from nvidia-smi and returns before the+ torch fallback the gate lives in. Separate from the cell above, which+ forces the fallback so "inert" is proven on both NVIDIA routes."""+ _apply_os(monkeypatch, os_key, is_rocm = False)+ binary = _binary_with_marker(tmp_path, {"mapped_targets": GFX110X})+ monkeypatch.setattr(+ LlamaCppBackend, "_find_llama_server_binary", staticmethod(lambda: binary)+ )+ for var in ("HIP_VISIBLE_DEVICES", "ROCR_VISIBLE_DEVICES", "CUDA_VISIBLE_DEVICES"):+ monkeypatch.delenv(var, raising = False)++ class _Result:+ returncode = 0+ stdout = "0, 22000, 24564\n1, 18000, 24564\n"++ monkeypatch.setattr(subprocess, "run", lambda *a, **k: _Result())+ # No torch at all: a bare nvidia-smi host must not need one.+ monkeypatch.setitem(sys.modules, "torch", None)+ assert LlamaCppBackend._get_gpu_memory(for_llama_server = True) == [+ (0, 22000, 24564),+ (1, 18000, 24564),+ ]+ assert marker_spy == []+ assert arch_map_spy == []++ @pytest.mark.parametrize("os_key", OS_KEYS)+ def test_cpu_only_host_without_torch_is_empty_and_quiet(+ self, os_key, tmp_path, monkeypatch, probe_env, marker_spy+ ):+ """CPU-only with no torch installed at all: no GPU, no traceback,+ empty list (the import failure is swallowed by the probe)."""+ _apply_os(monkeypatch, os_key, is_rocm = False)+ _binary_with_marker(tmp_path, {"mapped_targets": GFX103X})+ monkeypatch.setitem(sys.modules, "torch", None) # `import torch` -> ImportError+ assert LlamaCppBackend._get_gpu_memory(for_llama_server = True) == []+ assert marker_spy == []++ def test_macos_intel_radeon_shape_is_inert(self, tmp_path, monkeypatch, probe_env, marker_spy):+ """The second Apple shape: an Intel Mac with a Radeon, i.e. a CPU torch+ build that still reports an AMD device name. No ROCm exists there, so+ ``_torch_is_rocm`` is false and the marker stays unread."""+ _apply_os(monkeypatch, "macos", is_rocm = False)+ _binary_with_marker(tmp_path, {"mapped_targets": GFX103X})+ monkeypatch.setitem(+ sys.modules,+ "torch",+ _fake_torch(+ [_device("", name = "AMD Radeon Pro 5500M", free_mib = 8000)],+ vendor = "cpu",+ cuda_available = False,+ ),+ )+ assert LlamaCppBackend._get_gpu_free_memory(for_llama_server = True) == []+ assert marker_spy == []+++class TestAmdCoverageCases:+ """The substantive ROCm cells. Mock-based: no AMD hardware here."""++ @pytest.mark.parametrize("os_key", ["windows", "linux", "wsl"])+ def test_every_device_covered_drops_nothing(self, os_key, tmp_path, monkeypatch, probe_env):+ _apply_os(monkeypatch, os_key, is_rocm = True)+ _binary_with_marker(tmp_path, {"mapped_targets": GFX103X})+ monkeypatch.setitem(+ sys.modules,+ "torch",+ _fake_torch(+ [_device("gfx1030", free_mib = 12049), _device("gfx1032", free_mib = 7000)],+ vendor = "amd",+ ),+ )+ assert LlamaCppBackend._get_gpu_free_memory(for_llama_server = True) == [+ (0, 12049),+ (1, 7000),+ ]++ @pytest.mark.parametrize("os_key", ["windows", "linux", "wsl"])+ def test_uncovered_igpu_is_dropped_and_dgpu_kept(+ self, os_key, tmp_path, monkeypatch, probe_env+ ):+ # #7624 verbatim: gfx1030 dGPU + gfx1036 iGPU against the real gfx103X+ # bundle, which maps gfx1030/1031/1032/1034 only.+ _apply_os(monkeypatch, os_key, is_rocm = True)+ _binary_with_marker(tmp_path, {"mapped_targets": GFX103X})+ monkeypatch.setitem(+ sys.modules,+ "torch",+ _fake_torch(+ [+ _device("gfx1030", free_mib = 12049),+ _device("gfx1036", free_mib = 12176, is_integrated = 1),+ ],+ vendor = "amd",+ ),+ )+ monkeypatch.setattr(+ LlamaCppBackend, "_available_system_memory_mib", staticmethod(lambda: 60000)+ )+ assert LlamaCppBackend._get_gpu_free_memory(for_llama_server = True) == [(0, 12049)]++ @pytest.mark.parametrize("os_key", ["windows", "linux", "wsl"])+ def test_missing_marker_fails_open(self, os_key, tmp_path, monkeypatch, probe_env):+ # Source build / custom link: coverage unknown, so keep every device.+ _apply_os(monkeypatch, os_key, is_rocm = True)+ monkeypatch.setitem(+ sys.modules,+ "torch",+ _fake_torch(+ [_device("gfx1030", free_mib = 12049), _device("gfx1036", free_mib = 12176)],+ vendor = "amd",+ ),+ )+ assert LlamaCppBackend._get_gpu_free_memory(for_llama_server = True) == [+ (0, 12049),+ (1, 12176),+ ]++ @pytest.mark.parametrize("os_key", ["windows", "linux", "wsl"])+ def test_empty_mapped_targets_fails_open(self, os_key, tmp_path, monkeypatch, probe_env):+ # Non-ROCm bundles record []: unknown coverage, not "covers nothing".+ _apply_os(monkeypatch, os_key, is_rocm = True)+ _binary_with_marker(tmp_path, {"mapped_targets": []})+ monkeypatch.setitem(+ sys.modules,+ "torch",+ _fake_torch(+ [_device("gfx1030", free_mib = 12049), _device("gfx1036", free_mib = 12176)],+ vendor = "amd",+ ),+ )+ assert LlamaCppBackend._get_gpu_free_memory(for_llama_server = True) == [+ (0, 12049),+ (1, 12176),+ ]++ @pytest.mark.parametrize("os_key", ["windows", "linux", "wsl"])+ def test_every_device_uncovered_empties_the_pool(+ self, os_key, tmp_path, monkeypatch, probe_env+ ):+ """A marker that covers none of the present cards leaves the llama-server+ probe with nothing. Pinned deliberately: this is the input to the+ downstream behaviour asserted in TestEveryDeviceUncoveredDownstream."""+ _apply_os(monkeypatch, os_key, is_rocm = True)+ _binary_with_marker(tmp_path, {"mapped_targets": GFX120X})+ monkeypatch.setitem(+ sys.modules,+ "torch",+ _fake_torch(+ [_device("gfx1030", free_mib = 12049), _device("gfx1036", free_mib = 12176)],+ vendor = "amd",+ ),+ )+ assert LlamaCppBackend._get_gpu_free_memory(for_llama_server = True) == []+ # ... while the unfiltered probe, and therefore every torch caller,+ # still sees both cards.+ assert LlamaCppBackend._get_gpu_free_memory() == [(0, 12049), (1, 12176)]++ def test_amd_sdk_wheel_is_gated_on_every_os(self, tmp_path, monkeypatch, probe_env):+ """AMD SDK / Radeon wheels leave ``version.hip`` unset and only encode+ "rocm" in ``__version__``; a bare ``version.hip`` test would skip the+ gate on exactly the hosts #7624 was reported from."""+ _apply_os(monkeypatch, "windows", is_rocm = True)+ _binary_with_marker(tmp_path, {"mapped_targets": GFX103X})+ monkeypatch.setitem(+ sys.modules,+ "torch",+ _fake_torch(+ [_device("gfx1030", free_mib = 12049), _device("gfx1036", free_mib = 12176)],+ vendor = "amd_sdk",+ ),+ )+ assert LlamaCppBackend._get_gpu_free_memory(for_llama_server = True) == [(0, 12049)]+++class TestWslIsNotWindows:+ """ROCm under WSL reports through the same torch path as native Linux, but+ ``sys.platform`` is "linux", so the Windows-only free-VRAM cap (#8403) must not+ engage: same arch gate, different memory accounting."""++ def _probe(self, monkeypatch, tmp_path, os_key):+ _apply_os(monkeypatch, os_key, is_rocm = True)+ _binary_with_marker(tmp_path, {"mapped_targets": GFX103X})+ monkeypatch.setitem(+ sys.modules,+ "torch",+ _fake_torch(+ [+ _device("gfx1030", free_mib = 20000),+ _device("gfx1036", free_mib = 12176),+ ],+ vendor = "amd",+ # 24 GiB reserved by this process's own allocator, against a+ # 32 GiB card: on Windows the driver's "free" is an over-report+ # and gets capped to total - reserved = 8192 MiB.+ reserved_bytes = 24 * 1024**3,+ ),+ )+ return LlamaCppBackend._get_gpu_free_memory(for_llama_server = True)++ def test_windows_caps_free_against_the_allocator(self, tmp_path, monkeypatch, probe_env):+ assert self._probe(monkeypatch, tmp_path, "windows") == [(0, 8192)]++ def test_wsl_keeps_the_driver_reading(self, tmp_path, monkeypatch, probe_env):+ assert self._probe(monkeypatch, tmp_path, "wsl") == [(0, 20000)]++ def test_linux_keeps_the_driver_reading(self, tmp_path, monkeypatch, probe_env):+ assert self._probe(monkeypatch, tmp_path, "linux") == [(0, 20000)]+++class TestVisibilityMaskMapping:+ """The gate keys on PHYSICAL ids while torch enumerates visible ordinals.+ Every case below is built so that confusing the two drops the wrong card,+ rather than merely relabelling the surviving one."""++ def test_hip_mask_reversing_the_order_drops_the_right_card(+ self, tmp_path, monkeypatch, probe_env+ ):+ # HIP_VISIBLE_DEVICES=1,0, so ordinal 0 IS physical 1. Unsupported gfx1036+ # is physical 1, supported gfx1030 physical 0, with different free VRAM, so+ # an ordinal/physical mix-up returns (1, 12176) instead of (0, 5000).+ _apply_os(monkeypatch, "linux", is_rocm = True)+ _binary_with_marker(tmp_path, {"mapped_targets": GFX103X})+ monkeypatch.setenv("HIP_VISIBLE_DEVICES", "1,0")+ monkeypatch.setitem(+ sys.modules,+ "torch",+ _fake_torch(+ [+ _device("gfx1036", free_mib = 12176), # ordinal 0 = physical 1+ _device("gfx1030", free_mib = 5000), # ordinal 1 = physical 0+ ],+ vendor = "amd",+ ),+ )+ assert LlamaCppBackend._rocm_arch_by_physical_id() == {1: "gfx1036", 0: "gfx1030"}+ assert LlamaCppBackend._get_gpu_free_memory(for_llama_server = True) == [(0, 5000)]++ def test_rocr_mask_with_a_gap_maps_by_physical_id(self, tmp_path, monkeypatch, probe_env):+ # ROCR_VISIBLE_DEVICES=2,3 on Linux: an off-by-one on either side would+ # report GPU 3 (the unsupported card) or drop GPU 2.+ _apply_os(monkeypatch, "linux", is_rocm = True)+ _binary_with_marker(tmp_path, {"mapped_targets": GFX110X})+ monkeypatch.setenv("ROCR_VISIBLE_DEVICES", "2,3")+ monkeypatch.setitem(+ sys.modules,+ "torch",+ _fake_torch(+ [_device("gfx1100", free_mib = 9000), _device("gfx1036", free_mib = 12176)],+ vendor = "amd",+ ),+ )+ assert LlamaCppBackend._get_gpu_free_memory(for_llama_server = True) == [(2, 9000)]++ def test_windows_ignores_a_stray_rocr_mask(self, tmp_path, monkeypatch, probe_env):+ # Windows HIP has no ROCr layer, so ROCR_VISIBLE_DEVICES masks nothing and+ # must not be read as the ordinal->physical map: doing so would label the+ # surviving card GPU 2 and pin a device that does not exist.+ _apply_os(monkeypatch, "windows", is_rocm = True)+ _binary_with_marker(tmp_path, {"mapped_targets": GFX110X})+ monkeypatch.setenv("ROCR_VISIBLE_DEVICES", "2,3")+ monkeypatch.setitem(+ sys.modules,+ "torch",+ _fake_torch(+ [_device("gfx1100", free_mib = 9000), _device("gfx1036", free_mib = 12176)],+ vendor = "amd",+ ),+ )+ assert LlamaCppBackend._get_gpu_free_memory(for_llama_server = True) == [(0, 9000)]++ def test_hip_mask_wins_over_cuda_mask(self, tmp_path, monkeypatch, probe_env):+ # Both masks set with different contents: HIP is the one the ROCm+ # runtime honors, so it decides the physical ids the gate drops by.+ _apply_os(monkeypatch, "linux", is_rocm = True)+ _binary_with_marker(tmp_path, {"mapped_targets": GFX103X})+ monkeypatch.setenv("HIP_VISIBLE_DEVICES", "3,1")+ monkeypatch.setenv("CUDA_VISIBLE_DEVICES", "0,1")+ monkeypatch.setitem(+ sys.modules,+ "torch",+ _fake_torch(+ [_device("gfx1036", free_mib = 12176), _device("gfx1030", free_mib = 5000)],+ vendor = "amd",+ ),+ )+ assert LlamaCppBackend._get_gpu_free_memory(for_llama_server = True) == [(1, 5000)]++ def test_empty_mask_reports_no_gpu(self, tmp_path, monkeypatch, probe_env):+ # HIP_VISIBLE_DEVICES="" hides every agent, so the runtime enumerates+ # nothing. The gate still resolves its inputs first, and must return an+ # empty list rather than raise on the empty ordinal->physical map.+ _apply_os(monkeypatch, "linux", is_rocm = True)+ _binary_with_marker(tmp_path, {"mapped_targets": GFX103X})+ monkeypatch.setenv("HIP_VISIBLE_DEVICES", "")+ monkeypatch.setitem(sys.modules, "torch", _fake_torch([], vendor = "amd"))+ assert LlamaCppBackend._get_gpu_free_memory(for_llama_server = True) == []+++class TestArchStringRobustness:+ """Both sides of the comparison are normalised: the manifest token and the+ driver's arch string. A device must never be dropped over spelling."""++ @pytest.mark.parametrize(+ "reported",+ [+ "gfx1030",+ "GFX1030",+ " gfx1030 ",+ "gfx1030:xnack-",+ "gfx1030:sramecc+:xnack-",+ "GFX1030:SRAMECC+:XNACK-",+ ],+ ids = [+ "plain",+ "uppercase",+ "whitespace",+ "xnack",+ "sramecc_xnack",+ "uppercase_suffixed",+ ],+ )+ def test_covered_device_survives_every_spelling(+ self, reported, tmp_path, monkeypatch, probe_env+ ):+ _apply_os(monkeypatch, "linux", is_rocm = True)+ _binary_with_marker(tmp_path, {"mapped_targets": GFX103X})+ monkeypatch.setitem(+ sys.modules,+ "torch",+ _fake_torch(+ [_device(reported, free_mib = 12049), _device("gfx1036", free_mib = 12176)],+ vendor = "amd",+ ),+ )+ assert LlamaCppBackend._get_gpu_free_memory(for_llama_server = True) == [(0, 12049)]++ @pytest.mark.parametrize(+ "token", ["GFX1030", " gfx1030 ", "gfx1030:xnack-", "gfx1030:sramecc+:xnack-"]+ )+ def test_marker_token_spellings_are_normalised_too(+ self, token, tmp_path, monkeypatch, probe_env+ ):+ _apply_os(monkeypatch, "linux", is_rocm = True)+ _binary_with_marker(tmp_path, {"mapped_targets": [token]})+ monkeypatch.setitem(+ sys.modules,+ "torch",+ _fake_torch(+ [_device("gfx1030", free_mib = 12049), _device("gfx1036", free_mib = 12176)],+ vendor = "amd",+ ),+ )+ assert LlamaCppBackend._get_gpu_free_memory(for_llama_server = True) == [(0, 12049)]++ @pytest.mark.parametrize("attr", ["gcnArchName", "gcn_arch_name", "arch_name", "gfx_arch_name"])+ def test_every_arch_attribute_spelling_is_read(self, attr, tmp_path, monkeypatch, probe_env):+ # AMD SDK / Radeon wheels populate only one of these. Reading a single+ # spelling would leave the map empty and fail the gate open -- the crash+ # this exists to prevent.+ _apply_os(monkeypatch, "linux", is_rocm = True)+ _binary_with_marker(tmp_path, {"mapped_targets": GFX103X})+ monkeypatch.setitem(+ sys.modules,+ "torch",+ _fake_torch(+ [+ _device("gfx1030", free_mib = 12049, arch_attr = attr),+ _device("gfx1036", free_mib = 12176, arch_attr = attr),+ ],+ vendor = "amd",+ ),+ )+ assert LlamaCppBackend._get_gpu_free_memory(for_llama_server = True) == [(0, 12049)]++ def test_blank_arch_fails_open(self, tmp_path, monkeypatch, probe_env):+ # A device reporting no arch at all is unknown, not unsupported.+ _apply_os(monkeypatch, "linux", is_rocm = True)+ _binary_with_marker(tmp_path, {"mapped_targets": GFX103X})+ monkeypatch.setitem(+ sys.modules,+ "torch",+ _fake_torch(+ [_device("gfx1030", free_mib = 12049), _device("", free_mib = 12176)],+ vendor = "amd",+ ),+ )+ assert LlamaCppBackend._get_gpu_free_memory(for_llama_server = True) == [+ (0, 12049),+ (1, 12176),+ ]++ def test_undescribable_device_fails_open(self, tmp_path, monkeypatch, probe_env):+ # get_device_properties raising (a card the runtime cannot query) must+ # neither drop the device nor abort the probe for the other cards.+ _apply_os(monkeypatch, "linux", is_rocm = True)+ _binary_with_marker(tmp_path, {"mapped_targets": GFX103X})+ monkeypatch.setitem(+ sys.modules,+ "torch",+ _fake_torch(+ [+ _device("gfx1030", free_mib = 12049),+ _device(+ "gfx1036",+ free_mib = 12176,+ describe_error = RuntimeError("hipGetDeviceProperties failed"),+ ),+ _device("gfx1036", free_mib = 3000),+ ],+ vendor = "amd",+ ),+ )+ assert LlamaCppBackend._get_gpu_free_memory(for_llama_server = True) == [+ (0, 12049),+ (1, 12176),+ ]++ def test_marker_junk_tokens_are_ignored_not_matched(self, tmp_path, monkeypatch, probe_env):+ # Blank / whitespace-only entries must not become a "" arch that some+ # device's blank arch could match against.+ _apply_os(monkeypatch, "linux", is_rocm = True)+ _binary_with_marker(tmp_path, {"mapped_targets": ["", " ", "gfx1030"]})+ assert LlamaCppBackend._installed_llama_gfx_archs(+ str(tmp_path / "build" / "bin" / "llama-server")+ ) == frozenset({"gfx1030"})+++def _run_auto_load(+ monkeypatch,+ tmp_path,+ torch,+ marker_targets,+ *,+ returncode = 1,+ output = "",+ env_extra = None,+ model_bytes = 1024,+ capture = None,+ intent_kwargs = None,+ apu_ram_stub = None,+ backend = None,+):+ """Drive a real automatic (no explicit GPU pick) llama-server load with the real+ ``_get_gpu_memory`` behind it, and return the spawned (cmd, env) list.++ Everything below the placement decision is faked: header-only GGUF, Popen never+ runs, health wait answers from ``returncode``. The point is what placement handed+ the child, not that llama-server works."""+ if marker_targets is not None:+ _binary_with_marker(tmp_path, {"mapped_targets": marker_targets})+ binary = str(tmp_path / "build" / "bin" / "llama-server")+ monkeypatch.setitem(sys.modules, "torch", torch)++ def _gguf_string(value):+ encoded = value.encode()+ return struct.pack("<Q", len(encoded)) + encoded++ metadata = _gguf_string("general.architecture") + struct.pack("<I", 8) + _gguf_string("llama")+ gguf = tmp_path / "model.gguf"+ gguf.write_bytes(struct.pack("<IIQQ", 0x46554747, 3, 0, 1) + metadata)++ # ``backend`` replays a SECOND load onto the state the first one left, which is+ # the only way to see per-load state that must not be inherited.+ backend = backend if backend is not None else LlamaCppBackend()+ # ``capture`` hands the post-launch backend back for state the argv and env+ # cannot show (e.g. _gpu_offload_active).+ if capture is not None:+ capture["backend"] = backend+ backend._read_gguf_metadata = lambda _path: None+ backend._can_estimate_kv = lambda: False+ # model_bytes drives the placement decision: a model no GPU can hold makes+ # _select_gpus return (None, True), so `--fit on` owns placement.+ backend._get_gguf_size_bytes = lambda _path: model_bytes+ backend._mmproj_vram_bytes = lambda _path: 0+ backend._resolve_launch_mmproj_path = lambda **_kwargs: None+ # Off by default: the APU RAM preflight is not what most of these cells are+ # about. A test that IS about it passes its own recording stub.+ backend._apu_ram_shortfall_message = apu_ram_stub or (lambda *_args, **_kwargs: None)+ backend._find_llama_server_binary = lambda include_denied = False: binary+ backend._fit_off_retry_eligible = lambda *_args, **_kwargs: False+ backend.probe_server_capabilities = lambda _binary: {"found": True}+ backend._record_server_pid = lambda _pid: None+ backend._clear_server_pid = lambda: None+ # env_extra seeds the child env the way an inherited / user-set variable+ # would, so "did THIS launch set it" can be told from "it was already there".+ _base_env = {"PATH": os.environ.get("PATH", ""), **(env_extra or {})}+ backend._llama_server_env_for_binary = lambda _binary: dict(_base_env)+ monkeypatch.setattr(+ LlamaCppBackend, "_is_vulkan_backend", staticmethod(lambda _binary = None: False)+ )++ launches = []++ class _Process:+ pid = 123+ stdout = ()++ def __init__(self, code):+ self.returncode = code++ def poll(self):+ return returncode++ def terminate(self):+ return None++ def wait(self, timeout = None):+ return returncode++ def kill(self):+ return None++ def _popen(cmd, **kwargs):+ launches.append((list(cmd), dict(kwargs["env"])))+ return _Process(returncode)++ def _wait_for_health(timeout):+ backend._stdout_lines = [output]+ return returncode is None++ backend._wait_for_health = _wait_for_health+ backend._prepare_cpu_fallback_launch = lambda *_a, **_kw: None+ monkeypatch.setattr(subprocess, "Popen", _popen)+ try:+ backend.load_model(+ GgufLoadIntent(+ gguf_path = str(gguf),+ model_identifier = "owner/model",+ **(intent_kwargs or {}),+ )+ )+ except Exception as exc:+ # A crashing child is one of the cases under test; the launches are the+ # evidence either way. A refusal that PREVENTS a spawn has no launch to+ # point at, so hand it back through ``capture`` for those tests.+ if capture is not None:+ capture["error"] = exc+ return launches+++def _visibility(env):+ return {+ name: env.get(name)+ for name in ("HIP_VISIBLE_DEVICES", "ROCR_VISIBLE_DEVICES", "CUDA_VISIBLE_DEVICES")+ if env.get(name) is not None+ }+++class TestEveryDeviceUncoveredDownstream:+ """What the gate emptying the pool does to a load. Mock-based (no ROCm here).+ The comparison case is the #7624 shape, one covered card surviving; the case+ under test is the same host with a marker covering neither."""++ def test_one_covered_device_is_pinned(self, tmp_path, monkeypatch, probe_env):+ """The end-to-end #7624 fix. The iGPU's shared-RAM "free memory" outranks+ the dGPU's VRAM even after the host reserve, so before the gate automatic+ placement pinned the iGPU and llama-server died with "device kernel image is+ invalid". Measured on origin/main with these inputs: ROCR_VISIBLE_DEVICES=1+ (the gfx1036 iGPU); with the gate, 0."""+ _apply_os(monkeypatch, "linux", is_rocm = True)+ torch = _fake_torch(+ [+ _device("gfx1030", free_mib = 12049),+ _device("gfx1036", free_mib = 30000, is_integrated = 1),+ ],+ vendor = "amd",+ )+ monkeypatch.setattr(+ LlamaCppBackend, "_available_system_memory_mib", staticmethod(lambda: 60000)+ )+ launches = _run_auto_load(monkeypatch, tmp_path, torch, GFX103X, returncode = None)+ assert len(launches) == 1+ _cmd, env = launches[0]+ # The covered dGPU, and only it, is exposed to the child. Masked at the+ # ROCr layer, because a HIP-only mask still enumerates every agent first+ # and that enumeration can segfault on the unsupported card.+ assert _visibility(env) == {"ROCR_VISIBLE_DEVICES": "0", "CUDA_VISIBLE_DEVICES": "0"}++ def test_all_uncovered_degrades_to_cpu(self, tmp_path, monkeypatch, probe_env):+ """Every device gated out must mask the child onto the CPU (#7624).++ Before this the empty pool left ``gpu_indices`` None, the launch took the+ ``--fit on`` arm, the pin block never ran and no mask was written, so the+ child enumerated both unsupported cards and died, with the reactive retry+ unable to help (its guard needs a truthy ``gpu_indices``)."""+ _apply_os(monkeypatch, "linux", is_rocm = True)+ torch = _fake_torch(+ [_device("gfx1030", free_mib = 12049), _device("gfx1036", free_mib = 12176)],+ vendor = "amd",+ )+ launches = _run_auto_load(+ monkeypatch,+ tmp_path,+ torch,+ GFX120X,+ returncode = 1,+ output = "ROCm error: device kernel image is invalid",+ )+ assert len(launches) == 1, "the arch-crash retry cannot fire without a pinned set"+ _cmd, env = launches[0]+ # "-1" keeps the HIP spelling: the sentinel has no portable ROCR form.+ assert _visibility(env) == {"HIP_VISIBLE_DEVICES": "-1", "CUDA_VISIBLE_DEVICES": "-1"}++ def test_all_uncovered_keeps_an_inherited_rocr_mask(self, tmp_path, monkeypatch, probe_env):+ """The forced-CPU mask must not widen what the child can see. ROCr filters+ at topology build, below HIP, so a parent that hid a segfaulting agent keeps+ hiding it: HIP "-1" already means zero devices, and clearing ROCR would hand+ the HSA enumeration the dropped agents. The embedding CPU launch states the+ rule; the chat one went through the default HIP arm, which clears ROCR."""+ _apply_os(monkeypatch, "linux", is_rocm = True)+ torch = _fake_torch(+ [_device("gfx1030", free_mib = 12049), _device("gfx1036", free_mib = 12176)],+ vendor = "amd",+ )+ launches = _run_auto_load(+ monkeypatch,+ tmp_path,+ torch,+ GFX120X, # covers neither card+ returncode = None,+ env_extra = {"ROCR_VISIBLE_DEVICES": "1"},+ )+ assert len(launches) == 1+ _cmd, env = launches[0]+ assert _visibility(env) == {+ "HIP_VISIBLE_DEVICES": "-1",+ "ROCR_VISIBLE_DEVICES": "1",+ "CUDA_VISIBLE_DEVICES": "-1",+ }++ def test_the_forced_cpu_server_reports_zero_vram(self, tmp_path, monkeypatch, probe_env):+ """A masked-off child holds no VRAM, so the flag training reads must be+ exactly False: routes/training_vram.py spares a server only on+ ``is not False``, so the counted classifier's None (the gated probe left the+ detected list empty) would unload one whose death frees nothing."""+ _apply_os(monkeypatch, "linux", is_rocm = True)+ torch = _fake_torch(+ [_device("gfx1030", free_mib = 12049), _device("gfx1036", free_mib = 12176)],+ vendor = "amd",+ )+ capture: dict = {}+ launches = _run_auto_load(+ monkeypatch, tmp_path, torch, GFX120X, returncode = None, capture = capture+ )+ _cmd, env = launches[0]+ assert _visibility(env) == {"HIP_VISIBLE_DEVICES": "-1", "CUDA_VISIBLE_DEVICES": "-1"}+ assert capture["backend"]._gpu_offload_active is False++ def test_a_covered_host_still_classifies_normally(self, tmp_path, monkeypatch, probe_env):+ """The zero-VRAM verdict is the gate's doing, not a blanket False: a host+ the build covers keeps the counted classifier's answer."""+ _apply_os(monkeypatch, "linux", is_rocm = True)+ torch = _fake_torch(+ [_device("gfx1030", free_mib = 12049), _device("gfx1031", free_mib = 12176)],+ vendor = "amd",+ )+ capture: dict = {}+ _run_auto_load(monkeypatch, tmp_path, torch, GFX103X, returncode = None, capture = capture)+ assert capture["backend"]._gpu_offload_active is not False++ def test_all_uncovered_names_the_devices_in_the_warning(self, tmp_path, monkeypatch, probe_env):+ """The CPU fallback is a large, silent-looking performance cliff, so the+ log has to say why: which devices are present, and that the installed+ build covers none of them (#7624)."""+ _apply_os(monkeypatch, "linux", is_rocm = True)+ torch = _fake_torch(+ [_device("gfx1030", free_mib = 12049), _device("gfx1036", free_mib = 12176)],+ vendor = "amd",+ )+ # structlog, so the stdlib caplog fixture cannot see these records.+ warnings = []+ monkeypatch.setattr(+ llama_cpp.logger,+ "warning",+ lambda msg, *a, **kw: warnings.append(msg % a if a else msg),+ )+ _run_auto_load(monkeypatch, tmp_path, torch, GFX120X, returncode = 1)+ _hits = [w for w in warnings if "falls back to CPU" in w]+ assert len(_hits) == 1, warnings+ assert "0 (gfx1030)" in _hits[0] and "1 (gfx1036)" in _hits[0]++ def test_partial_coverage_never_reaches_the_cpu_fallback(+ self, tmp_path, monkeypatch, probe_env+ ):+ """The normal #7624 host (one covered card) must be untouched by the CPU+ fallback: it still pins the survivor, and never pays for the second,+ ungated probe the fallback needs to tell "all gated out" from "no GPU"."""+ _apply_os(monkeypatch, "linux", is_rocm = True)+ torch = _fake_torch(+ [_device("gfx1030", free_mib = 12049), _device("gfx1036", free_mib = 12176)],+ vendor = "amd",+ )+ _ungated = []+ _real = LlamaCppBackend._get_gpu_memory++ def _spy(binary = None, *, for_llama_server = False):+ if not for_llama_server:+ _ungated.append(binary)+ return _real(binary, for_llama_server = for_llama_server)++ monkeypatch.setattr(LlamaCppBackend, "_get_gpu_memory", staticmethod(_spy))+ launches = _run_auto_load(monkeypatch, tmp_path, torch, GFX103X, returncode = None)+ assert len(launches) == 1+ _cmd, env = launches[0]+ assert _visibility(env) == {"ROCR_VISIBLE_DEVICES": "0", "CUDA_VISIBLE_DEVICES": "0"}+ assert _ungated == [], "a covered device was found; the ungated re-probe is dead weight"++ def test_a_model_too_large_to_pin_still_masks_the_uncovered_card(+ self, tmp_path, monkeypatch, probe_env+ ):+ """One card short of the forced-CPU case: the gate drops the iGPU but keeps+ the dGPU, so the pool is not empty -- and a model too large for the planner+ makes `_select_gpus` answer (None, True) with `gpu_indices` still None.+ Nothing else writes a mask on that arm, so the child would enumerate the+ dropped card and die, the reactive retry needing `gpu_indices` to help."""+ _apply_os(monkeypatch, "linux", is_rocm = True)+ torch = _fake_torch(+ [_device("gfx1030", free_mib = 12049), _device("gfx1036", free_mib = 12176)],+ vendor = "amd",+ )+ launches = _run_auto_load(+ monkeypatch,+ tmp_path,+ torch,+ GFX103X,+ returncode = None,+ model_bytes = 400 * 1024**3,+ )+ assert len(launches) == 1+ cmd, env = launches[0]+ # --fit on is the arm under test: placement was handed to llama.cpp.+ assert cmd[cmd.index("--fit") + 1] == "on"+ # gfx1036 is index 1 and has no kernels in a gfx103X build, so only 0+ # may reach the child. ROCr, not HIP: a HIP mask still enumerates first.+ assert _visibility(env) == {"ROCR_VISIBLE_DEVICES": "0", "CUDA_VISIBLE_DEVICES": "0"}++ def test_full_coverage_leaves_a_fit_owned_launch_unmasked(+ self, tmp_path, monkeypatch, probe_env+ ):+ """The same unpinned arm on a host the build fully covers writes no mask+ at all, so the pin is the gate's doing and not a blanket change to every+ `--fit on` launch."""+ _apply_os(monkeypatch, "linux", is_rocm = True)+ torch = _fake_torch(+ [_device("gfx1030", free_mib = 12049), _device("gfx1031", free_mib = 12176)],+ vendor = "amd",+ )+ launches = _run_auto_load(+ monkeypatch,+ tmp_path,+ torch,+ GFX103X,+ returncode = None,+ model_bytes = 400 * 1024**3,+ )+ assert len(launches) == 1+ cmd, env = launches[0]+ assert cmd[cmd.index("--fit") + 1] == "on"+ assert _visibility(env) == {}++ def test_cuda_host_with_no_gpu_does_not_reprobe(self, tmp_path, monkeypatch, probe_env):+ """The GPU-less path is the common case, so the ROCm guard has to come+ BEFORE the ungated re-probe: on a CUDA or CPU-only host an empty probe+ just means "no GPU", and probing again would cost every such load."""+ _apply_os(monkeypatch, "linux", is_rocm = False)+ torch = _fake_torch([], vendor = "nvidia")+ _probes = []+ _real = LlamaCppBackend._get_gpu_memory++ def _spy(binary = None, *, for_llama_server = False):+ _probes.append(for_llama_server)+ return _real(binary, for_llama_server = for_llama_server)++ monkeypatch.setattr(LlamaCppBackend, "_get_gpu_memory", staticmethod(_spy))+ launches = _run_auto_load(monkeypatch, tmp_path, torch, GFX110X, returncode = None)+ assert len(launches) == 1+ _cmd, env = launches[0]+ # No mask at all: this is an ordinary CPU load, not the gated fallback.+ assert _visibility(env) == {}+ assert _probes == [True], "the ungated re-probe must not run off ROCm"+++class TestArchCrashRetryEnv:+ """What the arch-crash respawn inherits from the crashed launch (#7624). The+ canonical shape: the shared-pool APU outranks the dGPU, is pinned, and+ llama-server dies with "device kernel image is invalid"; the retry moves to the+ discrete card. Mock-based, no ROCm here."""++ def _apu_then_dgpu(self, monkeypatch):+ _apply_os(monkeypatch, "linux", is_rocm = True)+ monkeypatch.setattr(+ LlamaCppBackend, "_rocm_unified_memory_gpu_ids", staticmethod(lambda: {0})+ )+ monkeypatch.setattr(+ LlamaCppBackend, "_available_system_memory_mib", staticmethod(lambda: 60000)+ )+ return _fake_torch(+ [+ _device("gfx1151", free_mib = 40000, is_integrated = 1),+ _device("gfx1030", free_mib = 12049),+ ],+ vendor = "amd",+ )++ def test_retry_on_a_discrete_card_drops_unified_memory_env(+ self, tmp_path, monkeypatch, probe_env+ ):+ """GGML_CUDA_ENABLE_UNIFIED_MEMORY is decided for the CRASHED set. Left+ in place, the respawn on the dGPU keeps env that+ _amd_apu_wants_unified_memory's own docstring says hurts discrete GPUs."""+ torch = self._apu_then_dgpu(monkeypatch)+ launches = _run_auto_load(+ monkeypatch,+ tmp_path,+ torch,+ None, # no marker: the proactive gate fails open, so the crash path runs+ returncode = 1,+ output = "ROCm error: device kernel image is invalid",+ )+ # The APU is pinned first, so the crashed spawn carries the env and the+ # respawns are masked onto the discrete card. The unrelated --fit off retry+ # spawns each launch twice, so select by the mask, not by position.+ assert launches[0][1].get("GGML_CUDA_ENABLE_UNIFIED_MEMORY") == "1"+ _retry = [env for _c, env in launches if env.get("ROCR_VISIBLE_DEVICES") == "1"]+ assert _retry, "the arch-crash retry did not fire"+ assert all("GGML_CUDA_ENABLE_UNIFIED_MEMORY" not in env for env in _retry)++ def test_the_no_binary_for_gpu_spelling_also_fires_the_retry(+ self, tmp_path, monkeypatch, probe_env+ ):+ """Same mismatch, HIP's other error code: hipErrorNoBinaryForGpu, documented+ as code compiled for a different arch. Neither field log showed it, so keying+ recovery on the InvalidImage wording alone leaves those builds on the+ misleading GGUF error."""+ torch = self._apu_then_dgpu(monkeypatch)+ launches = _run_auto_load(+ monkeypatch,+ tmp_path,+ torch,+ None,+ returncode = 1,+ output = "ROCm error: no kernel image is available for execution on the device",+ )+ _retry = [env for _c, env in launches if env.get("ROCR_VISIBLE_DEVICES") == "1"]+ assert _retry, "the retry did not fire on the NoBinaryForGpu wording"++ def test_a_user_set_unified_memory_value_survives_the_retry(+ self, tmp_path, monkeypatch, probe_env+ ):+ """The first spawn uses setdefault, so a value already in env is the+ user's. Popping unconditionally would clobber it; ownership is tracked+ instead, and only a value this launch set is withdrawn."""+ torch = self._apu_then_dgpu(monkeypatch)+ monkeypatch.setenv("GGML_CUDA_ENABLE_UNIFIED_MEMORY", "1")+ launches = _run_auto_load(+ monkeypatch,+ tmp_path,+ torch,+ None,+ returncode = 1,+ output = "ROCm error: device kernel image is invalid",+ env_extra = {"GGML_CUDA_ENABLE_UNIFIED_MEMORY": "1"},+ )+ _retry = [env for _c, env in launches if env.get("ROCR_VISIBLE_DEVICES") == "1"]+ assert _retry, "the arch-crash retry did not fire"+ assert all(env.get("GGML_CUDA_ENABLE_UNIFIED_MEMORY") == "1" for env in _retry)+++class TestManualSplitLaunchesRespectTheGate:+ """Manual memory mode is not an explicit GPU pick, so the probe still opts into+ the gate (``for_llama_server = not gpu_ids``) -- but a manual per-GPU ratio took+ its own env branch, re-emitting the WHOLE visible set and handing the child the+ card the gate had just dropped."""++ def _manual_split(+ self,+ monkeypatch,+ tmp_path,+ targets,+ *,+ devices,+ capture = None,+ backend = None,+ tensor_split = (1.0, 1.0),+ gpu_layers = 20,+ tensor_parallel = False,+ ):+ _apply_os(monkeypatch, "linux", is_rocm = True)+ torch = _fake_torch(devices, vendor = "amd")+ return _run_auto_load(+ monkeypatch,+ tmp_path,+ torch,+ targets,+ returncode = None,+ capture = capture,+ backend = backend,+ intent_kwargs = {+ "gpu_memory_mode": "manual",+ "gpu_layers": gpu_layers,+ "tensor_split": tensor_split,+ "tensor_parallel": tensor_parallel,+ },+ )++ def test_the_dropped_ratio_is_recorded_for_the_duplicate_load_check(+ self, tmp_path, monkeypatch, probe_env+ ):+ """Dropping the ratio from the argv is half the job: the UI re-sends the same+ request on every Apply and the duplicate-load check compares the live+ ``_tensor_split`` against it, so a launch that drops the ratio and records+ nothing respawns the same already-normalized server every time."""+ capture: dict = {}+ self._manual_split(+ monkeypatch,+ tmp_path,+ GFX103X,+ devices = [+ _device("gfx1030", free_mib = 12049),+ _device("gfx1036", free_mib = 12176),+ ],+ capture = capture,+ )+ backend = capture["backend"]+ assert backend._tensor_split is None # gone from the argv+ assert backend._arch_gate_dropped_tensor_split == (1.0, 1.0) # but not forgotten++ def test_a_covered_host_records_no_drop(self, tmp_path, monkeypatch, probe_env):+ """The record is the gate's doing. With every card covered the ratio is+ still live, so nothing may be recorded as dropped -- that entry is what+ excuses a mismatch, and an unearned one would dedupe a genuine change."""+ capture: dict = {}+ self._manual_split(+ monkeypatch,+ tmp_path,+ GFX103X,+ devices = [+ _device("gfx1030", free_mib = 12049),+ _device("gfx1031", free_mib = 12176),+ ],+ capture = capture,+ )+ backend = capture["backend"]+ assert list(backend._tensor_split) == [1.0, 1.0]+ assert backend._arch_gate_dropped_tensor_split is None++ def test_a_later_load_does_not_inherit_the_dropped_ratio(+ self, tmp_path, monkeypatch, probe_env+ ):+ """The record excuses a mismatch, so it must not outlive the launch that+ earned it: after a gated split load, a load carrying no ratio would leave the+ stale entry excusing a split request against a server running none, and Apply+ would silently do nothing."""+ capture: dict = {}+ self._manual_split(+ monkeypatch,+ tmp_path,+ GFX103X,+ devices = [+ _device("gfx1030", free_mib = 12049),+ _device("gfx1036", free_mib = 12176),+ ],+ capture = capture,+ )+ backend = capture["backend"]+ assert backend._arch_gate_dropped_tensor_split == (1.0, 1.0)+ # Same backend, second load: covered host, no ratio, so nothing is dropped.+ self._manual_split(+ monkeypatch,+ tmp_path,+ GFX103X,+ devices = [+ _device("gfx1030", free_mib = 12049),+ _device("gfx1031", free_mib = 12176),+ ],+ backend = backend,+ tensor_split = None,+ gpu_layers = 21, # differs, so this really relaunches rather than dedupes+ )+ assert backend._tensor_split is None+ assert backend._arch_gate_dropped_tensor_split is None++ def test_the_dropped_tensor_mode_is_recorded_too(self, tmp_path, monkeypatch, probe_env):+ """The ratio is half the normalization: narrowing to one survivor also drops+ --split-mode tensor, and ``_tensor_parallel_matches_loaded`` compares the+ unchanged request against the layer-split server, so an unrecorded drop reloads+ the same multi-GB model on every Apply."""+ capture: dict = {}+ self._manual_split(+ monkeypatch,+ tmp_path,+ GFX103X,+ devices = [+ _device("gfx1030", free_mib = 12049),+ _device("gfx1036", free_mib = 12176),+ ],+ capture = capture,+ tensor_parallel = True,+ )+ backend = capture["backend"]+ assert backend._tensor_parallel is False # gone from the argv+ assert backend._arch_gate_dropped_tensor_parallel is True # but not forgotten++ def test_a_covered_host_records_no_mode_drop(self, tmp_path, monkeypatch, probe_env):+ """The record excuses a mismatch, so an unearned one would dedupe a genuine+ layer-to-tensor change away."""+ capture: dict = {}+ self._manual_split(+ monkeypatch,+ tmp_path,+ GFX103X,+ devices = [+ _device("gfx1030", free_mib = 12049),+ _device("gfx1031", free_mib = 12176),+ ],+ capture = capture,+ tensor_parallel = True,+ )+ # Live, not normalized: the record would be unearned.+ assert capture["backend"]._tensor_parallel is True+ assert capture["backend"]._arch_gate_dropped_tensor_parallel is False++ def test_a_forced_cpu_launch_records_both_drops(self, tmp_path, monkeypatch, probe_env):+ """The forced-CPU arm strips the mode AND the ratio, so it records both: it is+ the one arm that normalizes a manual tensor request all the way down to a server+ with no visible device."""+ capture: dict = {}+ self._manual_split(+ monkeypatch,+ tmp_path,+ ["gfx908"], # covers neither card+ devices = [+ _device("gfx1030", free_mib = 12049),+ _device("gfx1036", free_mib = 12176),+ ],+ capture = capture,+ tensor_parallel = True,+ )+ backend = capture["backend"]+ assert backend._arch_gate_forced_cpu is True+ assert backend._tensor_parallel is False and backend._tensor_split is None+ assert backend._arch_gate_dropped_tensor_parallel is True+ assert backend._arch_gate_dropped_tensor_split == (1.0, 1.0)++ def test_a_narrowed_host_masks_and_drops_the_ratio(self, tmp_path, monkeypatch, probe_env):+ launches = self._manual_split(+ monkeypatch,+ tmp_path,+ GFX103X,+ devices = [+ _device("gfx1030", free_mib = 12049),+ _device("gfx1036", free_mib = 12176),+ ],+ )+ assert len(launches) == 1+ cmd, env = launches[0]+ # The ratio was sized for both cards; the mask re-indexes the survivor to+ # ordinal 0, so keeping it would weight the wrong device.+ assert "--tensor-split" not in cmd+ assert _visibility(env) == {"ROCR_VISIBLE_DEVICES": "0", "CUDA_VISIBLE_DEVICES": "0"}++ def test_a_covered_host_keeps_its_ratio_and_its_order_pin(+ self, tmp_path, monkeypatch, probe_env+ ):+ """The drop is the gate's doing. With every card covered the manual ratio+ survives untouched and the launch keeps the PCI order pin it always had."""+ launches = self._manual_split(+ monkeypatch,+ tmp_path,+ GFX103X,+ devices = [+ _device("gfx1030", free_mib = 12049),+ _device("gfx1031", free_mib = 12176),+ ],+ )+ assert len(launches) == 1+ cmd, env = launches[0]+ assert cmd[cmd.index("--tensor-split") + 1] == "1,1"+ assert env.get("CUDA_DEVICE_ORDER") == "PCI_BUS_ID"+++class TestForcedCpuDropsTensorMode:+ """``--split-mode tensor`` with no visible device aborts the server instead of+ loading on CPU (the file says so twice: the manual gpu_layers=0 guard, and the+ paravirtual pin's note on "LLAMA_SPLIT_MODE_TENSOR not implemented for+ architecture"). Manual mode admits tensor parallelism on the FULL device count,+ so the forced-CPU mask could be reached with the flag still in the argv."""++ def test_the_forced_cpu_launch_carries_no_split_flags(self, tmp_path, monkeypatch, probe_env):+ _apply_os(monkeypatch, "linux", is_rocm = True)+ torch = _fake_torch(+ [_device("gfx1030", free_mib = 12049), _device("gfx1031", free_mib = 12176)],+ vendor = "amd",+ )+ capture: dict = {}+ launches = _run_auto_load(+ monkeypatch,+ tmp_path,+ torch,+ GFX120X, # covers neither card+ returncode = None,+ capture = capture,+ intent_kwargs = {+ "gpu_memory_mode": "manual",+ "gpu_layers": 20,+ "tensor_parallel": True,+ },+ )+ assert len(launches) == 1+ cmd, env = launches[0]+ assert _visibility(env) == {"HIP_VISIBLE_DEVICES": "-1", "CUDA_VISIBLE_DEVICES": "-1"}+ assert "--split-mode" not in cmd and "--tensor-split" not in cmd+ # /status must not advertise a mode the child was never given.+ assert capture["backend"]._tensor_parallel is False++ def test_a_covered_host_keeps_tensor_mode(self, tmp_path, monkeypatch, probe_env):+ """The normalisation is the gate's doing, not a blanket drop of tensor+ mode from every manual launch."""+ _apply_os(monkeypatch, "linux", is_rocm = True)+ torch = _fake_torch(+ [_device("gfx1030", free_mib = 12049), _device("gfx1031", free_mib = 12176)],+ vendor = "amd",+ )+ launches = _run_auto_load(+ monkeypatch,+ tmp_path,+ torch,+ GFX103X,+ returncode = None,+ intent_kwargs = {+ "gpu_memory_mode": "manual",+ "gpu_layers": 20,+ "tensor_parallel": True,+ },+ )+ cmd, _env = launches[0]+ assert cmd[cmd.index("--split-mode") + 1] == "tensor"+++class TestGatedNarrowingDropsUnifiedMemory:+ """The unified-memory decision is made against ``gpu_indices``, None on the+ fit-owned and manual-split arms, so an uncovered APU anywhere on the host turns+ it on -- and the survivor mask then hands the child only discrete cards, where+ the same code calls it harmful."""++ def _apu_and_dgpu(self, monkeypatch):+ _apply_os(monkeypatch, "linux", is_rocm = True)+ monkeypatch.setattr(+ LlamaCppBackend, "_rocm_unified_memory_gpu_ids", staticmethod(lambda: {1})+ )+ monkeypatch.setattr(+ LlamaCppBackend, "_available_system_memory_mib", staticmethod(lambda: 60000)+ )+ return _fake_torch(+ [+ _device("gfx1030", free_mib = 12049),+ _device("gfx1151", free_mib = 40000, is_integrated = 1),+ ],+ vendor = "amd",+ )++ def test_a_fit_owned_narrowing_withdraws_it(self, tmp_path, monkeypatch, probe_env):+ torch = self._apu_and_dgpu(monkeypatch)+ launches = _run_auto_load(+ monkeypatch,+ tmp_path,+ torch,+ GFX103X, # covers the dGPU, not the gfx1151 APU+ returncode = None,+ model_bytes = 400 * 1024**3,+ )+ assert len(launches) == 1+ _cmd, env = launches[0]+ assert _visibility(env) == {"ROCR_VISIBLE_DEVICES": "0", "CUDA_VISIBLE_DEVICES": "0"}+ assert "GGML_CUDA_ENABLE_UNIFIED_MEMORY" not in env++ def test_an_inherited_user_value_still_stands(self, tmp_path, monkeypatch, probe_env):+ """Ownership, not presence: the withdrawal only takes back what this+ launch set, so a deliberate user value survives the narrowing."""+ torch = self._apu_and_dgpu(monkeypatch)+ launches = _run_auto_load(+ monkeypatch,+ tmp_path,+ torch,+ GFX103X,+ returncode = None,+ model_bytes = 400 * 1024**3,+ env_extra = {"GGML_CUDA_ENABLE_UNIFIED_MEMORY": "1"},+ )+ _cmd, env = launches[0]+ assert env.get("GGML_CUDA_ENABLE_UNIFIED_MEMORY") == "1"++ def test_a_surviving_apu_keeps_it(self, tmp_path, monkeypatch, probe_env):+ """The withdrawal is scoped to a narrowing that leaves only discrete+ cards; an APU that survives the gate still wants the shared pool."""+ _apply_os(monkeypatch, "linux", is_rocm = True)+ monkeypatch.setattr(+ LlamaCppBackend, "_rocm_unified_memory_gpu_ids", staticmethod(lambda: {0})+ )+ monkeypatch.setattr(+ LlamaCppBackend, "_available_system_memory_mib", staticmethod(lambda: 60000)+ )+ torch = _fake_torch(+ [+ _device("gfx1151", free_mib = 40000, is_integrated = 1),+ _device("gfx1200", free_mib = 12049),+ ],+ vendor = "amd",+ )+ launches = _run_auto_load(+ monkeypatch,+ tmp_path,+ torch,+ ["gfx1151"], # covers the APU, not the gfx1200 dGPU+ returncode = None,+ model_bytes = 400 * 1024**3,+ )+ _cmd, env = launches[0]+ assert _visibility(env) == {"ROCR_VISIBLE_DEVICES": "0", "CUDA_VISIBLE_DEVICES": "0"}+ assert env.get("GGML_CUDA_ENABLE_UNIFIED_MEMORY") == "1"+++class TestGatedNarrowingDropsDeadTensorMode:+ """The proactive twin of TestArchCrashRetryDropsDeadTensorMode. Manual mode+ admits tensor parallelism on the FULL device count, so the survivor pin can leave+ one device running ``--split-mode tensor`` -- a no-op /status still advertises+ and that arms the MTP watchdog. ``_without_tensor_split`` takes only the ratio."""++ def _narrowed_tensor_load(+ self,+ monkeypatch,+ tmp_path,+ targets,+ *,+ devices,+ capture = None,+ ):+ _apply_os(monkeypatch, "linux", is_rocm = True)+ torch = _fake_torch(devices, vendor = "amd")+ return _run_auto_load(+ monkeypatch,+ tmp_path,+ torch,+ targets,+ returncode = None,+ capture = capture,+ intent_kwargs = {+ "gpu_memory_mode": "manual",+ "gpu_layers": 20,+ "tensor_parallel": True,+ },+ )++ def test_one_survivor_drops_split_mode_tensor(self, tmp_path, monkeypatch, probe_env):+ capture: dict = {}+ launches = self._narrowed_tensor_load(+ monkeypatch,+ tmp_path,+ GFX103X, # covers the dGPU, not the gfx1036 iGPU+ devices = [+ _device("gfx1030", free_mib = 12049),+ _device("gfx1036", free_mib = 12176),+ ],+ capture = capture,+ )+ assert len(launches) == 1+ cmd, env = launches[0]+ assert _visibility(env) == {"ROCR_VISIBLE_DEVICES": "0", "CUDA_VISIBLE_DEVICES": "0"}+ assert "--split-mode" not in cmd and "-sm" not in cmd+ # /status must not advertise a mode one device cannot be running.+ assert capture["backend"]._tensor_parallel is False++ def test_two_survivors_keep_it(self, tmp_path, monkeypatch, probe_env):+ """Scoped to a narrowing that leaves ONE card, not to every narrowing:+ two survivors still split by tensor."""+ capture: dict = {}+ launches = self._narrowed_tensor_load(+ monkeypatch,+ tmp_path,+ GFX103X, # covers 0 and 1, not the gfx1036 iGPU+ devices = [+ _device("gfx1030", free_mib = 12049),+ _device("gfx1031", free_mib = 12176),+ _device("gfx1036", free_mib = 30000),+ ],+ capture = capture,+ )+ cmd, env = launches[0]+ assert _visibility(env) == {"ROCR_VISIBLE_DEVICES": "0,1", "CUDA_VISIBLE_DEVICES": "0,1"}+ assert cmd[cmd.index("--split-mode") + 1] == "tensor"+ assert capture["backend"]._tensor_parallel is True+++class TestGatedNarrowingRechecksTheApuRamGuard:+ """The proactive twin of TestArchCrashRetryRechecksTheApuRamGuard, other+ direction. The preflight runs with ``gpu_indices`` None on an unpinned launch, so+ an uncovered APU anywhere on the host prices the load -- while the gate hands the+ child only the discrete survivor, whose VRAM the weights fit. Refusing there+ rejects a load that would have run (#7624)."""++ def _apu_and_dgpu(+ self,+ monkeypatch,+ *,+ avail_mib = 8000,+ ):+ _apply_os(monkeypatch, "linux", is_rocm = True)+ monkeypatch.setattr(+ LlamaCppBackend, "_rocm_unified_memory_gpu_ids", staticmethod(lambda: {1})+ )+ monkeypatch.setattr(+ LlamaCppBackend, "_available_system_memory_mib", staticmethod(lambda: avail_mib)+ )+ return _fake_torch(+ [+ _device("gfx1030", free_mib = 12049),+ _device("gfx1151", free_mib = 40000, is_integrated = 1),+ ],+ vendor = "amd",+ )++ @staticmethod+ def _shortfall_stub(calls):+ # Counted, not raised: this runs inside the launch path's own+ # except-Exception arms, which would swallow an AssertionError.+ def _shortfall(model_size_bytes, avail_mib, *_a, **_kw):+ calls.append((model_size_bytes, avail_mib))+ return "This model needs about 20 GB but only about 8 GB of memory is available."++ return _shortfall++ def test_a_discrete_survivor_waives_the_refusal(self, tmp_path, monkeypatch, probe_env):+ torch = self._apu_and_dgpu(monkeypatch)+ calls: list = []+ capture: dict = {}+ launches = _run_auto_load(+ monkeypatch,+ tmp_path,+ torch,+ GFX103X, # covers the dGPU, not the gfx1151 APU+ returncode = None,+ model_bytes = 20 * 1024**3,+ capture = capture,+ apu_ram_stub = self._shortfall_stub(calls),+ )+ assert len(calls) == 1, f"the RAM guard ran {len(calls)} times, expected once"+ assert capture.get("error") is None, capture.get("error")+ assert len(launches) == 1, "the load was refused for a device it never uses"+ _cmd, env = launches[0]+ assert _visibility(env) == {"ROCR_VISIBLE_DEVICES": "0", "CUDA_VISIBLE_DEVICES": "0"}++ def test_a_surviving_apu_still_refuses(self, tmp_path, monkeypatch, probe_env):+ """The waiver is scoped to survivors that are all discrete. A build+ covering both cards leaves the APU in play, so the refusal stands."""+ torch = self._apu_and_dgpu(monkeypatch)+ calls: list = []+ capture: dict = {}+ launches = _run_auto_load(+ monkeypatch,+ tmp_path,+ torch,+ [*GFX103X, "gfx1151"],+ returncode = None,+ model_bytes = 20 * 1024**3,+ capture = capture,+ apu_ram_stub = self._shortfall_stub(calls),+ )+ assert len(calls) == 1, f"the RAM guard ran {len(calls)} times, expected once"+ assert launches == [], "an oversized APU load reached the child"+ assert "only about 8 GB" in str(capture.get("error"))++ def test_the_forced_cpu_host_still_refuses(self, tmp_path, monkeypatch, probe_env):+ """Every card gated out means the weights load into system RAM after all,+ so the guard the gate has no survivor to answer with keeps its refusal."""+ torch = self._apu_and_dgpu(monkeypatch)+ calls: list = []+ capture: dict = {}+ launches = _run_auto_load(+ monkeypatch,+ tmp_path,+ torch,+ GFX120X, # covers neither card+ returncode = None,+ model_bytes = 20 * 1024**3,+ capture = capture,+ apu_ram_stub = self._shortfall_stub(calls),+ )+ assert len(calls) == 1, f"the RAM guard ran {len(calls)} times, expected once"+ assert launches == [], "an oversized CPU-bound load reached the child"+ assert "only about 8 GB" in str(capture.get("error"))+++class TestArchCrashRetryOntoAnApu:+ """The mirror of TestArchCrashRetryEnv (#7624). A markerless mixed host can as+ easily crash on the DISCRETE card and land on the APU, where the first launch+ correctly left GGML_CUDA_ENABLE_UNIFIED_MEMORY unset -- so handling only the+ withdrawal direction respawns onto a shared pool without the setting+ _amd_apu_wants_unified_memory says it needs. Mock-based, no ROCm here."""++ def _dgpu_then_apu(self, monkeypatch):+ # Device 1 is the APU, so the free-VRAM rank pins the dGPU first and the+ # retry's prefer-never-selected branch hands back exactly the APU.+ _apply_os(monkeypatch, "linux", is_rocm = True)+ monkeypatch.setattr(+ LlamaCppBackend, "_rocm_unified_memory_gpu_ids", staticmethod(lambda: {1})+ )+ monkeypatch.setattr(+ LlamaCppBackend, "_available_system_memory_mib", staticmethod(lambda: 60000)+ )+ return _fake_torch(+ [+ _device("gfx1030", free_mib = 40000),+ _device("gfx1151", free_mib = 12000, is_integrated = 1),+ ],+ vendor = "amd",+ )++ def test_retry_onto_an_apu_sets_unified_memory_env(self, tmp_path, monkeypatch, probe_env):+ torch = self._dgpu_then_apu(monkeypatch)+ launches = _run_auto_load(+ monkeypatch,+ tmp_path,+ torch,+ None, # no marker: the proactive gate fails open, so the crash path runs+ returncode = 1,+ output = "ROCm error: device kernel image is invalid",+ )+ assert "GGML_CUDA_ENABLE_UNIFIED_MEMORY" not in launches[0][1]+ _retry = [env for _c, env in launches if env.get("ROCR_VISIBLE_DEVICES") == "1"]+ assert _retry, "the arch-crash retry did not fire"+ assert all(env.get("GGML_CUDA_ENABLE_UNIFIED_MEMORY") == "1" for env in _retry)+++class TestArchCrashRetryDropsDeadTensorMode:+ """Narrowing to one device makes --split-mode tensor a no-op still REPORTED as+ active: tensor_parallel drives the UI and the MTP crash watchdog. Dropping+ --tensor-split alone left both behind (#7624)."""++ def test_a_single_gpu_retry_drops_split_mode_tensor(self, tmp_path, monkeypatch, probe_env):+ _apply_os(monkeypatch, "linux", is_rocm = True)+ # Both cards are selected for the tensor split, so the retry cannot prefer+ # an unselected device and falls back to dropping the unified-memory one.+ monkeypatch.setattr(+ LlamaCppBackend, "_rocm_unified_memory_gpu_ids", staticmethod(lambda: {0})+ )+ monkeypatch.setattr(+ LlamaCppBackend, "_available_system_memory_mib", staticmethod(lambda: 60000)+ )+ torch = _fake_torch(+ [+ _device("gfx1151", free_mib = 40000, is_integrated = 1),+ _device("gfx1030", free_mib = 30000),+ ],+ vendor = "amd",+ )+ launches = _run_auto_load(+ monkeypatch,+ tmp_path,+ torch,+ None,+ returncode = 1,+ output = "ROCm error: device kernel image is invalid",+ intent_kwargs = {"tensor_parallel": True},+ )+ _retry = [cmd for cmd, env in launches if env.get("ROCR_VISIBLE_DEVICES") == "1"]+ assert _retry, "the arch-crash retry did not fire"+ for cmd in _retry:+ _modes = [+ cmd[i + 1]+ for i, tok in enumerate(cmd)+ if tok in ("--split-mode", "-sm") and i + 1 < len(cmd)+ ]+ assert "tensor" not in _modes, f"the narrowed respawn kept tensor mode: {cmd}"++ def test_the_retry_records_what_it_normalized(self, tmp_path, monkeypatch, probe_env):+ """The reactive path keeps the same record the proactive gate does: a markerless+ build only ever reaches the gate reactively, so without it every identical Apply+ reads the normalized server as new."""+ _apply_os(monkeypatch, "linux", is_rocm = True)+ monkeypatch.setattr(+ LlamaCppBackend, "_rocm_unified_memory_gpu_ids", staticmethod(lambda: {0})+ )+ monkeypatch.setattr(+ LlamaCppBackend, "_available_system_memory_mib", staticmethod(lambda: 60000)+ )+ capture: dict = {}+ _run_auto_load(+ monkeypatch,+ tmp_path,+ _fake_torch(+ [+ _device("gfx1151", free_mib = 40000, is_integrated = 1),+ _device("gfx1030", free_mib = 30000),+ ],+ vendor = "amd",+ ),+ None, # markerless: only the reactive retry can help+ returncode = 1,+ output = "ROCm error: device kernel image is invalid",+ capture = capture,+ intent_kwargs = {"tensor_parallel": True},+ )+ backend = capture["backend"]+ assert backend._tensor_parallel is False # normalized by the retry+ assert backend._arch_gate_dropped_tensor_parallel is True # and recorded+++class TestArchCrashRetryRechecksTheApuRamGuard:+ """The APU RAM preflight runs once, against the FIRST spawn's selection. On the+ mirror shape (crash on the dGPU, retry on the unified-memory sibling) the respawn+ is the first launch onto system RAM and skipped the guard entirely, so an+ oversized GGUF was OOM-killed mid-load instead of getting the refusal the same+ host gives when the APU is picked first (#7624). Mock-based, no ROCm here."""++ def _dgpu_then_apu(self, monkeypatch):+ # Device 1 is the APU, so the free-VRAM rank pins the dGPU first and the+ # retry's prefer-never-selected branch hands back exactly the APU.+ _apply_os(monkeypatch, "linux", is_rocm = True)+ monkeypatch.setattr(+ LlamaCppBackend, "_rocm_unified_memory_gpu_ids", staticmethod(lambda: {1})+ )+ monkeypatch.setattr(+ LlamaCppBackend, "_available_system_memory_mib", staticmethod(lambda: 8000)+ )+ return _fake_torch(+ [+ _device("gfx1030", free_mib = 40000),+ _device("gfx1151", free_mib = 12000, is_integrated = 1),+ ],+ vendor = "amd",+ )++ def test_an_oversized_model_is_refused_instead_of_respawned(+ self, tmp_path, monkeypatch, probe_env+ ):+ torch = self._dgpu_then_apu(monkeypatch)+ # Counted, not raised: this runs inside the launch path's own+ # except-Exception arms, which would swallow an AssertionError and leave+ # the test green on a guard that never ran.+ calls: list = []++ def _shortfall(model_size_bytes, avail_mib, *_a, **_kw):+ calls.append((model_size_bytes, avail_mib))+ return "This model needs about 20 GB but only about 8 GB is available."++ capture: dict = {}+ launches = _run_auto_load(+ monkeypatch,+ tmp_path,+ torch,+ None, # no marker: the proactive gate fails open, so the crash path runs+ returncode = 1,+ output = "ROCm error: device kernel image is invalid",+ model_bytes = 20 * 1024**3,+ capture = capture,+ apu_ram_stub = _shortfall,+ )+ # The dGPU is pinned first, so the pre-launch guard never asks (it is+ # gated on the selection wanting unified memory) and the crash happens.+ assert launches, "the first spawn never ran"+ assert all(+ env.get("ROCR_VISIBLE_DEVICES") != "1" for _c, env in launches+ ), "the retry respawned onto the APU without the RAM preflight"+ assert len(calls) == 1, f"the RAM guard ran {len(calls)} times, expected once"+ assert calls[0][0] == 20 * 1024**3+ assert "only about 8 GB" in str(capture.get("error"))++ def test_a_model_that_fits_still_retries_onto_the_apu(self, tmp_path, monkeypatch, probe_env):+ """The guard refuses a shortfall, it does not block the fallback. With+ room to spare the retry runs exactly as before."""+ torch = self._dgpu_then_apu(monkeypatch)+ calls: list = []++ def _no_shortfall(model_size_bytes, avail_mib, *_a, **_kw):+ calls.append((model_size_bytes, avail_mib))+ return None++ launches = _run_auto_load(+ monkeypatch,+ tmp_path,+ torch,+ None,+ returncode = 1,+ output = "ROCm error: device kernel image is invalid",+ model_bytes = 1024,+ apu_ram_stub = _no_shortfall,+ )+ assert len(calls) == 1, f"the RAM guard ran {len(calls)} times, expected once"+ _retry = [env for _c, env in launches if env.get("ROCR_VISIBLE_DEVICES") == "1"]+ assert _retry, "the arch-crash retry did not fire"+ assert all(env.get("GGML_CUDA_ENABLE_UNIFIED_MEMORY") == "1" for env in _retry)+++class TestHsaOverrideGfxVersion:+ """``HSA_OVERRIDE_GFX_VERSION`` is the long-standing AMD workaround for an arch+ the ROCm stack does not build for: the user sets it, ROCr reports the SPOOFED+ arch, and code compiled for it really does run on the card. The gate reads the+ arch through the same device properties HIP will act on, so it sees the override+ too. Pinned because this is the shape most likely to read as "your fix broke my+ working setup": raw silicon uncovered, presented arch covered, and the launch has+ to follow the presented one."""++ def test_a_spoofed_arch_is_gated_on_what_the_runtime_reports(+ self, tmp_path, monkeypatch, probe_env+ ):+ _apply_os(monkeypatch, "linux", is_rocm = True)+ monkeypatch.setenv("HSA_OVERRIDE_GFX_VERSION", "10.3.0")+ _binary_with_marker(tmp_path, {"mapped_targets": GFX103X})+ # A gfx1035 laptop iGPU presenting itself as gfx1030 under the override,+ # beside a card the bundle does not cover at all.+ monkeypatch.setitem(+ sys.modules,+ "torch",+ _fake_torch(+ [_device("gfx1030", free_mib = 8000), _device("gfx1036", free_mib = 30000)],+ vendor = "amd",+ ),+ )+ assert LlamaCppBackend._get_gpu_free_memory(+ binary = str(tmp_path / "build" / "bin" / "llama-server"), for_llama_server = True+ ) == [(0, 8000)]+++class TestAnInstallFromBeforeThisPr:+ """An install written by an older Studio has no ``mapped_targets``, and the+ fingerprint deliberately does not cover the field, so it is never refreshed for+ that reason alone. Such a host must behave EXACTLY as it did before the PR: the+ fix arrives with the next llama.cpp update, and until then nothing may change,+ least of all a drop to CPU."""++ OLD_MARKER = {+ "release_tag": "b10107",+ "asset": "app-b10107-windows-x64-rocm-gfx110X.zip",+ "install_kind": "app",+ "bundle_profile": "rocm",+ "runtime_line": "rocm",+ "coverage_class": "gfx110X",+ "install_fingerprint": "unchanged-by-this-pr",+ "installed_at_utc": "2026-07-01T00:00:00Z",+ }++ def test_the_probe_keeps_every_device(self, tmp_path, monkeypatch, probe_env):+ _apply_os(monkeypatch, "linux", is_rocm = True)+ # The APU's usable figure is its shared pool minus a host reserve, and the+ # pool is capped by the REAL free system RAM unless this is stubbed. Without+ # it the expected 11152 silently assumes the machine has >12176MiB free, so+ # the test passes on a large runner and fails on a small one (measured: it+ # failed inside a WSL VM at 7340->6316MiB). Same stub as the sibling below.+ monkeypatch.setattr(+ LlamaCppBackend, "_available_system_memory_mib", staticmethod(lambda: 60000)+ )+ (tmp_path / "UNSLOTH_PREBUILT_INFO.json").write_text(+ json.dumps(self.OLD_MARKER), encoding = "utf-8"+ )+ monkeypatch.setitem(+ sys.modules,+ "torch",+ _fake_torch(+ [+ _device("gfx1101", free_mib = 12049),+ _device("gfx1036", free_mib = 12176, is_integrated = 1),+ ],+ vendor = "amd",+ ),+ )+ assert LlamaCppBackend._get_gpu_free_memory(+ binary = str(tmp_path / "build" / "bin" / "llama-server"), for_llama_server = True+ ) == [(0, 12049), (1, 11152)]++ def test_the_launch_is_not_masked_onto_the_cpu(self, tmp_path, monkeypatch, probe_env):+ """The failure that would matter most: an old install that used to run+ on the GPU being gated to CPU by a marker the gate cannot read."""+ _apply_os(monkeypatch, "linux", is_rocm = True)+ monkeypatch.setattr(+ LlamaCppBackend, "_available_system_memory_mib", staticmethod(lambda: 60000)+ )+ (tmp_path / "UNSLOTH_PREBUILT_INFO.json").write_text(+ json.dumps(self.OLD_MARKER), encoding = "utf-8"+ )+ launches = _run_auto_load(+ monkeypatch,+ tmp_path,+ _fake_torch(+ [+ _device("gfx1101", free_mib = 12049),+ _device("gfx1036", free_mib = 30000, is_integrated = 1),+ ],+ vendor = "amd",+ ),+ None, # the marker above stands; do not overwrite it+ returncode = None,+ )+ assert len(launches) == 1+ _cmd, env = launches[0]+ assert env.get("HIP_VISIBLE_DEVICES") != "-1", "an old install was gated onto the CPU"+ # Pre-PR placement, reproduced: the shared-pool iGPU still outranks the dGPU+ # (#7669) until the install is refreshed. CUDA_VISIBLE_DEVICES is 0 because+ # ROCr re-indexes the visible agents from zero; the physical pick is ROCR's.+ assert _visibility(env) == {"ROCR_VISIBLE_DEVICES": "1", "CUDA_VISIBLE_DEVICES": "0"}+++class TestArchForcedCpuFlagLifecycle:+ """``_arch_gate_forced_cpu`` drives ``holds_no_vram``, so it has to be+ per-load state: a CPU-masked launch that kept the flag would go on claiming+ zero VRAM for the GPU load that replaces it."""++ def _host(self):+ return [+ _device("gfx1101", free_mib = 12049),+ _device("gfx1036", free_mib = 30000, is_integrated = 1),+ ]++ def test_every_device_uncovered_sets_it(self, tmp_path, monkeypatch, probe_env):+ _apply_os(monkeypatch, "linux", is_rocm = True)+ monkeypatch.setattr(+ LlamaCppBackend, "_available_system_memory_mib", staticmethod(lambda: 60000)+ )+ capture: dict = {}+ _run_auto_load(+ monkeypatch,+ tmp_path,+ _fake_torch(self._host(), vendor = "amd"),+ GFX103X, # covers neither card+ returncode = None,+ capture = capture,+ )+ backend = capture["backend"]+ assert backend._arch_gate_forced_cpu is True+ # The GPU arbiter reads this: a child masked onto the CPU must not keep+ # the CHAT claim or block an image/video pipeline.+ assert backend.holds_no_vram is True++ def test_a_covered_card_leaves_it_alone(self, tmp_path, monkeypatch, probe_env):+ _apply_os(monkeypatch, "linux", is_rocm = True)+ monkeypatch.setattr(+ LlamaCppBackend, "_available_system_memory_mib", staticmethod(lambda: 60000)+ )+ capture: dict = {}+ _run_auto_load(+ monkeypatch,+ tmp_path,+ _fake_torch(self._host(), vendor = "amd"),+ GFX110X, # the dGPU survives+ returncode = None,+ capture = capture,+ )+ backend = capture["backend"]+ assert backend._arch_gate_forced_cpu is False+ assert backend.holds_no_vram is False++ def test_unload_clears_it(self):+ backend = LlamaCppBackend()+ backend._arch_gate_forced_cpu = True+ backend.unload_model()+ assert backend._arch_gate_forced_cpu is False+++class TestTheForcedCpuFlagIsNotSticky:+ """``load_model`` phase 1 only kills the old process, so per-load state only ever+ set TRUE outlives the launch that set it. The dangerous direction for this flag:+ a host that gains coverage (a llama.cpp update, or just the next model) would+ report a VRAM-holding server as holding none, and the arbiter leave it unclaimed+ beside a competing workload."""++ def _load(self, monkeypatch, tmp_path, targets, capture):+ _apply_os(monkeypatch, "linux", is_rocm = True)+ monkeypatch.setattr(+ LlamaCppBackend, "_available_system_memory_mib", staticmethod(lambda: 60000)+ )+ return _run_auto_load(+ monkeypatch,+ tmp_path,+ _fake_torch(+ [+ _device("gfx1101", free_mib = 12049),+ _device("gfx1036", free_mib = 30000, is_integrated = 1),+ ],+ vendor = "amd",+ ),+ targets,+ returncode = None,+ capture = capture,+ )++ def test_a_covered_load_after_a_gated_one_clears_it(self, tmp_path, monkeypatch, probe_env):+ """The llama.cpp-update shape: the SAME backend instance loads again on+ a build that now covers the dGPU, with no unload in between (load_model+ phase 1 only kills the process)."""+ gated: dict = {}+ self._load(monkeypatch, tmp_path, GFX103X, gated) # covers neither card+ assert gated["backend"]._arch_gate_forced_cpu is True++ covered: dict = {}+ second = tmp_path / "second"+ second.mkdir()+ self._load(monkeypatch, second, GFX110X, covered)+ # Carry the stale flag onto the instance the second load ran on: the+ # harness builds a fresh backend per drive, so without this the assert+ # would pass on a default rather than on the publish.+ backend = covered["backend"]+ assert backend._arch_gate_forced_cpu is False+ assert backend.holds_no_vram is False++ def test_the_publish_overwrites_a_stale_true(self, tmp_path, monkeypatch, probe_env):+ """The mutation the class exists for, on one instance: pre-set the flag,+ run a covered load, and the launch must publish False over it."""+ _apply_os(monkeypatch, "linux", is_rocm = True)+ monkeypatch.setattr(+ LlamaCppBackend, "_available_system_memory_mib", staticmethod(lambda: 60000)+ )+ _real_init = LlamaCppBackend.__init__++ def _init_with_stale_flag(self, *args, **kwargs):+ _real_init(self, *args, **kwargs)+ self._arch_gate_forced_cpu = True++ monkeypatch.setattr(LlamaCppBackend, "__init__", _init_with_stale_flag)+ covered: dict = {}+ self._load(monkeypatch, tmp_path, GFX110X, covered)+ assert covered["backend"]._arch_gate_forced_cpu is False+ assert covered["backend"].holds_no_vram is False++ def test_the_diffusion_state_path_clears_it(self):+ """A diffusion runner does hold VRAM, and its state block already resets+ the sibling chat fields for exactly this reason."""+ source = (+ Path(__file__).resolve().parent.parent / "core" / "inference" / "llama_cpp.py"+ ).read_text(encoding = "utf-8")+ block = source.split("Diffusion is never tensor-parallel")[1].split("def ")[0]+ assert "self._arch_gate_forced_cpu = False" in block++ def test_the_flag_is_published_not_only_set(self):+ """Source-level, because the miss was structural: a branch that only+ assigns True can never clear a previous launch's value."""+ source = (+ Path(__file__).resolve().parent.parent / "core" / "inference" / "llama_cpp.py"+ ).read_text(encoding = "utf-8")+ assert "self._arch_gate_forced_cpu = bool(_arch_gate_forced_cpu)" in source+ assert "self._arch_gate_forced_cpu = True" not in source+++class TestInheritedSplitEnvGoesWithTheArgvStrip:+ """LLAMA_ARG_SPLIT_MODE / LLAMA_ARG_TENSOR_SPLIT are the env spelling of+ --split-mode / --tensor-split, so dropping the tokens alone leaves the inherited+ value in force -- and the forced-CPU arm strips --split-mode precisely because a+ tensor split aborts a child with no visible device."""++ def _host(self):+ return [+ _device("gfx1101", free_mib = 12049),+ _device("gfx1036", free_mib = 30000, is_integrated = 1),+ ]++ def test_the_forced_cpu_launch_clears_both(self, tmp_path, monkeypatch, probe_env):+ _apply_os(monkeypatch, "linux", is_rocm = True)+ monkeypatch.setattr(+ LlamaCppBackend, "_available_system_memory_mib", staticmethod(lambda: 60000)+ )+ launches = _run_auto_load(+ monkeypatch,+ tmp_path,+ _fake_torch(self._host(), vendor = "amd"),+ GFX103X, # covers neither card+ returncode = None,+ # Split mode unset on purpose. The existing tensor->layer+ # reconciliation only clears the pair when an inherited mode is+ # present and non-layer, so this is the shape that survives it.+ env_extra = {"LLAMA_ARG_TENSOR_SPLIT": "3,1"},+ )+ assert len(launches) == 1+ cmd, env = launches[0]+ assert "LLAMA_ARG_TENSOR_SPLIT" not in env+ assert "--split-mode" not in cmd and "--tensor-split" not in cmd+ assert env.get("HIP_VISIBLE_DEVICES") == "-1"++ def test_an_inherited_tensor_mode_cannot_survive_the_forced_cpu_strip(+ self, tmp_path, monkeypatch, probe_env+ ):+ """The abort this strip prevents: llama.cpp fails the load with+ "LLAMA_SPLIT_MODE_TENSOR needs >= 1 devices" once the mask hides every device,+ and an inherited tensor mode reinstates it after the argv flag is gone."""+ _apply_os(monkeypatch, "linux", is_rocm = True)+ monkeypatch.setattr(+ LlamaCppBackend, "_available_system_memory_mib", staticmethod(lambda: 60000)+ )+ launches = _run_auto_load(+ monkeypatch,+ tmp_path,+ _fake_torch(self._host(), vendor = "amd"),+ GFX103X, # covers neither card+ returncode = None,+ intent_kwargs = {"tensor_parallel": True},+ env_extra = {"LLAMA_ARG_SPLIT_MODE": "tensor"},+ )+ assert launches+ cmd, env = launches[0]+ assert "LLAMA_ARG_SPLIT_MODE" not in env+ assert "--split-mode" not in cmd++ def test_the_narrowed_pin_clears_both(self, tmp_path, monkeypatch, probe_env):+ """A survivor pin re-indexes the visible devices, so an inherited+ positional ratio would land on the wrong card."""+ _apply_os(monkeypatch, "linux", is_rocm = True)+ monkeypatch.setattr(+ LlamaCppBackend, "_available_system_memory_mib", staticmethod(lambda: 60000)+ )+ monkeypatch.setattr(+ LlamaCppBackend, "_arch_gate_survivors", staticmethod(lambda _b = None: [0])+ )+ launches = _run_auto_load(+ monkeypatch,+ tmp_path,+ _fake_torch(self._host(), vendor = "amd"),+ GFX110X,+ returncode = None,+ model_bytes = 400 * 1024**3, # too large to place: --fit on owns it+ env_extra = {"LLAMA_ARG_TENSOR_SPLIT": "3,1"},+ )+ assert launches+ _cmd, env = launches[0]+ assert "LLAMA_ARG_TENSOR_SPLIT" not in env++ def test_an_ordinary_load_keeps_them(self, tmp_path, monkeypatch, probe_env):+ """Only the gate's own branches clear these. An unrelated launch must+ not lose an inherited setting the existing reconciliation allows."""+ _apply_os(monkeypatch, "linux", is_rocm = True)+ monkeypatch.setattr(+ LlamaCppBackend, "_available_system_memory_mib", staticmethod(lambda: 60000)+ )+ launches = _run_auto_load(+ monkeypatch,+ tmp_path,+ _fake_torch([_device("gfx1101", free_mib = 20000)], vendor = "amd"),+ GFX110X, # covers the only card: nothing to narrow+ returncode = None,+ env_extra = {"LLAMA_ARG_TENSOR_SPLIT": "3,1"},+ )+ assert launches+ _cmd, env = launches[0]+ assert env.get("LLAMA_ARG_TENSOR_SPLIT") == "3,1"+++class TestTheForcedCpuLaunchAppliesThePageLock:+ """The gate masks every device away, so the child runs from host RAM, but+ ``_weights_in_host_memory`` answered for the ORIGINAL placement, where a manual full+ offload onto discrete cards reads as not host-resident. Left alone the page-lock is+ skipped AND recorded as deliberate, which no relaunch undoes."""++ def _run(self, tmp_path, monkeypatch, *, targets):+ _apply_os(monkeypatch, "linux", is_rocm = True)+ monkeypatch.setattr(+ LlamaCppBackend, "_available_system_memory_mib", staticmethod(lambda: 200000)+ )+ import utils.model_memory_settings as _mem_settings++ monkeypatch.setattr(_mem_settings, "get_model_memory_settings", lambda: (True, False))+ capture: dict = {}+ backend = LlamaCppBackend()+ # A known block count is what lets _offloads_every_layer answer True for the+ # manual maximum below; without it every launch reads as host-resident and the+ # skip this test is about could never happen.+ backend._n_layers = 32+ launches = _run_auto_load(+ monkeypatch,+ tmp_path,+ _fake_torch(+ # Two DISCRETE cards: _amd_apu_wants_unified_memory answers False, so+ # a full offload really does read as not host-resident.+ [+ _device("gfx1030", free_mib = 40000),+ _device("gfx1031", free_mib = 30000),+ ],+ vendor = "amd",+ ),+ targets,+ returncode = None,+ capture = capture,+ backend = backend,+ # Manual full offload: every layer on the GPU.+ intent_kwargs = {"gpu_memory_mode": "manual", "gpu_layers": 33}, # n_layers + 1+ )+ return launches, capture++ def test_the_masked_child_gets_the_lock(self, tmp_path, monkeypatch, probe_env):+ launches, capture = self._run(tmp_path, monkeypatch, targets = ["gfx908"])+ assert launches+ cmd, env = launches[0]+ assert env.get("HIP_VISIBLE_DEVICES") == "-1", _visibility(env)+ assert "--mlock" in cmd or "mmap+mlock" in " ".join(cmd), cmd+ assert capture["backend"]._memory_mlock_applicable is True++ def test_a_covered_host_still_skips_it(self, tmp_path, monkeypatch, probe_env):+ """The recompute is the gate's doing. With the cards covered the launch really+ is fully offloaded, so the pre-existing skip has to stand."""+ launches, capture = self._run(tmp_path, monkeypatch, targets = GFX103X)+ assert launches+ cmd, env = launches[0]+ assert env.get("HIP_VISIBLE_DEVICES") != "-1"+ assert "--mlock" not in cmd+ assert capture["backend"]._memory_mlock_applicable is False+++class TestForcedCpuNeedsRealArchEvidence:+ """``_get_gpu_memory`` turns any probe error into [], so "gated empty, ungated not"+ also describes a one-shot failure of the FIRST probe on a host the gate never+ filters. Masking that onto the CPU is a silent, permanent cliff, so the branch+ re-derives the gate's verdict instead of inferring it."""++ def _run(self, tmp_path, monkeypatch, *, targets, flaky):+ _apply_os(monkeypatch, "linux", is_rocm = True)+ real = LlamaCppBackend._get_gpu_memory+ calls = {"n": 0}++ def _probe(binary = None, *, for_llama_server = False):+ calls["n"] += 1+ if flaky and calls["n"] == 1:+ return [] # the transient failure, on the gated call+ return real(binary, for_llama_server = for_llama_server)++ monkeypatch.setattr(LlamaCppBackend, "_get_gpu_memory", staticmethod(_probe))+ capture: dict = {}+ _run_auto_load(+ monkeypatch,+ tmp_path,+ _fake_torch([_device("gfx1030", free_mib = 12049)], vendor = "amd"),+ targets,+ returncode = None,+ capture = capture,+ )+ return capture["backend"]++ def test_a_transient_probe_failure_does_not_force_cpu(self, tmp_path, monkeypatch, probe_env):+ """The marker covers the only card, so nothing was filtered: an empty gated+ result here is the probe, not the gate."""+ backend = self._run(tmp_path, monkeypatch, targets = GFX103X, flaky = True)+ assert backend._arch_gate_forced_cpu is False++ def test_an_unmarked_install_does_not_force_cpu(self, tmp_path, monkeypatch, probe_env):+ """No marker at all means unknown coverage, which the filter fails open on, so+ the gate cannot have emptied anything."""+ backend = self._run(tmp_path, monkeypatch, targets = None, flaky = True)+ assert backend._arch_gate_forced_cpu is False++ def test_a_genuinely_uncovered_host_still_forces_cpu(self, tmp_path, monkeypatch, probe_env):+ backend = self._run(tmp_path, monkeypatch, targets = ["gfx908"], flaky = False)+ assert backend._arch_gate_forced_cpu is True+++class TestTheApuRetryRecomputesThePageLock:+ """Residency is a property of the DEVICES, which the arch-crash retry changes:+ crash on the discrete card, land on the unified-memory APU, and the weights are+ host-backed after all, so the lock the first launch skipped is the one the user+ asked for. Left alone the respawn runs unlocked and records the missing lock as+ deliberate, deduping away the reload that would apply it."""++ def _dgpu_then_apu(self, monkeypatch):+ # The dGPU is picked first (more free VRAM after the APU host reserve),+ # then crashes; the APU is what remains.+ monkeypatch.setattr(+ LlamaCppBackend, "_rocm_unified_memory_gpu_ids", staticmethod(lambda: {1})+ )+ return _fake_torch(+ [+ # The dGPU wins the free-memory rank (the APU's shared pool is+ # reported minus the host reserve), so it is picked, crashes, and+ # the APU is what remains.+ _device("gfx1201", free_mib = 40000),+ _device("gfx1151", free_mib = 30000, is_integrated = 1),+ ],+ vendor = "amd",+ )++ def _run(self, tmp_path, monkeypatch, *, mlock):+ _apply_os(monkeypatch, "linux", is_rocm = True)+ monkeypatch.setattr(+ LlamaCppBackend, "_available_system_memory_mib", staticmethod(lambda: 200000)+ )+ import utils.model_memory_settings as _mem_settings++ # (keep_resident, no_ram_reserve): both should_mlock and+ # apply_model_memory_policy read this one snapshot.+ monkeypatch.setattr(_mem_settings, "get_model_memory_settings", lambda: (mlock, False))++ capture: dict = {}+ launches = _run_auto_load(+ monkeypatch,+ tmp_path,+ self._dgpu_then_apu(monkeypatch),+ None, # markerless: only the reactive retry can help+ returncode = 1,+ output = "ROCm error: device kernel image is invalid",+ capture = capture,+ )+ return launches, capture++ def test_the_respawn_onto_the_apu_gets_the_lock(self, tmp_path, monkeypatch, probe_env):+ launches, capture = self._run(tmp_path, monkeypatch, mlock = True)+ retry = [(cmd, env) for cmd, env in launches if env.get("ROCR_VISIBLE_DEVICES") == "1"]+ assert (+ retry+ ), f"the arch-crash retry never targeted the APU: {[_visibility(e) for _c, e in launches]}"+ cmd, _env = retry[0]+ assert "--mlock" in cmd or "mmap+mlock" in " ".join(cmd), cmd+ # And the record agrees with the child, or the reload that would apply+ # the policy is deduplicated away.+ assert capture["backend"]._memory_mlock_applicable is True++ def test_page_locking_off_changes_nothing(self, tmp_path, monkeypatch, probe_env):+ launches, _capture = self._run(tmp_path, monkeypatch, mlock = False)+ assert launches+ for cmd, _env in launches:+ assert "--mlock" not in cmd++ def test_the_users_own_extra_args_survive_the_recompute(self, tmp_path, monkeypatch, probe_env):+ """The recompute may only ADD the lock: taking the crashed launch's memory+ flags back off would mean scanning for --mlock / --no-mmap, valueless in+ llama.cpp's parser, so the scan drops the argv entry after them -- here the+ user's own -c 8192."""+ _apply_os(monkeypatch, "linux", is_rocm = True)+ monkeypatch.setattr(+ LlamaCppBackend, "_available_system_memory_mib", staticmethod(lambda: 200000)+ )+ import utils.model_memory_settings as _mem_settings++ monkeypatch.setattr(_mem_settings, "get_model_memory_settings", lambda: (True, False))+ capture: dict = {}+ launches = _run_auto_load(+ monkeypatch,+ tmp_path,+ self._dgpu_then_apu(monkeypatch),+ None,+ returncode = 1,+ output = "ROCm error: device kernel image is invalid",+ capture = capture,+ # --no-mmap is a memory flag apply_model_memory_policy keeps when it+ # emits the legacy --mlock (this build reports no --load-mode), and+ # -c 8192 is the entry a valueless-flag scan would eat with it.+ intent_kwargs = {"extra_args": ["--no-mmap", "-c", "8192"]},+ )+ retry = [(cmd, env) for cmd, env in launches if env.get("ROCR_VISIBLE_DEVICES") == "1"]+ assert retry, [_visibility(e) for _c, e in launches]+ cmd, _env = retry[0]+ assert "--no-mmap" in cmd, f"a user memory flag was stripped by the recompute: {cmd}"+ assert cmd[cmd.index("-c") + 1] == "8192", f"the extra after --no-mmap was eaten: {cmd}"+ assert "--mlock" in cmd, cmd+ # The record has to describe the argv actually launched, or the reload+ # comparator fights a child it already agrees with.+ assert capture["backend"]._memory_mlock_applicable is True+ assert capture["backend"]._memory_state[0] is True # (mlock, reserves_ram)diff --git a/studio/backend/tests/test_gpu_init_crash_message.py b/studio/backend/tests/test_gpu_init_crash_message.pyindex 2e04412dcc5..485febc2df7 100644--- a/studio/backend/tests/test_gpu_init_crash_message.py+++ b/studio/backend/tests/test_gpu_init_crash_message.py@@ -113,8 +113,8 @@ def _run_cpu_fallback_load(mmproj.write_bytes(b"projector")backend = LlamaCppBackend()- backend._get_gpu_memory = lambda _binary = None: []- backend._get_gpu_free_memory = lambda _binary = None: []+ backend._get_gpu_memory = lambda _binary = None, **_kw: []+ backend._get_gpu_free_memory = lambda _binary = None, **_kw: []backend._read_gguf_metadata = lambda _path: Nonebackend._can_estimate_kv = lambda: Falsebackend._get_gguf_size_bytes = lambda _path: 1024@@ -1198,8 +1198,8 @@ def test_terminal_signal_with_explicit_child_placement_does_not_replay(gguf.write_bytes(struct.pack("<IIQQ", 0x46554747, 3, 0, 1) + metadata)backend = LlamaCppBackend()- backend._get_gpu_memory = lambda _binary = None: [(0, 8_000, 16_000)]- backend._get_gpu_free_memory = lambda _binary = None: [(0, 8_000)]+ backend._get_gpu_memory = lambda _binary = None, **_kw: [(0, 8_000, 16_000)]+ backend._get_gpu_free_memory = lambda _binary = None, **_kw: [(0, 8_000)]backend._read_gguf_metadata = lambda _path: Nonebackend._can_estimate_kv = lambda: Falsebackend._get_gguf_size_bytes = lambda _path: 1024diff --git a/studio/backend/tests/test_gpu_memory_mode.py b/studio/backend/tests/test_gpu_memory_mode.pyindex dc78799ff0c..3c60c60eba5 100644--- a/studio/backend/tests/test_gpu_memory_mode.py+++ b/studio/backend/tests/test_gpu_memory_mode.py@@ -735,7 +735,7 @@ def test_remote_vulkan_diffusion_rejection_keeps_active_server(monkeypatch):killed = []monkeypatch.setattr(backend, "_find_llama_server_binary", lambda **_kwargs: "/bin/llama")monkeypatch.setattr(backend, "_is_vulkan_backend", lambda _binary = None: True)- monkeypatch.setattr(backend, "_get_gpu_memory", lambda _binary = None: [(0, 1024, 2048)])+ monkeypatch.setattr(backend, "_get_gpu_memory", lambda _binary = None, **_kw: [(0, 1024, 2048)])monkeypatch.setattr(backend,"_download_gguf",@@ -794,7 +794,9 @@ def test_remote_vulkan_preflight_download_failure_keeps_active_server(monkeypatcmonkeypatch.setattr(backend, "_find_llama_server_binary", lambda **_kwargs: "/bin/llama")monkeypatch.setattr(backend, "_is_vulkan_backend", lambda _binary = None: True)- monkeypatch.setattr(backend, "_get_gpu_memory", lambda _binary = None: [(0, 1024, 2048)])+ monkeypatch.setattr(+ backend, "_get_gpu_memory", lambda _binary = None, **_kw: [(0, 1024, 2048)]+ )monkeypatch.setattr(backend, "_download_gguf", _download)monkeypatch.setattr(backend, "_gguf_path_is_diffusion", lambda *_args: False)monkeypatch.setattr(backend, "_kill_process", lambda: order.append("kill"))@@ -826,7 +828,7 @@ def test_local_vulkan_diffusion_rejection_keeps_active_server(monkeypatch, tmp_pkilled = []monkeypatch.setattr(backend, "_find_llama_server_binary", lambda **_kwargs: "/bin/llama")monkeypatch.setattr(backend, "_is_vulkan_backend", lambda _binary = None: True)- monkeypatch.setattr(backend, "_get_gpu_memory", lambda _binary = None: [(0, 1024, 2048)])+ monkeypatch.setattr(backend, "_get_gpu_memory", lambda _binary = None, **_kw: [(0, 1024, 2048)])monkeypatch.setattr(backend, "_gguf_path_is_diffusion", lambda *_args: True)monkeypatch.setattr(backend, "_kill_process", lambda: killed.append(True))@@ -875,7 +877,7 @@ def _vulkan_pinned_backend(monkeypatch, killed: list) -> LlamaCppBackend:backend = LlamaCppBackend()monkeypatch.setattr(backend, "_find_llama_server_binary", lambda **_kwargs: "/bin/llama")monkeypatch.setattr(backend, "_is_vulkan_backend", lambda _binary = None: True)- monkeypatch.setattr(backend, "_get_gpu_memory", lambda _binary = None: [(0, 1024, 2048)])+ monkeypatch.setattr(backend, "_get_gpu_memory", lambda _binary = None, **_kw: [(0, 1024, 2048)])monkeypatch.setattr(backend, "_kill_process", lambda: killed.append(True))return backend@@ -1121,6 +1123,20 @@ def test_cpu_only_pin_keeps_hip_even_with_prefer_rocr(monkeypatch):assert "ROCR_VISIBLE_DEVICES" not in env+def test_cpu_only_pin_keeps_an_inherited_rocr_mask(monkeypatch):+ # The anti-stacking clear exists for a POSITIVE pin (ROCR re-indexes from 0,+ # then a non-zero HIP pin points out of range). "-1" hides every device+ # whatever ROCR says, so clearing it only re-exposes agents the parent hid to+ # the HSA enumeration that dies on an uncovered arch (#7624). Same rule the+ # embedding CPU launch follows.+ _rocm_torch_stub(monkeypatch)+ env = {"ROCR_VISIBLE_DEVICES": "1"}+ LlamaCppBackend._emit_child_gpu_visibility(env, "-1")+ assert env["HIP_VISIBLE_DEVICES"] == "-1"+ assert env["CUDA_VISIBLE_DEVICES"] == "-1"+ assert env["ROCR_VISIBLE_DEVICES"] == "1"++def _amd_sdk_torch_stub(monkeypatch):# AMD SDK wheel: torch.version.hip is None but __version__ encodes rocm.torch_stub = _types.ModuleType("torch")diff --git a/studio/backend/tests/test_llama_cpp_placement.py b/studio/backend/tests/test_llama_cpp_placement.pyindex bd851c28a19..2248651ba81 100644--- a/studio/backend/tests/test_llama_cpp_placement.py+++ b/studio/backend/tests/test_llama_cpp_placement.py@@ -85,8 +85,8 @@ def _write_gguf(path: Path, architecture: str = "llama") -> Path:def _backend(tmp_path: Path, *, vulkan: bool, memory):backend = LlamaCppBackend()gguf = _write_gguf(tmp_path / "model.gguf")- backend._get_gpu_memory = lambda _binary = None: list(memory)- backend._get_gpu_free_memory = lambda _binary = None: [+ backend._get_gpu_memory = lambda _binary = None, **_kw: list(memory)+ backend._get_gpu_free_memory = lambda _binary = None, **_kw: [(index, free) for index, free, _total in memory]backend._read_gguf_metadata = lambda _path: None@@ -339,7 +339,7 @@ def test_diffusion_does_not_reinterpret_vulkan_ordinals(tmp_path):backend = LlamaCppBackend()backend._find_llama_server_binary = lambda include_denied = False: "/fake/llama-server"backend._is_vulkan_backend = lambda _binary = None: True- backend._get_gpu_memory = lambda _binary = None: [(1, 8_000, 8_000)]+ backend._get_gpu_memory = lambda _binary = None, **_kw: [(1, 8_000, 8_000)]backend._download_gguf = lambda **kwargs: str(gguf)backend._read_gguf_metadata = lambda _path: setattr(backend, "_is_diffusion", True)backend._start_diffusion_server = lambda **kwargs: pytest.fail(diff --git a/studio/backend/tests/test_mtp_drafter_companion.py b/studio/backend/tests/test_mtp_drafter_companion.pyindex 92f9be76199..a07e86845c2 100644--- a/studio/backend/tests/test_mtp_drafter_companion.py+++ b/studio/backend/tests/test_mtp_drafter_companion.py@@ -2579,7 +2579,7 @@ def _dflash_fetch_during_auto_load(monkeypatch, *, supports_dspark, supports_dflseen: dict = {"dflash_fetched": False}monkeypatch.setattr(backend, "_find_llama_server_binary", lambda **_kwargs: "/bin/llama")monkeypatch.setattr(backend, "_is_vulkan_backend", lambda _binary = None: False)- monkeypatch.setattr(backend, "_get_gpu_memory", lambda _binary = None: [(0, 4096, 8192)])+ monkeypatch.setattr(backend, "_get_gpu_memory", lambda _binary = None, **_kw: [(0, 4096, 8192)])monkeypatch.setattr(backend, "_gguf_path_is_diffusion", lambda *_args: False)monkeypatch.setattr(backend, "_kill_process", lambda: None)monkeypatch.setattr(diff --git a/studio/backend/tests/test_rag_embed_llama_server.py b/studio/backend/tests/test_rag_embed_llama_server.pyindex 18d9723b882..0e8fe1f368f 100644--- a/studio/backend/tests/test_rag_embed_llama_server.py+++ b/studio/backend/tests/test_rag_embed_llama_server.py@@ -53,7 +53,7 @@ def _mock_auto(monkeypatch, *, gpus, binary):from core.inference.llama_cpp import LlamaCppBackendmonkeypatch.setattr(config, "EMBED_BACKEND", "auto")- monkeypatch.setattr(LlamaCppBackend, "_get_gpu_free_memory", staticmethod(lambda: gpus))+ monkeypatch.setattr(LlamaCppBackend, "_get_gpu_free_memory", staticmethod(lambda **_kw: gpus))monkeypatch.setattr(LlamaCppBackend, "_find_llama_server_binary", staticmethod(lambda: binary))@@ -184,11 +184,15 @@ def test_gpu_available_reuses_studio_probe(monkeypatch):monkeypatch.setattr(uh, "is_apple_silicon", lambda: False)# Ample free VRAM -> GPU; nearly full -> CPU; none -> CPU.- monkeypatch.setattr(LlamaCppBackend, "_get_gpu_free_memory", staticmethod(lambda: [(0, 40000)]))+ monkeypatch.setattr(+ LlamaCppBackend, "_get_gpu_free_memory", staticmethod(lambda **_kw: [(0, 40000)])+ )assert LlamaServerBackend._gpu_available() is True- monkeypatch.setattr(LlamaCppBackend, "_get_gpu_free_memory", staticmethod(lambda: [(0, 100)]))+ monkeypatch.setattr(+ LlamaCppBackend, "_get_gpu_free_memory", staticmethod(lambda **_kw: [(0, 100)])+ )assert LlamaServerBackend._gpu_available() is False- monkeypatch.setattr(LlamaCppBackend, "_get_gpu_free_memory", staticmethod(lambda: []))+ monkeypatch.setattr(LlamaCppBackend, "_get_gpu_free_memory", staticmethod(lambda **_kw: []))assert LlamaServerBackend._gpu_available() is Falsediff --git a/studio/install_llama_prebuilt.py b/studio/install_llama_prebuilt.pyindex 6ef4049ead3..6c81aa51387 100644--- a/studio/install_llama_prebuilt.py+++ b/studio/install_llama_prebuilt.py@@ -402,6 +402,10 @@ class AssetChoice:max_sm: int | None = Noneselection_log: list[str] | None = Noneexpected_sha256: str | None = None+ # ROCm bundles only (mirrors PublishedLlamaArtifact): umbrella gfx family+ # and the concrete archs the binaries were built for.+ gfx_target: str | None = None+ mapped_targets: list[str] | None = None@dataclass(frozen = True)@@ -3434,6 +3438,8 @@ def published_rocm_choice_for_host(url = asset_url,source_label = "published",install_kind = install_kind,+ gfx_target = artifact.gfx_target,+ mapped_targets = list(artifact.mapped_targets),selection_log = list(release.selection_log)+ [f"rocm_selection: gpu={host.rocm_gfx_target} "@@ -6061,6 +6067,12 @@ def write_prebuilt_metadata("bundle_profile": choice.bundle_profile,"runtime_line": choice.runtime_line,"coverage_class": choice.coverage_class,+ # ROCm bundles: concrete built archs, so runtime GPU selection can gate+ # devices the binary has no kernels for (#7624). Deliberately NOT in the+ # install fingerprint, so existing installs stay valid and fail open until+ # their next refresh.+ "gfx_target": choice.gfx_target,+ "mapped_targets": list(choice.mapped_targets or []),"install_fingerprint": fingerprint,"prebuilt_fallback_used": prebuilt_fallback_used,"installed_at_utc": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),@@ -6184,6 +6196,17 @@ def _marker_selection_patch(automatic = patch.get("llama_backend", marker.get("llama_backend")) == "auto"if rocm_gfx and automatic and marker.get("rocm_gfx") != rocm_gfx:patch["rocm_gfx"] = rocm_gfx+ # Built-arch coverage for the runtime GPU gate (#7624). Absent targets mean+ # "this bundle declares none" (CUDA, Vulkan, CPU, source), not "clear it": reuse+ # requires a fingerprint match, so the asset is the one the marker describes.+ # Outside the fingerprint, so recording it never forces a reinstall -- which is+ # also why an install predating the field only gains it here.+ targets = [str(t).strip() for t in (choice.mapped_targets or []) if str(t).strip()]+ if targets and (+ marker.get("mapped_targets") != targets or marker.get("gfx_target") != choice.gfx_target+ ):+ patch["gfx_target"] = choice.gfx_target+ patch["mapped_targets"] = targetsreturn patchdiff --git a/tests/studio/install/test_install_llama_prebuilt_logic.py b/tests/studio/install/test_install_llama_prebuilt_logic.pyindex cafebd97b9b..4b9a0ba037a 100644--- a/tests/studio/install/test_install_llama_prebuilt_logic.py+++ b/tests/studio/install/test_install_llama_prebuilt_logic.py@@ -1958,6 +1958,293 @@ def test_existing_install_matches_plan_windows_cuda_unpaired_skips_cudart_check(assert existing_install_matches_plan(install_dir, host, plan) is True+def test_arch_fields_do_not_change_the_install_fingerprint(tmp_path: Path):+ """gfx_target/mapped_targets must be invisible to the fingerprint (#7624): the+ same asset with the same sha256 is the same install whether or not the marker+ names its built archs, and leaking them in would stale every existing ROCm install+ the moment this shipped. Inverse of the cudart-pair test below."""+ choice_kwargs = dict(+ repo = "unslothai/llama.cpp",+ tag = "release-1",+ name = "app-b9001-linux-x64-rocm-gfx110X.tar.gz",+ url = "https://example.com/x.tar.gz",+ source_label = "published",+ install_kind = "linux-rocm",+ runtime_line = "rocm7",+ expected_sha256 = "a" * 64,+ )+ # The pre-PR marker shape: no arch fields at all.+ old_choice = AssetChoice(**choice_kwargs)+ # Verbatim from the published manifest for this asset.+ new_choice = AssetChoice(+ **choice_kwargs,+ gfx_target = "gfx110X",+ mapped_targets = ["gfx1100", "gfx1101", "gfx1102", "gfx1103"],+ )+ checksums = ApprovedReleaseChecksums(+ repo = "unslothai/llama.cpp",+ release_tag = "release-1",+ upstream_tag = "b9001",+ source_commit = "deadbeef",+ artifacts = {+ source_archive_logical_name("b9001"): ApprovedArtifactHash(+ asset_name = source_archive_logical_name("b9001"),+ sha256 = "b" * 64,+ repo = "ggml-org/llama.cpp",+ kind = "upstream-source",+ ),+ },+ )+ fingerprint_kwargs = dict(+ llama_tag = "b9001", release_tag = "release-1", approved_checksums = checksums+ )+ old_fingerprint = INSTALL_LLAMA_PREBUILT.expected_install_fingerprint(+ choice = old_choice, **fingerprint_kwargs+ )+ new_fingerprint = INSTALL_LLAMA_PREBUILT.expected_install_fingerprint(+ choice = new_choice, **fingerprint_kwargs+ )+ assert old_fingerprint and old_fingerprint == new_fingerprint, (+ "recording gfx_target/mapped_targets changed the install fingerprint; "+ "every existing install would refresh on upgrade"+ )++ # And end to end through the marker: a marker written with the arch fields+ # still satisfies the reuse check computed from a choice without them, so an+ # upgraded client does not decide the install on disk is stale.+ install_dir = tmp_path / "llama.cpp"+ install_dir.mkdir()+ write_prebuilt_metadata(+ install_dir,+ requested_tag = "latest",+ llama_tag = "b9001",+ release_tag = "release-1",+ choice = new_choice,+ approved_checksums = checksums,+ prebuilt_fallback_used = False,+ )+ marker = json.loads((install_dir / "UNSLOTH_PREBUILT_INFO.json").read_text())+ assert marker["mapped_targets"] == ["gfx1100", "gfx1101", "gfx1102", "gfx1103"]+ assert marker["gfx_target"] == "gfx110X"+ assert marker["install_fingerprint"] == old_fingerprint+++def test_non_rocm_bundles_record_no_mapped_targets(tmp_path: Path):+ """CPU/CUDA/Vulkan/macOS choices never populate the arch fields (#7624): only+ published_rocm_choice_for_host sets them, so the marker records [] and the runtime+ gate fails open on a non-ROCm bundle."""+ checksums = ApprovedReleaseChecksums(+ repo = "unslothai/llama.cpp",+ release_tag = "release-1",+ upstream_tag = "b9001",+ source_commit = "deadbeef",+ artifacts = {+ source_archive_logical_name("b9001"): ApprovedArtifactHash(+ asset_name = source_archive_logical_name("b9001"),+ sha256 = "b" * 64,+ repo = "ggml-org/llama.cpp",+ kind = "upstream-source",+ ),+ },+ )+ for kind, asset in (+ ("linux-cpu", "app-b9001-linux-x64-cpu.tar.gz"),+ ("linux-cuda12", "app-b9001-linux-x64-cuda12-portable.tar.gz"),+ ("linux-vulkan", "app-b9001-linux-x64-vulkan.tar.gz"),+ ("windows-cpu", "app-b9001-windows-x64-cpu.zip"),+ ("macos-arm64", "llama-b9001-bin-macos-arm64.tar.gz"),+ ):+ install_dir = tmp_path / kind+ install_dir.mkdir()+ write_prebuilt_metadata(+ install_dir,+ requested_tag = "latest",+ llama_tag = "b9001",+ release_tag = "release-1",+ choice = AssetChoice(+ repo = "unslothai/llama.cpp",+ tag = "release-1",+ name = asset,+ url = "https://example.com/x",+ source_label = "published",+ install_kind = kind,+ expected_sha256 = "a" * 64,+ ),+ approved_checksums = checksums,+ prebuilt_fallback_used = False,+ )+ marker = json.loads((install_dir / "UNSLOTH_PREBUILT_INFO.json").read_text())+ assert marker["mapped_targets"] == [], kind+ assert marker["gfx_target"] is None, kind+++def _rocm_choice(**overrides):+ """A published ROCm bundle choice, the shape published_rocm_choice_for_host+ returns."""+ fields = dict(+ repo = "unslothai/llama.cpp",+ tag = "b10360",+ name = "app-b10360-linux-x64-rocm-gfx110X.tar.gz",+ url = "https://example.invalid/app.tar.gz",+ source_label = "published",+ install_kind = "app",+ bundle_profile = "rocm",+ runtime_line = "rocm",+ coverage_class = "gfx110X",+ gfx_target = "gfx110X",+ mapped_targets = ["gfx1100", "gfx1101", "gfx1102", "gfx1103"],+ )+ fields.update(overrides)+ return AssetChoice(**fields)+++def _sync_arch_coverage(install_dir, choice):+ """sync_marker_selection with only the built-arch coverage in play."""+ INSTALL_LLAMA_PREBUILT.sync_marker_selection(+ install_dir,+ choice = choice,+ backend_request = None,+ persist_llama_backend = "auto",+ )+++def test_reused_install_backfills_the_arch_coverage(tmp_path: Path):+ """An install made before mapped_targets existed must gain it on reuse:+ write_prebuilt_metadata only runs on a real install and the field sits outside the+ fingerprint, so without the backfill the gate fails open indefinitely (#7624)."""+ install_dir = tmp_path / "llama.cpp"+ install_dir.mkdir()+ marker_path = install_dir / "UNSLOTH_PREBUILT_INFO.json"+ marker_path.write_text(+ json.dumps({"release_tag": "b10360", "llama_backend": "auto"}) + "\n",+ encoding = "utf-8",+ )++ _sync_arch_coverage(install_dir, _rocm_choice())++ marker = json.loads(marker_path.read_text(encoding = "utf-8"))+ assert marker["mapped_targets"] == ["gfx1100", "gfx1101", "gfx1102", "gfx1103"]+ assert marker["gfx_target"] == "gfx110X"+ assert marker["release_tag"] == "b10360" # nothing else lost+ assert marker["llama_backend"] == "auto"+++def test_reused_install_refreshes_corrected_arch_coverage(tmp_path: Path):+ """A manifest that corrects mapped_targets for an unchanged asset must reach the+ marker. Stale coverage is worse than none: too narrow forces a supported GPU to+ CPU, too wide leaves an unsupported one visible to crash."""+ install_dir = tmp_path / "llama.cpp"+ install_dir.mkdir()+ marker_path = install_dir / "UNSLOTH_PREBUILT_INFO.json"+ marker_path.write_text(+ json.dumps(+ {+ "release_tag": "b10360",+ "gfx_target": "gfx110X",+ "mapped_targets": ["gfx1100"],+ }+ )+ + "\n",+ encoding = "utf-8",+ )++ _sync_arch_coverage(install_dir, _rocm_choice())++ marker = json.loads(marker_path.read_text(encoding = "utf-8"))+ assert marker["mapped_targets"] == ["gfx1100", "gfx1101", "gfx1102", "gfx1103"]++[email protected]("targets", [None, [], ["", " "]])+def test_a_bundle_that_declares_no_arch_leaves_the_marker_alone(tmp_path: Path, targets):+ """CUDA, Vulkan, CPU and source builds declare no targets. Absent means "this+ bundle has none", not "clear what is there": reuse requires a fingerprint match,+ so the asset is the one the marker already describes."""+ install_dir = tmp_path / "llama.cpp"+ install_dir.mkdir()+ marker_path = install_dir / "UNSLOTH_PREBUILT_INFO.json"+ original = {+ "release_tag": "b10360",+ "gfx_target": "gfx110X",+ "mapped_targets": ["gfx1100", "gfx1101"],+ }+ marker_path.write_text(json.dumps(original) + "\n", encoding = "utf-8")++ _sync_arch_coverage(install_dir, _rocm_choice(gfx_target = None, mapped_targets = targets))++ # The arch fields specifically: the shared writer may still record other+ # selection fields from this run, which is not what this test is about.+ marker = json.loads(marker_path.read_text(encoding = "utf-8"))+ assert marker["gfx_target"] == original["gfx_target"]+ assert marker["mapped_targets"] == original["mapped_targets"]+++def test_arch_coverage_sync_survives_a_missing_or_broken_marker(tmp_path: Path):+ """It runs after the install is already valid, so it must never raise:+ an unexpected exit here no longer falls back to a source build."""+ install_dir = tmp_path / "llama.cpp"+ install_dir.mkdir()+ # No marker at all.+ _sync_arch_coverage(install_dir, _rocm_choice())+ marker_path = install_dir / "UNSLOTH_PREBUILT_INFO.json"+ assert not marker_path.exists()+ # A marker that is not JSON, and one that is JSON but not an object.+ for payload in ("{not json", "[1, 2]"):+ marker_path.write_text(payload, encoding = "utf-8")+ _sync_arch_coverage(install_dir, _rocm_choice())+ assert marker_path.read_text(encoding = "utf-8") == payload+++def test_every_reuse_path_syncs_the_arch_coverage():+ """The reuse paths skip write_prebuilt_metadata, so the coverage has to ride the+ one writer they all share. Source-level because reaching them needs a full install+ run: pinned on _record_reused_selection, which every reuse path calls."""+ source = MODULE_PATH.read_text(encoding = "utf-8")+ assert source.count("_record_reused_selection(") == 4 # definition + 3 reuse paths+ patch = source[+ source.index("def _marker_selection_patch") : source.index("def sync_marker_selection")+ ]+ assert 'patch["mapped_targets"] = targets' in patch+++def test_marker_rewrite_preserves_arch_fields(tmp_path: Path):+ """A sync that touches other fields must not drop the arch ones (#7624).+ sync_marker_selection reads the marker, applies a patch and writes the whole dict+ back; a rebuild-from-known-keys implementation would strip mapped_targets on any+ reused install, turning the gate off unnoticed."""+ install_dir = tmp_path / "llama.cpp"+ install_dir.mkdir()+ marker_path = install_dir / "UNSLOTH_PREBUILT_INFO.json"+ marker_path.write_text(+ json.dumps(+ {+ "release_tag": "release-1",+ "llama_backend": "auto",+ "force_cpu": False,+ "gfx_target": "gfx110X",+ "mapped_targets": ["gfx1100", "gfx1101"],+ }+ ),+ encoding = "utf-8",+ )+ INSTALL_LLAMA_PREBUILT.sync_marker_selection(+ install_dir,+ choice = _rocm_choice(gfx_target = None, mapped_targets = None),+ backend_request = "cpu",+ persist_force_cpu = True,+ persist_llama_backend = "auto",+ ggml_tree = "tree-abc",+ rocm_gfx = "gfx1101",+ )++ marker = json.loads(marker_path.read_text())+ assert marker["gfx_target"] == "gfx110X"+ assert marker["mapped_targets"] == ["gfx1100", "gfx1101"]+ # The syncs did their own job too, so this is not passing on a no-op.+ assert marker["force_cpu"] is True+ assert marker["rocm_gfx"] == "gfx1101"+ assert marker["ggml_tree"] == "tree-abc"++def test_existing_install_fingerprint_changes_when_cudart_pair_added(tmp_path: Path):"""A pre-#5322 CUDA install must go stale once the choice gains a runtime archive (#5106 fingerprint half)."""install_dir = tmp_path / "llama.cpp"diff --git a/tests/studio/install/test_selection_logic.py b/tests/studio/install/test_selection_logic.pyindex c7f2133530f..ce1ed1589e8 100644--- a/tests/studio/install/test_selection_logic.py+++ b/tests/studio/install/test_selection_logic.py@@ -3043,6 +3043,33 @@ class TestPublishedRocmGfxSelection:is None), unbuilt+ def test_choice_records_the_concrete_built_archs(self):+ # The choice carries the arch pair into the install marker, where the+ # runtime GPU gate reads mapped_targets and drops devices outside it+ # (#7624). It must be the CONCRETE list: recording the umbrella family+ # label instead would match no device's reported arch and gate every GPU+ # off the host, silently forcing CPU.+ release = self._release("linux-rocm", "app-b9457-linux-x64-rocm")+ choice = INSTALL_LLAMA_PREBUILT.published_rocm_choice_for_host(+ release, self._host("gfx1100"), "linux-rocm"+ )+ assert choice.gfx_target == "gfx110X"+ assert choice.mapped_targets == ["gfx1100", "gfx1101", "gfx1102", "gfx1103"]++ def test_family_token_match_still_records_concrete_archs(self):+ # The update path forwards the family token (gfx110X) rather than a+ # concrete arch, so selection matches on gfx_target instead of on the+ # mapped list. That branch must record the same concrete archs -- this is+ # the one path where the matched token itself is NOT a device arch.+ release = self._release("linux-rocm", "app-b9457-linux-x64-rocm")+ for token in ("gfx110X", "gfx110x"):+ choice = INSTALL_LLAMA_PREBUILT.published_rocm_choice_for_host(+ release, self._host(token), "linux-rocm"+ )+ assert choice is not None, token+ assert choice.mapped_targets == ["gfx1100", "gfx1101", "gfx1102", "gfx1103"], token+ assert token.lower() not in [t.lower() for t in choice.mapped_targets], token+def test_family_token_matches_family_bundle(self):# The update path forwards a family token (gfx110X, lowercased to gfx110x), not# a concrete arch; it must still select the family bundle, not source-build.