Skip to content

Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.

Studio: repair ROCm attention packages and bound Qwen-Image-2.1 math prefill (#13115)

oobabooga8f389e615154
diff --git a/studio/backend/core/inference/diffusion.py b/studio/backend/core/inference/diffusion.py
index a7bf29e4ea4..ca92fb61608 100644
--- a/studio/backend/core/inference/diffusion.py
+++ b/studio/backend/core/inference/diffusion.py
@@ -1951,15 +1951,25 @@ def _calibrated_activation(fam: Any, target: Any) -> Any:
return None
-def _quadratic_attention(target: Any, engaged_backend: Optional[str] = None) -> bool:
+def _quadratic_attention(
+ target: Any,
+ engaged_backend: Optional[str] = None,
+ pipe: Any = None,
+) -> bool:
"""Whether attention can only run on SDPA math (quadratic memory); False when unknown.
Any engaged non-native backend is a fused kernel, so the SDPA probe only speaks for native."""
if engaged_backend is not None and str(engaged_backend) != "native":
return False
try:
- return bool(sdpa_math_only(target))
+ if not sdpa_math_only(target):
+ return False
except Exception: # noqa: BLE001 - a broken probe must never block a generation
return False
+ try:
+ from .diffusion_qwenimage21_math import bounded_math_attention
+ return not bounded_math_attention(pipe)
+ except Exception: # noqa: BLE001 - known math stays quadratic unless every processor is verified
+ return True
def _activation_guard_batch(chunks: Sequence[Sequence[Any]]) -> int:
@@ -10639,7 +10649,7 @@ class DiffusionBackend:
vae_tile_side = vae_tile_side(getattr(pipe, "vae", None)),
vae_sliced = vae_can_slice(getattr(pipe, "vae", None)),
quadratic_attention = _quadratic_attention(
- guard_target, getattr(state, "attention_backend", None)
+ guard_target, getattr(state, "attention_backend", None), pipe
),
allow_oversized = allow_oversized,
calibrated_placement = bool(getattr(state, "calibrated_placement", False)),
diff --git a/studio/backend/core/inference/diffusion_attention.py b/studio/backend/core/inference/diffusion_attention.py
index 7fdeb507f33..87bb85163c1 100644
--- a/studio/backend/core/inference/diffusion_attention.py
+++ b/studio/backend/core/inference/diffusion_attention.py
@@ -126,7 +126,7 @@ def _is_cuda_nvidia(target: Any) -> bool:
# build in #8225 (gfx1200, torch 2.11+rocm7) both answer True while every dispatch to them raises "No available
# kernel. Aborting execution.", so the dispatcher degrades silently to MATH -- the one backend that materialises the
# whole B x heads x N x N score matrix, which is how a 3.4 GB Q4_K_M video model asked a 16 GB card for a single 66.54
-# GiB allocation. So do not read the flags: run one tiny attention per backend and record what happens.
+# GiB allocation. Probe actual execution first, then intersect that capability with the current process flags.
SDPA_FLASH = "flash"
SDPA_MEM_EFFICIENT = "mem_efficient"
SDPA_CUDNN = "cudnn"
@@ -136,13 +136,116 @@ SDPA_MATH = "math"
_SDPA_SUBQUADRATIC = (SDPA_FLASH, SDPA_MEM_EFFICIENT, SDPA_CUDNN)
_SDPA_PROBE_LOCK = threading.Lock()
-# (device type, dtype name) -> the kernels that ran. A kernel cannot appear or vanish under a running interpreter, so
-# one probe per device/dtype for the life of the process.
+# (indexed device, dtype name) -> capability; process flags are applied on every read.
_SDPA_PROBE_CACHE: dict[tuple[str, str], tuple[str, ...]] = {}
+# An incomplete ROCm probe is retried, but not by every check of the same load (up to 90 s per attempt).
+_ROCM_PROBE_RETRY_S = 120.0
+_ROCM_PROBE_INCOMPLETE: dict[tuple[str, str], float] = {}
+
+
+def _probe_rocm_sdpa_kernels(device: str, dtype: Any) -> tuple[str, ...]:
+ import time
+
+ key = (device, str(dtype))
+ last = _ROCM_PROBE_INCOMPLETE.get(key)
+ if last is not None and time.monotonic() - last < _ROCM_PROBE_RETRY_S:
+ return ()
+ available = _run_rocm_sdpa_children(device, dtype)
+ if available:
+ _ROCM_PROBE_INCOMPLETE.pop(key, None)
+ # Whichever check completes the probe applies its answer; fp32 never runs fused kernels.
+ if _rocm_guard_allowed() and str(dtype) in ("torch.float16", "torch.bfloat16"):
+ try:
+ _apply_rocm_guard(available)
+ except Exception: # noqa: BLE001 - a diagnostic may never fail a load
+ pass
+ else:
+ _ROCM_PROBE_INCOMPLETE[key] = time.monotonic()
+ return available
+
+
+def _run_rocm_sdpa_children(device: str, dtype: Any) -> tuple[str, ...]:
+ """Isolate each backend's HIP error state from Studio and from the other probes."""
+ from concurrent.futures import ThreadPoolExecutor
+ import json
+ from pathlib import Path
+ import subprocess
+ import sys
+ from utils.child_stdio import utf8_child_env
+ from utils.native_path_leases import child_env_without_native_path_secret
+ from utils.subprocess_compat import windows_hidden_subprocess_kwargs
+ from utils.torch_device_probe import ROCM_DLL_DIRS_ENV_VAR, _rocm_dll_directories
+ from .rocm_sdpa_probe import RESULT_PREFIX
+
+ # Same bootstrap as the device probe: a fresh interpreter lacks main.py's ROCm DLL registrations.
+ child_env = child_env_without_native_path_secret()
+ dll_directories = _rocm_dll_directories()
+ if dll_directories:
+ child_env[ROCM_DLL_DIRS_ENV_VAR] = os.pathsep.join(dll_directories)
+
+ def probe(backend: str) -> str:
+ try:
+ result = subprocess.run(
+ [
+ sys.executable,
+ str(Path(__file__).with_name("rocm_sdpa_probe.py")),
+ device,
+ str(dtype).removeprefix("torch."),
+ backend,
+ ],
+ capture_output = True,
+ text = True,
+ encoding = "utf-8",
+ errors = "replace",
+ timeout = 45,
+ env = utf8_child_env(child_env),
+ **windows_hidden_subprocess_kwargs(),
+ )
+ replies = [
+ line[len(RESULT_PREFIX) :]
+ for line in result.stdout.splitlines()
+ if line.startswith(RESULT_PREFIX)
+ ]
+ return json.loads(replies[-1]) if result.returncode == 0 and replies else "unknown"
+ except Exception:
+ return "unknown"
+
+ if probe("MATH") != "available":
+ return ()
+ # One child per backend, run concurrently: an in-process fused failure would poison Studio.
+ candidates = (
+ (SDPA_FLASH, "FLASH_ATTENTION"),
+ (SDPA_MEM_EFFICIENT, "EFFICIENT_ATTENTION"),
+ )
+ with ThreadPoolExecutor(max_workers = 2) as executor:
+ statuses = list(executor.map(probe, (backend for _, backend in candidates)))
+ available = [SDPA_MATH]
+ for (name, _), status in zip(candidates, statuses):
+ if status not in ("available", "unavailable", "failed"):
+ return ()
+ if status == "available":
+ available.append(name)
+ return tuple(available)
+
+
+def _enabled_sdpa_kernels(kernels: tuple[str, ...]) -> tuple[str, ...]:
+ if not kernels:
+ return ()
+ import torch
+
+ flags = {
+ SDPA_FLASH: "flash_sdp_enabled",
+ SDPA_MEM_EFFICIENT: "mem_efficient_sdp_enabled",
+ SDPA_CUDNN: "cudnn_sdp_enabled",
+ SDPA_MATH: "math_sdp_enabled",
+ }
+ return tuple(k for k in kernels if getattr(torch.backends.cuda, flags[k], lambda: True)())
+
+
def _probe_sdpa_kernels(device: str, dtype: Any) -> tuple[str, ...]:
- """Run a 4 KB attention under each SDPA backend; return the ones that did not raise."""
+ """Probe execution; ROCm runs in fresh children so launch errors stay isolated."""
import torch
from torch.nn.attention import SDPBackend, sdpa_kernel
@@ -152,6 +255,10 @@ def _probe_sdpa_kernels(device: str, dtype: Any) -> tuple[str, ...]:
(SDPA_CUDNN, getattr(SDPBackend, "CUDNN_ATTENTION", None)),
(SDPA_MATH, getattr(SDPBackend, "MATH", None)),
)
+ from core._torchao_stub import _module_is_rocm
+
+ if device.split(":")[0] == "cuda" and _module_is_rocm(torch):
+ return _probe_rocm_sdpa_kernels(device, dtype)
# Small enough to be free, but shaped like real attention: the fused kernels reject head_dim they cannot serve, and
# a degenerate 1-element tensor would not exercise that.
q = torch.zeros((1, 2, 8, 64), device = device, dtype = dtype)
@@ -175,7 +282,14 @@ def available_sdpa_kernels(target: Any) -> tuple[str, ...]:
Empty when the probe could not run at all (no torch, no device, an allocator failure) -- an
unanswerable probe must never be read as "only math", which is a claim about the hardware."""
- device = str(getattr(target, "device", "") or "")
+ return _enabled_sdpa_kernels(_sdpa_capability(target))
+
+
+def _sdpa_capability(target: Any) -> tuple[str, ...]:
+ device = str(getattr(target, "torch_device", None) or getattr(target, "device", "") or "")
+ if device == "cuda":
+ ordinal = getattr(target, "ordinal", None)
+ device = f"cuda:{ordinal}" if ordinal is not None else _indexed_cuda_device(device)
if not device:
return ()
dtype = getattr(target, "dtype", None)
@@ -188,7 +302,7 @@ def available_sdpa_kernels(target: Any) -> tuple[str, ...]:
dtype = torch.float16
except Exception: # noqa: BLE001
return ()
- key = (device.split(":")[0], str(dtype))
+ key = (device, str(dtype))
with _SDPA_PROBE_LOCK:
cached = _SDPA_PROBE_CACHE.get(key)
if cached is not None:
@@ -202,8 +316,7 @@ def available_sdpa_kernels(target: Any) -> tuple[str, ...]:
if not available:
return ()
with _SDPA_PROBE_LOCK:
- _SDPA_PROBE_CACHE.setdefault(key, available)
- return _SDPA_PROBE_CACHE[key]
+ return _SDPA_PROBE_CACHE.setdefault(key, available)
def sdpa_math_only(target: Any) -> bool:
@@ -247,6 +360,79 @@ def warn_if_sdpa_math_only(target: Any, logger: Any = None) -> bool:
return True
+ROCM_FUSED_SDPA_ALLOW_ENV = "UNSLOTH_ALLOW_ROCM_FUSED_SDPA"
+_ROCM_GUARD_DISABLED: set[str] = set()
+
+
+def guard_rocm_fused_sdpa(target: Any, logger: Any = None) -> tuple[str, ...]:
+ """Disable failed ROCm fused backends only after math has been verified in isolation."""
+ if not _is_cuda_rocm(target):
+ return ()
+ if not _rocm_guard_allowed():
+ return ()
+ import torch
+
+ from types import SimpleNamespace
+ from .rocm_bf16 import rocm_bf16_supported
+
+ device = str(getattr(target, "torch_device", None) or getattr(target, "device", "cuda"))
+ ordinal = getattr(target, "ordinal", None)
+ if device == "cuda":
+ device = f"cuda:{ordinal}" if ordinal is not None else _indexed_cuda_device(device)
+ dtype = getattr(target, "dtype", None)
+ if dtype not in (torch.float16, torch.bfloat16):
+ dtype = (
+ torch.bfloat16
+ if rocm_bf16_supported(torch, torch.device(device).index)
+ else torch.float16
+ )
+ available = _sdpa_capability(SimpleNamespace(device = device, dtype = dtype))
+ return _apply_rocm_guard(available, logger)
+
+
+def _rocm_guard_allowed() -> bool:
+ return os.environ.get(ROCM_FUSED_SDPA_ALLOW_ENV, "").strip().lower() not in (
+ "1",
+ "true",
+ "yes",
+ "on",
+ )
+
+
+def _apply_rocm_guard(available: tuple[str, ...], logger: Any = None) -> tuple[str, ...]:
+ if SDPA_MATH not in available:
+ return ()
+ import torch
+
+ disabled = []
+ for name, enabled, switch in (
+ (SDPA_FLASH, torch.backends.cuda.flash_sdp_enabled, torch.backends.cuda.enable_flash_sdp),
+ (
+ SDPA_MEM_EFFICIENT,
+ torch.backends.cuda.mem_efficient_sdp_enabled,
+ torch.backends.cuda.enable_mem_efficient_sdp,
+ ),
+ ):
+ if name in available:
+ # The flags are process-wide: a healthy card gets back only what this guard turned off for another.
+ if name in _ROCM_GUARD_DISABLED and not enabled():
+ switch(True)
+ _ROCM_GUARD_DISABLED.discard(name)
+ elif enabled():
+ switch(False)
+ _ROCM_GUARD_DISABLED.add(name)
+ disabled.append(name)
+ if disabled:
+ (logger or _module_logger()).warning(
+ "diffusion.attention: disabled unavailable ROCm SDPA kernels %s; using the remaining kernels. "
+ "If fused kernels are expected on this GPU, run 'unsloth studio update' to repair "
+ "the AMD device packages. %s=1 skips this check.",
+ ", ".join(disabled),
+ ROCM_FUSED_SDPA_ALLOW_ENV,
+ )
+ return tuple(disabled)
+
+
def select_attention_backend(
target: Any,
requested: Optional[str],
@@ -1756,6 +1942,28 @@ def _cudnn_serves_pipe(
return not missing
+def _configure_native_attention(pipe: Any, target: Any, logger: Any) -> None:
+ rocm = _is_cuda_rocm(target)
+ if rocm:
+ try:
+ guard_rocm_fused_sdpa(target, logger)
+ except Exception as exc:
+ _warn(logger, "ROCm fused SDPA check", exc)
+ if rocm and sdpa_math_only(target):
+ try:
+ from .diffusion_qwenimage21_math import install
+ if install(pipe, target, logger):
+ if logger is not None:
+ logger.warning(
+ "diffusion.attention: Qwen-Image-2.1 is using bounded math attention; "
+ "check the AMD device packages if fused kernels are expected on this GPU"
+ )
+ return
+ except Exception as exc:
+ _warn(logger, "bounded Qwen-Image-2.1 math attention", exc)
+ warn_if_sdpa_math_only(target, logger)
+
+
def apply_attention_backend(
pipe: Any,
backend: Optional[str],
@@ -1776,6 +1984,11 @@ def apply_attention_backend(
a fresh transformer's processors follow it (default None). So a load wanting native must
restore it explicitly, else it inherits a backend an earlier load pinned (e.g. cuDNN under a
speed profile), breaking the ``off`` guarantee. Best-effort."""
+ if target is not None:
+ try:
+ guard_rocm_fused_sdpa(target, logger)
+ except Exception as exc:
+ _warn(logger, "ROCm fused SDPA check", exc)
setters = [
s
for s in (getattr(t, "set_attention_backend", None) for t in _attention_dits(pipe))
@@ -1786,7 +1999,7 @@ def apply_attention_backend(
# runs through torch SDPA, so the math-only diagnosis applies exactly as it does to a DiT. Report it here or an
# SDXL load gets no warning at all.
if target is not None:
- warn_if_sdpa_math_only(target, logger)
+ _configure_native_attention(pipe, target, logger)
return None
if backend is not None:
_ensure_attention_backend_installed(backend, logger)
@@ -1857,7 +2070,7 @@ def apply_attention_backend(
# Native means torch's SDPA dispatch decides per call, and on a device with no fused kernel that decision is MATH.
# Say so now; the flags this would otherwise be read off lie (#8225).
if target is not None:
- warn_if_sdpa_math_only(target, logger)
+ _configure_native_attention(pipe, target, logger)
return None
diff --git a/studio/backend/core/inference/diffusion_qwenimage21_math.py b/studio/backend/core/inference/diffusion_qwenimage21_math.py
new file mode 100644
index 00000000000..75844b71b20
--- /dev/null
+++ b/studio/backend/core/inference/diffusion_qwenimage21_math.py
@@ -0,0 +1,190 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Bound Qwen-Image-2.1 math attention in both segmented prefill and cached decode."""
+
+from __future__ import annotations
+
+import functools
+from typing import Any
+
+QUERY_CHUNK_SIZE = 512
+
+
+def _bounded_attention(
+ query,
+ key,
+ value,
+ dispatch,
+ *,
+ mask = None,
+ causal_offset = None,
+ **kwargs,
+):
+ import torch
+
+ outputs = []
+ for start in range(0, query.shape[1], QUERY_CHUNK_SIZE):
+ part = query[:, start : start + QUERY_CHUNK_SIZE]
+ part_mask = mask
+ if mask is not None and mask.shape[-2] != 1:
+ part_mask = mask[..., start : start + QUERY_CHUNK_SIZE, :]
+ if causal_offset is not None:
+ # The segment can see all preceding segments, then a triangle over its own keys.
+ causal = torch.arange(key.shape[1], device = query.device)[None, :] <= (
+ causal_offset + start + torch.arange(part.shape[1], device = query.device)[:, None]
+ )
+ causal = causal[None, None]
+ part_mask = causal if part_mask is None else causal & part_mask
+ outputs.append(dispatch(part, key, value, attn_mask = part_mask, dropout_p = 0.0, **kwargs))
+ if not outputs:
+ return query.new_empty((*query.shape[:-1], value.shape[-1]))
+ return torch.cat(outputs, dim = 1)
+
+
+def _eligible(processor, hidden_states, attention_mask, segments):
+ import torch
+ from .diffusion_qwenimage21_rocm import _native_backend
+
+ if (
+ processor._parallel_config is not None
+ or torch.is_grad_enabled()
+ or not _native_backend(processor)
+ ):
+ return False
+ # Segmented prefill ignores the flex BlockMask, exactly as the upstream stock processor does.
+ return (
+ segments is not None
+ or attention_mask is None
+ or (
+ isinstance(attention_mask, torch.Tensor)
+ and attention_mask.ndim >= 2
+ and attention_mask.shape[-2] in (1, hidden_states.shape[1])
+ )
+ )
+
+
[email protected]_cache(maxsize = 1)
+def _processor_class():
+ import torch
+ from diffusers.models.transformers.transformer_qwenimage21 import (
+ QwenImage21AttnProcessor,
+ _qwenimage21_prepare_qkv,
+ dispatch_attention_fn,
+ )
+
+ class BoundedMathQwenImage21AttnProcessor(QwenImage21AttnProcessor):
+ def __call__(
+ self,
+ attn,
+ hidden_states,
+ attention_mask = None,
+ rotary_emb = None,
+ layer_cache = None,
+ kv_cache_mode = None,
+ cache_write_slice = None,
+ segments = None,
+ key_valid = None,
+ ):
+ if not _eligible(self, hidden_states, attention_mask, segments):
+ return super().__call__(
+ attn,
+ hidden_states,
+ attention_mask,
+ rotary_emb,
+ layer_cache,
+ kv_cache_mode,
+ cache_write_slice,
+ segments,
+ key_valid,
+ )
+ query, key, value, seq_len_q = _qwenimage21_prepare_qkv(
+ attn, hidden_states, rotary_emb, layer_cache, kv_cache_mode, cache_write_slice
+ )
+ if segments is None:
+ output = _bounded_attention(
+ query,
+ key,
+ value,
+ dispatch_attention_fn,
+ mask = attention_mask,
+ backend = self._attention_backend,
+ parallel_config = self._parallel_config,
+ )
+ else:
+ outputs = []
+ for start, end, is_text in segments:
+ outputs.append(
+ _bounded_attention(
+ query[:, start:end],
+ key[:, :end],
+ value[:, :end],
+ dispatch_attention_fn,
+ mask = None if key_valid is None else key_valid[:, None, None, :end],
+ causal_offset = start if is_text else None,
+ backend = None,
+ parallel_config = self._parallel_config,
+ )
+ )
+ prefix_len = segments[-1][1] if segments else 0
+ outputs.append(
+ _bounded_attention(
+ query[:, prefix_len:],
+ key,
+ value,
+ dispatch_attention_fn,
+ mask = None if key_valid is None else key_valid[:, None, None, :],
+ backend = None,
+ parallel_config = self._parallel_config,
+ )
+ )
+ output = torch.cat(outputs, dim = 1)
+ output = output[:, :seq_len_q].flatten(2, 3).type_as(query)
+ return attn.to_out[1](attn.to_out[0](output))
+
+ return BoundedMathQwenImage21AttnProcessor
+
+
+def install(
+ pipe: Any,
+ target: Any,
+ logger: Any = None,
+) -> bool:
+ """A correctness fallback for every ROCm architecture, independent of speed mode."""
+ from .diffusion_attention import sdpa_math_only
+ from .diffusion_qwenimage21_rocm import _processor_class as speed_processor_class
+ from diffusers.models.transformers.transformer_qwenimage21 import QwenImage21AttnProcessor
+
+ if getattr(target, "backend", None) != "rocm" or not sdpa_math_only(target):
+ return False
+ transformer = getattr(pipe, "transformer", None)
+ if type(transformer).__name__ != "QwenImage21Transformer2DModel":
+ return False
+ cls = _processor_class()
+ changed = False
+ for module in transformer.modules():
+ processor = getattr(module, "processor", None)
+ if type(processor) in (QwenImage21AttnProcessor, speed_processor_class()):
+ replacement = cls()
+ replacement.__dict__.update(processor.__dict__)
+ module.set_processor(replacement)
+ changed = True
+ if changed and logger is not None:
+ logger.info(
+ "diffusion.qwenimage21: bounding math attention to 512 query rows, including prefill"
+ )
+ return bounded_math_attention(pipe)
+
+
+def bounded_math_attention(pipe: Any) -> bool:
+ """Credit bounded memory only when every attention processor on this transformer qualifies."""
+ from .diffusion_qwenimage21_rocm import _native_backend
+
+ transformer = getattr(pipe, "transformer", None)
+ if type(transformer).__name__ != "QwenImage21Transformer2DModel":
+ return False
+ processors = [m.processor for m in transformer.modules() if hasattr(m, "processor")]
+ return bool(processors) and all(
+ type(p) is _processor_class() and p._parallel_config is None and _native_backend(p)
+ for p in processors
+ )
diff --git a/studio/backend/core/inference/rocm_sdpa_probe.py b/studio/backend/core/inference/rocm_sdpa_probe.py
new file mode 100644
index 00000000000..368b1aff1fb
--- /dev/null
+++ b/studio/backend/core/inference/rocm_sdpa_probe.py
@@ -0,0 +1,80 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""One ROCm SDPA backend per process, so a deferred launch error cannot poison the next probe."""
+
+from __future__ import annotations
+
+import json
+import sys
+
+RESULT_PREFIX = "UNSLOTH_SDPA_PROBE "
+
+
+def _register_rocm_dll_directories() -> list:
+ import os
+
+ handles = []
+ if sys.platform == "win32":
+ for directory in os.environ.get("UNSLOTH_STUDIO_PROBE_ROCM_DLL_DIRS", "").split(os.pathsep):
+ if directory and os.path.isdir(directory):
+ try:
+ handles.append(os.add_dll_directory(directory))
+ except (OSError, AttributeError):
+ pass
+ return handles
+
+
+def probe(device: str, dtype_name: str, backend_name: str) -> str:
+ _handles = _register_rocm_dll_directories()
+ import torch
+ from torch.nn.attention import SDPBackend, sdpa_kernel
+
+ dtype = getattr(torch, dtype_name)
+ backend = getattr(SDPBackend, backend_name)
+ generator = torch.Generator(device = device).manual_seed(0)
+ ran = False
+ with torch.inference_mode():
+ for length, causal in ((256, True), (1024, False)):
+ q, k, v = (
+ torch.randn(1, 4, length, 128, device = device, dtype = dtype, generator = generator)
+ for _ in range(3)
+ )
+ try:
+ with sdpa_kernel([SDPBackend.MATH]):
+ reference = torch.nn.functional.scaled_dot_product_attention(
+ q, k, v, is_causal = causal
+ )
+ reference = reference.float()
+ if not bool(torch.isfinite(reference).all().item()):
+ return "unknown"
+ except Exception:
+ return "unknown"
+ if backend_name == "MATH":
+ ran = True
+ continue
+ try:
+ with sdpa_kernel([backend]):
+ actual = torch.nn.functional.scaled_dot_product_attention(
+ q, k, v, is_causal = causal
+ )
+ # A failed HIP launch can surface only at this checked consumer, not at synchronize().
+ actual = actual.float()
+ actual.sum().item()
+ if not torch.allclose(actual, reference, atol = 2e-2, rtol = 2e-2):
+ return "failed"
+ ran = True
+ except torch.OutOfMemoryError:
+ return "unknown"
+ except Exception as exc:
+ if "No available kernel" not in str(exc):
+ return "failed"
+ return "available" if ran else "unavailable"
+
+
+if __name__ == "__main__":
+ try:
+ result = probe(*sys.argv[1:])
+ except Exception:
+ result = "unknown"
+ print(RESULT_PREFIX + json.dumps(result), flush = True)
diff --git a/studio/backend/tests/test_diffusion_attention.py b/studio/backend/tests/test_diffusion_attention.py
index ce4bc63a446..ab0678102d8 100644
--- a/studio/backend/tests/test_diffusion_attention.py
+++ b/studio/backend/tests/test_diffusion_attention.py
@@ -866,6 +866,8 @@ def _stub_probe(
return tuple(kernels)
monkeypatch.setattr(att, "_probe_sdpa_kernels", _probe)
+ # Importing unsloth on SM100 turns cuDNN SDPA off process-wide; these tests pin the probe alone.
+ monkeypatch.setattr(att, "_enabled_sdpa_kernels", lambda found: found)
def test_math_only_is_read_off_a_probe_not_the_flags(monkeypatch):
@@ -941,15 +943,18 @@ def test_a_target_with_no_device_is_never_probed(monkeypatch):
def test_the_probe_runs_once_per_device_and_dtype(monkeypatch):
# A kernel cannot appear or vanish under a running interpreter, and this sits on the load
- # path, so the probe is memoised. cuda:0 and cuda:1 are the same device TYPE.
+ # path, so the probe is memoised. each indexed GPU has its own capability result.
+ import torch
+
+ monkeypatch.setattr(torch.cuda, "current_device", lambda: 0)
seen: list = []
_stub_probe(monkeypatch, ("math",), record = seen)
for device in ("cuda", "cuda:0", "cuda:1"):
assert att.sdpa_math_only(types.SimpleNamespace(device = device, dtype = "fp16")) is True
- assert len(seen) == 1
+ assert len(seen) == 2
# A different dtype is a different question: fused kernels are half-precision only.
att.sdpa_math_only(types.SimpleNamespace(device = "cuda", dtype = "fp32"))
- assert len(seen) == 2
+ assert len(seen) == 3
def test_a_dtypeless_target_probes_in_half_precision(monkeypatch):
@@ -960,7 +965,7 @@ def test_a_dtypeless_target_probes_in_half_precision(monkeypatch):
seen: list = []
_stub_probe(monkeypatch, ("flash", "math"), record = seen)
att.available_sdpa_kernels(types.SimpleNamespace(device = "cuda", dtype = None))
- assert seen == [("cuda", torch.float16)]
+ assert seen == [(att._indexed_cuda_device("cuda"), torch.float16)]
def test_warn_names_the_quadratic_cost(monkeypatch):
diff --git a/studio/backend/tests/test_diffusion_backend.py b/studio/backend/tests/test_diffusion_backend.py
index 890d006396b..5ac75e2c072 100644
--- a/studio/backend/tests/test_diffusion_backend.py
+++ b/studio/backend/tests/test_diffusion_backend.py
@@ -11717,7 +11717,7 @@ def _upscale_with_tiling_vae(backend, monkeypatch, **kw):
vae = _TilingVae()
monkeypatch.setattr(_FakeImg2ImgPipe, "vae", vae, raising = False)
- monkeypatch.setattr(dmod, "_quadratic_attention", lambda target, backend = None: False)
+ monkeypatch.setattr(dmod, "_quadratic_attention", lambda target, backend = None, pipe = None: False)
seen = {}
real_call = _FakeImg2ImgPipe.__call__
@@ -11753,7 +11753,7 @@ def test_generate_upscale_that_fits_is_not_tiled(fake_runtime, tmp_path, monkeyp
vae = _TilingVae()
monkeypatch.setattr(_FakeImg2ImgPipe, "vae", vae, raising = False)
- monkeypatch.setattr(dmod, "_quadratic_attention", lambda target, backend = None: False)
+ monkeypatch.setattr(dmod, "_quadratic_attention", lambda target, backend = None, pipe = None: False)
backend.generate(prompt = "a sloth", steps = 4, seed = 1, init_image = _png_b64(512), upscale = 2.0)
assert vae.calls == []
@@ -11766,7 +11766,7 @@ def test_generate_upscale_restores_the_vae_when_the_render_fails(
vae = _TilingVae()
monkeypatch.setattr(_FakeImg2ImgPipe, "vae", vae, raising = False)
- monkeypatch.setattr(dmod, "_quadratic_attention", lambda target, backend = None: False)
+ monkeypatch.setattr(dmod, "_quadratic_attention", lambda target, backend = None, pipe = None: False)
def _boom(self, **kwargs):
raise RuntimeError("decode failed")
@@ -11782,7 +11782,7 @@ def test_generate_upscale_on_math_only_attention_still_refuses(fake_runtime, tmp
backend = _loaded_backend_on_a_16g_card(tmp_path, monkeypatch)
monkeypatch.setattr(_FakeImg2ImgPipe, "vae", _TilingVae(), raising = False)
- monkeypatch.setattr(dmod, "_quadratic_attention", lambda target, backend = None: True)
+ monkeypatch.setattr(dmod, "_quadratic_attention", lambda target, backend = None, pipe = None: True)
with pytest.raises(ValueError) as excinfo:
backend.generate(prompt = "a sloth", steps = 4, seed = 1, init_image = _png_b64(1024), upscale = 2.0)
message = str(excinfo.value)
@@ -11809,7 +11809,7 @@ def test_generate_windows_batch_prices_tiles_at_the_batch_without_slicing(
backend = _loaded_backend_on_a_16g_card(tmp_path, monkeypatch)
vae = vae_cls()
monkeypatch.setattr(_FakeImg2ImgPipe, "vae", vae, raising = False)
- monkeypatch.setattr(dmod, "_quadratic_attention", lambda target, backend = None: False)
+ monkeypatch.setattr(dmod, "_quadratic_attention", lambda target, backend = None, pipe = None: False)
monkeypatch.setattr(dmod.sys, "platform", "win32")
kw = dict(prompt = "a sloth", steps = 4, init_image = _png_b64(1024), upscale = 2.0, seeds = [1, 2])
if vae_cls is _TilingVae:
@@ -11836,7 +11836,7 @@ def test_generate_upscale_refuses_when_the_vae_tiling_does_not_engage(
backend = _loaded_backend_on_a_16g_card(tmp_path, monkeypatch)
vae = _BrokenTilingVae()
monkeypatch.setattr(_FakeImg2ImgPipe, "vae", vae, raising = False)
- monkeypatch.setattr(dmod, "_quadratic_attention", lambda target, backend = None: False)
+ monkeypatch.setattr(dmod, "_quadratic_attention", lambda target, backend = None, pipe = None: False)
calls = []
real_call = _FakeImg2ImgPipe.__call__
diff --git a/studio/backend/tests/test_diffusion_qwenimage21_math.py b/studio/backend/tests/test_diffusion_qwenimage21_math.py
new file mode 100644
index 00000000000..c6dd23b07bd
--- /dev/null
+++ b/studio/backend/tests/test_diffusion_qwenimage21_math.py
@@ -0,0 +1,178 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+from types import SimpleNamespace
+
+import pytest
+
+from core.inference import diffusion_qwenimage21_math as bounded
+from core.inference import diffusion_attention as attention
+
+torch = pytest.importorskip("torch")
+qmod = pytest.importorskip("diffusers.models.transformers.transformer_qwenimage21")
+
+
[email protected](autouse = True)
+def math_backend():
+ from torch.nn.attention import SDPBackend, sdpa_kernel
+ from diffusers.models.attention_dispatch import attention_backend
+ with sdpa_kernel([SDPBackend.MATH]), attention_backend("native"):
+ yield
+
+
[email protected]("mask_kind", ["none", "broadcast", "rows", "additive"])
+def test_bounded_attention_matches_full_math_with_masks(mask_kind):
+ torch.manual_seed(51)
+ q = torch.randn(2, 769, 2, 8)
+ k, v = torch.randn(2, 833, 2, 8), torch.randn(2, 833, 2, 8)
+ mask = None
+ if mask_kind == "broadcast":
+ mask = torch.ones(2, 1, 1, 833, dtype = torch.bool)
+ mask[1, ..., -7:] = False
+ elif mask_kind in ("rows", "additive"):
+ mask = (torch.arange(833)[None, :] <= torch.arange(769)[:, None] + 32)[None, None]
+ if mask_kind == "additive":
+ mask = torch.zeros_like(mask, dtype = torch.float32).masked_fill(~mask, float("-inf"))
+ calls = []
+
+ def dispatch(q, k, v, **kw):
+ calls.append((q.shape[1], k.shape[1], kw["attn_mask"]))
+ return qmod.dispatch_attention_fn(q, k, v, backend = "native", **kw)
+
+ expected = dispatch(q, k, v, attn_mask = mask, dropout_p = 0.0)
+ calls.clear()
+ actual = bounded._bounded_attention(q, k, v, dispatch, mask = mask)
+ torch.testing.assert_close(actual, expected)
+ assert [c[:2] for c in calls] == [(512, 833), (257, 833)]
+
+
[email protected]("padded", [False, True])
+def test_segmented_prefill_and_cached_decode_match_stock(monkeypatch, padded):
+ torch.manual_seed(7)
+ attn = qmod.QwenImage21Attention(dim = 16, heads = 2, dim_head = 8)
+ stock, patched = qmod.QwenImage21AttnProcessor(), bounded._processor_class()()
+ states = torch.randn(2, 1800, 16)
+ segments = [(0, 600, True), (600, 1130, False)]
+ mask = torch.ones(2, 1800, dtype = torch.bool) if padded else None
+ if padded:
+ mask[1, 580:600] = False
+ caches = [qmod.QwenImage21KVLayerCache(), qmod.QwenImage21KVLayerCache()]
+ calls = []
+ original = bounded._bounded_attention
+
+ def record(q, k, v, dispatch, **kw):
+ def checked(q, k, v, **args):
+ calls.append(q.shape[1])
+ return dispatch(q, k, v, **args)
+
+ return original(q, k, v, checked, **kw)
+
+ monkeypatch.setattr(bounded, "_bounded_attention", record)
+ with torch.inference_mode():
+ args = dict(
+ segments = segments,
+ key_valid = mask,
+ kv_cache_mode = "extract",
+ cache_write_slice = slice(0, 1130),
+ )
+ expected = stock(attn, states, layer_cache = caches[0], **args)
+ actual = patched(attn, states, layer_cache = caches[1], **args)
+ torch.testing.assert_close(actual, expected)
+ torch.testing.assert_close(caches[0].k, caches[1].k, atol = 0, rtol = 0)
+ torch.testing.assert_close(caches[0].v, caches[1].v, atol = 0, rtol = 0)
+ assert max(calls) == 512 and len(calls) >= 6
+ target = states[:, 1130:]
+ key_mask = mask[:, None, None, :] if padded else None
+ expected = stock(
+ attn, target, layer_cache = caches[0], kv_cache_mode = "cached", attention_mask = key_mask
+ )
+ actual = patched(
+ attn, target, layer_cache = caches[1], kv_cache_mode = "cached", attention_mask = key_mask
+ )
+ torch.testing.assert_close(actual, expected)
+ assert caches[1].k.shape[1] == 1130
+
+
+def make_pipe():
+ modules = [qmod.QwenImage21Attention(dim = 16, heads = 2, dim_head = 8) for _ in range(2)]
+ transformer = type(
+ "QwenImage21Transformer2DModel", (), {"modules": lambda self: iter(modules)}
+ )()
+ return SimpleNamespace(transformer = transformer), modules
+
+
+def test_native_load_installs_fallback_and_guard_tracks_actual_processors(monkeypatch):
+ from core.inference.diffusion import _quadratic_attention
+
+ pipe, modules = make_pipe()
+ target = SimpleNamespace(backend = "rocm", device = "cuda:0", dtype = torch.bfloat16)
+ monkeypatch.setattr(attention, "sdpa_math_only", lambda t: True)
+ monkeypatch.setattr("core.inference.diffusion.sdpa_math_only", lambda t: True)
+ monkeypatch.setattr(attention, "_is_cuda_rocm", lambda t: True)
+ monkeypatch.setattr(attention, "guard_rocm_fused_sdpa", lambda *a: ())
+ assert _quadratic_attention(target, None, pipe)
+ attention.apply_attention_backend(pipe, None, target = target)
+ assert bounded.bounded_math_attention(pipe)
+ assert not _quadratic_attention(target, None, pipe)
+ installed = modules[0].processor
+ assert bounded.install(pipe, target)
+ assert modules[0].processor is installed
+ modules[1].set_processor(qmod.QwenImage21AttnProcessor())
+ assert _quadratic_attention(target, None, pipe)
+
+
[email protected]("change", ["parallel", "custom", "non_native"])
+def test_guard_never_credits_uncovered_processors(monkeypatch, change):
+ pipe, modules = make_pipe()
+ monkeypatch.setattr(attention, "sdpa_math_only", lambda t: True)
+ assert bounded.install(pipe, SimpleNamespace(backend = "rocm"))
+ if change == "parallel":
+ modules[0].processor._parallel_config = object()
+ elif change == "custom":
+ modules[0].set_processor(qmod.QwenImage21AttnProcessor())
+ else:
+ modules[0].processor._attention_backend = "_native_math"
+ assert not bounded.bounded_math_attention(pipe)
+
+
+def test_healthy_fused_install_and_non_rocm_keep_stock(monkeypatch):
+ pipe, modules = make_pipe()
+ monkeypatch.setattr(attention, "sdpa_math_only", lambda t: False)
+ assert not bounded.install(pipe, SimpleNamespace(backend = "rocm"))
+ monkeypatch.setattr(attention, "sdpa_math_only", lambda t: True)
+ assert not bounded.install(pipe, SimpleNamespace(backend = "cuda"))
+ assert all(type(m.processor) is qmod.QwenImage21AttnProcessor for m in modules)
+
+
+def test_causal_chunk_offsets_include_preceding_segments():
+ torch.manual_seed(42)
+ query = torch.randn(1, 769, 2, 8)
+ key, value = torch.randn(1, 1000, 2, 8), torch.randn(1, 1000, 2, 8)
+ allowed = (torch.arange(1000)[None, :] <= 231 + torch.arange(769)[:, None])[None, None]
+ expected = qmod.dispatch_attention_fn(query, key, value, attn_mask = allowed, backend = "native")
+ actual = bounded._bounded_attention(
+ query, key, value, qmod.dispatch_attention_fn, causal_offset = 231, backend = "native"
+ )
+ torch.testing.assert_close(actual, expected)
+
+
+def test_failed_bounded_processor_inspection_keeps_quadratic_guard(monkeypatch):
+ from core.inference import diffusion
+
+ monkeypatch.setattr(diffusion, "sdpa_math_only", lambda t: True)
+
+ def failed(pipe):
+ raise RuntimeError("processor unavailable")
+
+ monkeypatch.setattr(bounded, "bounded_math_attention", failed)
+ assert diffusion._quadratic_attention(object(), None, object())
+
+
+def test_empty_prefix_matches_full_attention():
+ torch.manual_seed(23)
+ attn = qmod.QwenImage21Attention(dim = 16, heads = 2, dim_head = 8)
+ states = torch.randn(1, 769, 16)
+ with torch.inference_mode():
+ expected = qmod.QwenImage21AttnProcessor()(attn, states, segments = [])
+ actual = bounded._processor_class()()(attn, states, segments = [])
+ torch.testing.assert_close(actual, expected)
diff --git a/studio/backend/tests/test_rocm_attention_recovery.py b/studio/backend/tests/test_rocm_attention_recovery.py
new file mode 100644
index 00000000000..53ddea50f34
--- /dev/null
+++ b/studio/backend/tests/test_rocm_attention_recovery.py
@@ -0,0 +1,291 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+import json
+import os
+import subprocess
+import threading
+from types import SimpleNamespace
+
+import pytest
+
+from core.inference import diffusion_attention as att
+from core.inference import rocm_sdpa_probe as probe
+
+torch = pytest.importorskip("torch")
+
+
[email protected](autouse = True)
+def flags():
+ before = [
+ (read(), write)
+ for read, write in (
+ (torch.backends.cuda.flash_sdp_enabled, torch.backends.cuda.enable_flash_sdp),
+ (
+ torch.backends.cuda.mem_efficient_sdp_enabled,
+ torch.backends.cuda.enable_mem_efficient_sdp,
+ ),
+ (torch.backends.cuda.math_sdp_enabled, torch.backends.cuda.enable_math_sdp),
+ )
+ ]
+ for _, write in before:
+ write(True)
+ att._SDPA_PROBE_CACHE.clear()
+ att._ROCM_GUARD_DISABLED.clear()
+ att._ROCM_PROBE_INCOMPLETE.clear()
+ yield
+ for value, write in before:
+ write(value)
+ att._SDPA_PROBE_CACHE.clear()
+ att._ROCM_GUARD_DISABLED.clear()
+ att._ROCM_PROBE_INCOMPLETE.clear()
+
+
[email protected]("platform", ["linux", "win32"])
+def test_isolated_probe_runs_each_backend_in_a_fresh_child(monkeypatch, platform):
+ from utils import subprocess_compat
+
+ monkeypatch.setattr(subprocess_compat, "sys", SimpleNamespace(platform = platform))
+ monkeypatch.setattr(subprocess, "CREATE_NO_WINDOW", 0x08000000, raising = False)
+ monkeypatch.setattr(subprocess, "STARTF_USESHOWWINDOW", 1, raising = False)
+ monkeypatch.setattr(subprocess, "SW_HIDE", 0, raising = False)
+ monkeypatch.setattr(
+ subprocess, "STARTUPINFO", lambda: SimpleNamespace(dwFlags = 16), raising = False
+ )
+ calls = []
+
+ def run(cmd, **kwargs):
+ calls.append((cmd, kwargs))
+ status = "failed" if cmd[-1] == "FLASH_ATTENTION" else "available"
+ return SimpleNamespace(returncode = 0, stdout = probe.RESULT_PREFIX + json.dumps(status))
+
+ monkeypatch.setattr(subprocess, "run", run)
+ assert att._probe_rocm_sdpa_kernels("cuda:1", torch.bfloat16) == ("math", "mem_efficient")
+ assert calls[0][0][-1] == "MATH"
+ assert {cmd[-1] for cmd, _ in calls[1:]} == {"FLASH_ATTENTION", "EFFICIENT_ATTENTION"}
+ assert all(cmd[-3:-1] == ["cuda:1", "bfloat16"] and kw["timeout"] == 45 for cmd, kw in calls)
+ for _, kwargs in calls:
+ if platform == "win32":
+ assert kwargs["creationflags"] == subprocess.CREATE_NO_WINDOW
+ assert kwargs["startupinfo"].dwFlags == 17
+ assert kwargs["startupinfo"].wShowWindow == subprocess.SW_HIDE
+ else:
+ assert "creationflags" not in kwargs and "startupinfo" not in kwargs
+
+
+def test_fused_children_overlap_only_after_math_succeeds(monkeypatch):
+ math_done = threading.Event()
+ fused_started = threading.Barrier(2, timeout = 5)
+
+ def run(cmd, **kwargs):
+ if cmd[-1] == "MATH":
+ math_done.set()
+ else:
+ assert math_done.is_set()
+ # A serial implementation cannot finish either child before the other starts.
+ fused_started.wait()
+ return SimpleNamespace(returncode = 0, stdout = probe.RESULT_PREFIX + '"available"')
+
+ monkeypatch.setattr(subprocess, "run", run)
+ assert att._probe_rocm_sdpa_kernels("cuda:0", torch.bfloat16) == (
+ "math",
+ "flash",
+ "mem_efficient",
+ )
+
+
[email protected]("status", ["failed", "unavailable", "unknown", "timeout"])
+def test_fused_children_are_not_started_without_working_math(monkeypatch, status):
+ calls = []
+
+ def run(cmd, **kwargs):
+ calls.append(cmd[-1])
+ if status == "timeout":
+ raise subprocess.TimeoutExpired(cmd, 45)
+ return SimpleNamespace(returncode = 0, stdout = probe.RESULT_PREFIX + json.dumps(status))
+
+ monkeypatch.setattr(subprocess, "run", run)
+ assert att._probe_rocm_sdpa_kernels("cuda:0", torch.bfloat16) == ()
+ assert calls == ["MATH"]
+
+
[email protected]("failure", ["timeout", "exit", "garbage", "unknown"])
+def test_incomplete_probe_does_not_disable_or_cache_kernels(monkeypatch, failure):
+ def run(cmd, **kw):
+ if cmd[-1] == "MATH":
+ return SimpleNamespace(returncode = 0, stdout = probe.RESULT_PREFIX + '"available"')
+ if failure == "timeout":
+ raise subprocess.TimeoutExpired(cmd, 45)
+ return SimpleNamespace(
+ returncode = int(failure == "exit"),
+ stdout = ("garbage" if failure == "garbage" else probe.RESULT_PREFIX + '"unknown"'),
+ )
+
+ monkeypatch.setattr(subprocess, "run", run)
+ monkeypatch.setattr(att, "_is_cuda_rocm", lambda t: True)
+ monkeypatch.setattr(torch.version, "hip", "7.14")
+ target = SimpleNamespace(device = "cuda:0", dtype = torch.bfloat16)
+ assert att.guard_rocm_fused_sdpa(target) == ()
+ assert att._SDPA_PROBE_CACHE == {}
+ assert torch.backends.cuda.flash_sdp_enabled()
+ assert torch.backends.cuda.mem_efficient_sdp_enabled()
+
+
+ "available,disabled",
+ [
+ (("math",), ("flash", "mem_efficient")),
+ (("math", "flash"), ("mem_efficient",)),
+ (("math", "flash", "mem_efficient"), ()),
+ ((), ()),
+ ],
+)
+def test_guard_only_disables_failed_backends(monkeypatch, available, disabled):
+ monkeypatch.setattr(att, "_is_cuda_rocm", lambda t: True)
+ monkeypatch.setattr(att, "_probe_sdpa_kernels", lambda *a: available)
+ target = SimpleNamespace(device = "cuda:0", dtype = torch.bfloat16)
+ assert att.guard_rocm_fused_sdpa(target) == disabled
+ assert torch.backends.cuda.flash_sdp_enabled() == ("flash" not in disabled)
+ assert torch.backends.cuda.mem_efficient_sdp_enabled() == ("mem_efficient" not in disabled)
+ assert att.guard_rocm_fused_sdpa(target) == ()
+
+
+def test_guard_restores_only_its_own_flags_for_a_healthy_card(monkeypatch):
+ monkeypatch.setattr(att, "_is_cuda_rocm", lambda t: True)
+ capability = {"cuda:0": ("math",), "cuda:1": ("math", "flash", "mem_efficient")}
+ monkeypatch.setattr(att, "_probe_sdpa_kernels", lambda device, dtype: capability[device])
+ broken = SimpleNamespace(device = "cuda:0", dtype = torch.bfloat16)
+ healthy = SimpleNamespace(device = "cuda:1", dtype = torch.bfloat16)
+ assert att.guard_rocm_fused_sdpa(broken) == ("flash", "mem_efficient")
+ assert att.sdpa_math_only(healthy)
+ assert att.guard_rocm_fused_sdpa(healthy) == ()
+ assert att.sdpa_subquadratic_confirmed(healthy)
+ assert torch.backends.cuda.flash_sdp_enabled()
+ assert torch.backends.cuda.mem_efficient_sdp_enabled()
+
+ torch.backends.cuda.enable_flash_sdp(False)
+ assert att.guard_rocm_fused_sdpa(broken) == ("mem_efficient",)
+ att.guard_rocm_fused_sdpa(healthy)
+ assert not torch.backends.cuda.flash_sdp_enabled()
+ assert torch.backends.cuda.mem_efficient_sdp_enabled()
+
+
+def test_cached_capabilities_follow_current_flags(monkeypatch):
+ calls = []
+
+ def run(*args):
+ calls.append(args)
+ return ("math", "flash", "mem_efficient")
+
+ monkeypatch.setattr(att, "_probe_sdpa_kernels", run)
+ target = SimpleNamespace(device = "cuda:0", dtype = torch.bfloat16)
+ assert att.sdpa_subquadratic_confirmed(target)
+ torch.backends.cuda.enable_flash_sdp(False)
+ torch.backends.cuda.enable_mem_efficient_sdp(False)
+ assert att.sdpa_math_only(target)
+ assert not att.sdpa_subquadratic_confirmed(target)
+ torch.backends.cuda.enable_flash_sdp(True)
+ assert att.sdpa_subquadratic_confirmed(target)
+ assert len(calls) == 1
+
+
[email protected]("rocm,allow", [(False, False), (True, True)])
+def test_other_platforms_and_explicit_override_do_not_probe(monkeypatch, rocm, allow):
+ monkeypatch.setattr(att, "_is_cuda_rocm", lambda t: rocm)
+ monkeypatch.setenv(att.ROCM_FUSED_SDPA_ALLOW_ENV, "1" if allow else "0")
+ monkeypatch.setattr(att, "_sdpa_capability", lambda t: pytest.fail("unexpected probe"))
+ assert att.guard_rocm_fused_sdpa(SimpleNamespace()) == ()
+
+
+def test_probe_consumes_deferred_launch_errors(monkeypatch):
+ real = torch.nn.functional.scaled_dot_product_attention
+
+ class Pending:
+ def float(self):
+ raise RuntimeError("hipErrorInvalidValue")
+
+ def sdpa(*args, **kwargs):
+ return real(*args, **kwargs) if torch.backends.cuda.math_sdp_enabled() else Pending()
+
+ monkeypatch.setattr(torch.nn.functional, "scaled_dot_product_attention", sdpa)
+ assert probe.probe("cpu", "float32", "FLASH_ATTENTION") == "failed"
+ assert probe.probe("cpu", "float32", "MATH") == "available"
+
+
+def test_probe_rejects_numerically_wrong_fused_result(monkeypatch):
+ real = torch.nn.functional.scaled_dot_product_attention
+
+ def sdpa(*args, **kwargs):
+ result = real(*args, **kwargs)
+ return result if torch.backends.cuda.math_sdp_enabled() else result + 1
+
+ monkeypatch.setattr(torch.nn.functional, "scaled_dot_product_attention", sdpa)
+ assert probe.probe("cpu", "float32", "FLASH_ATTENTION") == "failed"
+
+
+def test_a_successful_retry_after_an_incomplete_probe_still_disables_failed_kernels(monkeypatch):
+ answers = iter([(), ("math",)])
+ monkeypatch.setattr(att, "_is_cuda_rocm", lambda t: True)
+ monkeypatch.setattr(att, "_probe_sdpa_kernels", lambda *a: next(answers, ("math",)))
+ target = SimpleNamespace(device = "cuda:0", dtype = torch.bfloat16)
+ att.apply_attention_backend(SimpleNamespace(), None, target = target)
+ assert not torch.backends.cuda.flash_sdp_enabled()
+ assert not torch.backends.cuda.mem_efficient_sdp_enabled()
+
+
+def test_probe_children_inherit_windows_rocm_dll_directories(monkeypatch, tmp_path):
+ from utils import torch_device_probe
+
+ monkeypatch.setattr(torch_device_probe, "_rocm_dll_directories", lambda: [str(tmp_path)])
+ envs = []
+
+ def run(cmd, **kwargs):
+ envs.append(kwargs["env"])
+ return SimpleNamespace(returncode = 0, stdout = probe.RESULT_PREFIX + '"available"')
+
+ monkeypatch.setattr(subprocess, "run", run)
+ att._probe_rocm_sdpa_kernels("cuda:0", torch.bfloat16)
+ assert envs and all(e[torch_device_probe.ROCM_DLL_DIRS_ENV_VAR] == str(tmp_path) for e in envs)
+
+ added = []
+ monkeypatch.setattr(probe.sys, "platform", "win32")
+ monkeypatch.setattr(os, "add_dll_directory", added.append, raising = False)
+ monkeypatch.setenv(torch_device_probe.ROCM_DLL_DIRS_ENV_VAR, str(tmp_path))
+ probe._register_rocm_dll_directories()
+ assert added == [str(tmp_path)]
+
+
+def test_an_unanswered_probe_needs_no_torch(monkeypatch):
+ import sys
+
+ monkeypatch.setitem(sys.modules, "torch", None)
+ assert att.available_sdpa_kernels(SimpleNamespace(device = "")) == ()
+ assert att.sdpa_math_only(SimpleNamespace(device = "")) is False
+
+
+def test_an_incomplete_child_probe_is_not_relaunched_by_every_check_of_one_load(monkeypatch):
+ calls = []
+
+ def run(cmd, **kwargs):
+ calls.append(cmd[-1])
+ raise subprocess.TimeoutExpired(cmd, 45)
+
+ monkeypatch.setattr(subprocess, "run", run)
+ monkeypatch.setattr(att, "_is_cuda_rocm", lambda t: True)
+ monkeypatch.setattr("core._torchao_stub._module_is_rocm", lambda m: True)
+ target = SimpleNamespace(device = "cuda:0", dtype = torch.bfloat16)
+ att.apply_attention_backend(SimpleNamespace(), None, target = target)
+ assert not att.sdpa_math_only(target)
+ assert calls == ["MATH"]
+ monkeypatch.setattr(att, "_ROCM_PROBE_RETRY_S", 0.0)
+ att.sdpa_math_only(target)
+ assert calls == ["MATH", "MATH"]
+
+
[email protected]("dtype,disabled", [("bfloat16", True), ("float32", False)])
+def test_any_completed_half_precision_probe_applies_its_answer(monkeypatch, dtype, disabled):
+ monkeypatch.setattr(att, "_run_rocm_sdpa_children", lambda device, dtype: ("math",))
+ monkeypatch.setattr("core._torchao_stub._module_is_rocm", lambda m: True)
+ assert att.sdpa_math_only(SimpleNamespace(device = "cuda:0", dtype = getattr(torch, dtype)))
+ assert torch.backends.cuda.flash_sdp_enabled() is not disabled
+ assert torch.backends.cuda.mem_efficient_sdp_enabled() is not disabled
diff --git a/studio/install_python_stack.py b/studio/install_python_stack.py
index ea64652b8ad..93e32f7290f 100644
--- a/studio/install_python_stack.py
+++ b/studio/install_python_stack.py
@@ -377,17 +377,46 @@ def _windows_routes_multiarch(gfx_arch: "str | None") -> bool:
def _multiarch_device_pack_installed(gfx_arch: "str | None") -> bool:
- """Whether the venv carries AMD's torch and torchvision kernel packs for this card."""
+ """Whether the selected device extra is fully installed, family kernel packs included.
+ Names come from wheel metadata: family names differ between AMD releases."""
try:
from importlib import metadata
- names = {
- (d.metadata["Name"] or "").strip().lower().replace("_", "-")
- for d in metadata.distributions()
- }
+ from packaging.requirements import Requirement
+ from packaging.utils import canonicalize_name
+
+ gfx = _bare_gfx(gfx_arch)
+ extra = f"device-{gfx}"
+ for package in ("torch", "torchvision"):
+ root = metadata.distribution(package)
+ pending = [(root, extra)]
+ visited = set()
+ found_leaf = False
+ while pending:
+ dist, selected_extra = pending.pop()
+ key = (canonicalize_name(dist.metadata["Name"]), selected_extra)
+ if key in visited:
+ continue
+ visited.add(key)
+ for raw in dist.requires or ():
+ req = Requirement(raw)
+ name = canonicalize_name(req.name)
+ if not name.startswith(("amd-torch-device-", "amd-torchvision-device-")):
+ continue
+ if req.marker is not None and not req.marker.evaluate(
+ {"extra": selected_extra}
+ ):
+ continue
+ child = metadata.distribution(name)
+ if not req.specifier.contains(child.version, prereleases = True):
+ return False
+ found_leaf |= name == f"amd-{package}-device-{gfx}"
+ pending.append((child, ""))
+ pending.extend((child, e) for e in req.extras)
+ if not found_leaf:
+ return False
+ return True
except Exception:
return False
- gfx = _bare_gfx(gfx_arch)
- return {f"amd-torch-device-{gfx}", f"amd-torchvision-device-{gfx}"} <= names
def _windows_multiarch_torch_pkg_specs(gfx_arch: str) -> tuple[str, str, str]:
@@ -6009,6 +6038,34 @@ def _rocm_torch_family_needs_repair(
) or _generic_only_target_below_floor(runtime_gfx, _installed_tag)
+def _windows_rocm_device_packs_need_dependency_pass() -> bool:
+ """For setup.ps1's fast path: would _ensure_rocm_torch repair this multi-arch ROCm torch?
+
+ Same gates as that repair, read from wheel metadata only; fails closed and never installs.
+ """
+ if not IS_WINDOWS or NO_TORCH or _TORCH_BACKEND in ("cuda", "cpu", "xpu"):
+ return False
+ try:
+ if (
+ _explicit_unknown_family_torch_index_url() is not None
+ or _explicit_torch_index_is_unusable()
+ or _explicit_rocm_torch_index_url() is not None
+ or _has_usable_nvidia_gpu()
+ ):
+ return False
+ gfx_arch = _detect_windows_gfx_arch()
+ if not gfx_arch or not _windows_routes_multiarch(gfx_arch):
+ return False
+ from importlib import metadata
+
+ tag = metadata.version("torch").lower().rpartition("+")[2]
+ except Exception: # noqa: BLE001 - an unreadable host keeps the fast path
+ return False
+ if not tag.startswith("rocm"):
+ return False
+ return tag in _ROCM_MULTIARCH_BROKEN_TAGS or not _multiarch_device_pack_installed(gfx_arch)
+
+
def _ensure_rocm_torch() -> "bool | None":
"""Reinstall torch with ROCm wheels when the venv received CPU-only torch.
@@ -6035,17 +6092,24 @@ def _ensure_rocm_torch() -> "bool | None":
)
if _explicit_torch_index_is_unusable() and (IS_WINDOWS or not _rocm_pin_unusable):
return
- # setup.ps1's marker; trust it only when torch imports as ROCm (a wiped venv leaves it stale).
+ # setup.ps1's marker cannot prove that the device extra is still complete.
if os.environ.get("UNSLOTH_ROCM_TORCH_INSTALLED") == "1":
_ran, _importable, _version, _hip, _cuda = _probe_torch_runtime()
_torch_ok = _ran and _importable and (bool(_hip) or "rocm" in (_version or "").lower())
+ if _torch_ok and IS_WINDOWS and _explicit_rocm_torch_index_url() is None:
+ _marker_gfx = _detect_windows_gfx_arch()
+ if _windows_routes_multiarch(_marker_gfx):
+ _torch_ok = (
+ _multiarch_device_pack_installed(_marker_gfx)
+ and (_version or "").lower().rpartition("+")[2]
+ not in _ROCM_MULTIARCH_BROKEN_TAGS
+ )
if _torch_ok:
_rocm_windows_torch_installed = True
# ROCm torch is already installed, but bnb still needs the ROCm build
# (pre-release wheel, else PyPI >=0.50.0).
_install_bnb_windows_rocm()
return
- # torch was wiped between runs; fall through to the full install path
if IS_MACOS:
return
@@ -6077,7 +6141,7 @@ def _ensure_rocm_torch() -> "bool | None":
and not _multiarch_device_pack_installed(gfx_arch)
):
_safe_print(
- f" installed ROCm torch has no {gfx_arch} device pack -- reinstalling from "
+ f" installed ROCm torch has incomplete or mismatched {gfx_arch} device packs -- reinstalling from "
"AMD's multi-arch index"
)
_torch_already_rocm = False
@@ -12820,6 +12884,9 @@ if __name__ == "__main__":
f"probe={_TORCH_RUNTIME_PROBE!r}"
)
sys.exit(0 if _needs_pass else 1)
+ if sys.argv[1:] == ["--windows-rocm-device-packs-need-dependency-pass"]:
+ # Exit 0 forces the dependency pass; exit 1 keeps the fast path.
+ sys.exit(0 if _windows_rocm_device_packs_need_dependency_pass() else 1)
if sys.argv[1:] == ["--cuda-torch-needs-dependency-pass"]:
# Exit 0 forces the dependency pass; exit 1 keeps the fast path.
sys.exit(0 if _cuda_torch_needs_dependency_pass() else 1)
diff --git a/studio/setup.ps1 b/studio/setup.ps1
index ad0c2647ff6..e06daaf0178 100644
--- a/studio/setup.ps1
+++ b/studio/setup.ps1
@@ -8324,6 +8324,16 @@ sys.exit(2 if conflict else (0 if version else 1))
substep "AMD GPU ($script:ROCmGfxArch) detected but installed PyTorch is CPU-only -- reinstalling ROCm PyTorch" "Cyan"
$SkipPythonDeps = $false
}
+ # A ROCm torch whose device extra lost a family kernel pack still sees the GPU.
+ if ($SkipPythonDeps) {
+ try {
+ & python (Join-Path $PSScriptRoot "install_python_stack.py") --windows-rocm-device-packs-need-dependency-pass *> $null
+ if ($LASTEXITCODE -eq 0) {
+ substep "AMD device packs are incomplete or mismatched -- forcing dependency pass to repair..." "Cyan"
+ $SkipPythonDeps = $false
+ }
+ } catch {}
+ }
}
}
}
diff --git a/tests/studio/install/test_rdna1_multiarch_windows_route_11614.py b/tests/studio/install/test_rdna1_multiarch_windows_route_11614.py
index 2a4432d8e18..f9d89e3eea6 100644
--- a/tests/studio/install/test_rdna1_multiarch_windows_route_11614.py
+++ b/tests/studio/install/test_rdna1_multiarch_windows_route_11614.py
@@ -351,19 +351,34 @@ class TestTheWindowsRepairSiteRunsForRdna1:
def test_the_device_pack_check_needs_torch_and_torchvision_packs(self, monkeypatch):
from importlib import metadata
+ from types import SimpleNamespace
+
+ def installed(*names):
+ dists = {
+ package: SimpleNamespace(
+ metadata = {"Name": package},
+ version = "2.11.0",
+ requires = [f'amd-{package}-device-gfx1010==2.11.0; extra == "device-gfx1010"'],
+ )
+ for package in ("torch", "torchvision")
+ }
+ dists.update(
+ (n, SimpleNamespace(metadata = {"Name": n}, version = "2.11.0", requires = None))
+ for n in names
+ )
+
+ def distribution(name):
+ if name not in dists:
+ raise metadata.PackageNotFoundError(name)
+ return dists[name]
- def dists(*names):
- return lambda: [type("D", (), {"metadata": {"Name": n}})() for n in names]
+ monkeypatch.setattr(metadata, "distribution", distribution)
- monkeypatch.setattr(metadata, "distributions", dists("torch"))
+ installed()
assert stack_mod._multiarch_device_pack_installed("GFX1010:xnack-") is False
- monkeypatch.setattr(metadata, "distributions", dists("amd_torch_device_gfx1010"))
+ installed("amd-torch-device-gfx1010")
assert stack_mod._multiarch_device_pack_installed("GFX1010:xnack-") is False
- monkeypatch.setattr(
- metadata,
- "distributions",
- dists("amd-torch-device-gfx1010", "amd-torchvision-device-gfx1010"),
- )
+ installed("amd-torch-device-gfx1010", "amd-torchvision-device-gfx1010")
assert stack_mod._multiarch_device_pack_installed("GFX1010:xnack-") is True
diff --git a/tests/studio/install/test_rocm_device_extra_integrity.py b/tests/studio/install/test_rocm_device_extra_integrity.py
new file mode 100644
index 00000000000..e412c51688c
--- /dev/null
+++ b/tests/studio/install/test_rocm_device_extra_integrity.py
@@ -0,0 +1,178 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+from importlib import metadata
+from types import SimpleNamespace
+
+import pytest
+
+from test_windows_multiarch_all_11815 import stack_mod
+
+
+def installed(monkeypatch):
+ packages = {}
+
+ def add(
+ name,
+ version,
+ requirements = (),
+ ):
+ packages[name] = SimpleNamespace(
+ metadata = {"Name": name}, version = version, requires = list(requirements)
+ )
+
+ for package, version in (("torch", "2.11.0+rocm7.14.0"), ("torchvision", "0.26.0+rocm7.14.0")):
+ leaf = f"amd-{package}-device-gfx1100"
+ family = f"amd-{package}-device-gfx110x"
+ add(
+ package,
+ version,
+ [
+ f'{leaf}=={version}; extra == "device-gfx1100"',
+ f'{family}=={version}; extra == "device-gfx1100"',
+ f'amd-{package}-device-gfx1151=={version}; extra == "device-gfx1151"',
+ ],
+ )
+ add(leaf, version)
+ add(family, version)
+
+ def distribution(name):
+ if name not in packages:
+ raise metadata.PackageNotFoundError(name)
+ return packages[name]
+
+ monkeypatch.setattr(metadata, "distribution", distribution)
+ return packages, add
+
+
+def test_complete_selected_extra_is_accepted(installed):
+ assert stack_mod._multiarch_device_pack_installed("gfx1100:xnack-")
+
+
[email protected]("package", ["torch", "torchvision"])
[email protected]("part", ["gfx1100", "gfx110x"])
[email protected]("damage", ["missing", "version"])
+def test_leaf_names_do_not_hide_missing_or_mismatched_packs(installed, package, part, damage):
+ packages, _ = installed
+ name = f"amd-{package}-device-{part}"
+ if damage == "missing":
+ del packages[name]
+ else:
+ packages[name].version = "2.12.0+rocm7.14.0"
+ assert not stack_mod._multiarch_device_pack_installed("gfx1100")
+
+
+def test_family_names_come_from_wheel_metadata_and_dependencies_are_recursive(installed):
+ packages, add = installed
+ version = packages["torch"].version
+ packages["torch"].requires = [f'amd-torch-device-gfx1100=={version}; extra == "device-gfx1100"']
+ packages["amd-torch-device-gfx1100"].requires = [f"amd-torch-device-gfx11=={version}"]
+ assert not stack_mod._multiarch_device_pack_installed("gfx1100")
+ add("amd-torch-device-gfx11", version, [f"amd-torch-device-gfx1100=={version}"])
+ assert stack_mod._multiarch_device_pack_installed("gfx1100")
+
+
[email protected]("requirements", [[], ["not a requirement"]])
+def test_missing_or_invalid_extra_metadata_requires_repair(installed, requirements):
+ packages, _ = installed
+ packages["torch"].requires = requirements
+ assert not stack_mod._multiarch_device_pack_installed("gfx1100")
+
+
[email protected]("marker", ["0", "1"])
[email protected]("damage", [None, "missing", "version"])
+def test_update_repairs_the_selected_extra_even_with_setup_marker(
+ installed, monkeypatch, marker, damage
+):
+ packages, _ = installed
+ family = "amd-torch-device-gfx110x"
+ if damage == "missing":
+ del packages[family]
+ elif damage == "version":
+ packages[family].version = "2.12.0+rocm7.14.0"
+ monkeypatch.setenv("UNSLOTH_ROCM_TORCH_INSTALLED", marker)
+ monkeypatch.delenv("UNSLOTH_ROCM_WINDOWS_MIRROR", raising = False)
+ monkeypatch.delenv("UNSLOTH_ROCM_WINDOWS_MULTIARCH_MIRROR", raising = False)
+ for name, value in {
+ "IS_WINDOWS": True,
+ "IS_MACOS": False,
+ "_TORCH_BACKEND": "rocm",
+ "_rocm_windows_torch_installed": False,
+ }.items():
+ monkeypatch.setattr(stack_mod, name, value)
+ for name, result in {
+ "_explicit_unknown_family_torch_index_url": None,
+ "_explicit_torch_index_family": "",
+ "_explicit_torch_index_is_unusable": False,
+ "_explicit_rocm_torch_index_url": None,
+ "_has_usable_nvidia_gpu": False,
+ "_detect_windows_gfx_arch": "gfx1100",
+ "_probe_torch_runtime": (True, True, "2.11.0+rocm7.14.0", "7.14", None),
+ "_install_bnb_windows_rocm": True,
+ "_is_win_arm64_interpreter": False,
+ }.items():
+ monkeypatch.setattr(stack_mod, name, lambda result = result: result)
+ calls = []
+
+ def install(*args, **kwargs):
+ calls.append(args)
+ return True
+
+ monkeypatch.setattr(stack_mod, "pip_install_try", install)
+ stack_mod._ensure_rocm_torch()
+ assert stack_mod._rocm_windows_torch_installed
+ assert len(calls) == int(damage is not None)
+ if calls:
+ assert "--force-reinstall" in calls[0]
+ assert any(arg.startswith("torch[device-gfx1100]==") for arg in calls[0])
+ assert any(arg.startswith("torchvision[device-gfx1100]==") for arg in calls[0])
+
+
+def _fast_path_host(
+ monkeypatch,
+ installed,
+ *,
+ tag = "rocm7.14.0",
+ pinned = False,
+ nvidia = False,
+):
+ packages, _ = installed
+ packages["torch"].version = f"2.11.0+{tag}"
+ monkeypatch.setattr(stack_mod, "IS_WINDOWS", True)
+ monkeypatch.setattr(stack_mod, "NO_TORCH", False)
+ monkeypatch.setattr(stack_mod, "_TORCH_BACKEND", "")
+ monkeypatch.setattr(stack_mod, "_explicit_unknown_family_torch_index_url", lambda: None)
+ monkeypatch.setattr(stack_mod, "_explicit_torch_index_is_unusable", lambda: False)
+ monkeypatch.setattr(
+ stack_mod, "_explicit_rocm_torch_index_url", lambda: "https://pin/" if pinned else None
+ )
+ monkeypatch.setattr(stack_mod, "_has_usable_nvidia_gpu", lambda: nvidia)
+ monkeypatch.setattr(stack_mod, "_detect_windows_gfx_arch", lambda: "gfx1100")
+ monkeypatch.setattr(stack_mod, "_windows_routes_multiarch", lambda gfx: True)
+ monkeypatch.setattr(metadata, "version", lambda name: packages[name].version)
+ return packages
+
+
+def test_setup_fast_path_keeps_a_complete_extra(monkeypatch, installed):
+ _fast_path_host(monkeypatch, installed)
+ assert stack_mod._windows_rocm_device_packs_need_dependency_pass() is False
+
+
+def test_setup_fast_path_runs_the_repair_for_a_missing_family_pack(monkeypatch, installed):
+ packages = _fast_path_host(monkeypatch, installed)
+ del packages["amd-torch-device-gfx110x"]
+ assert stack_mod._windows_rocm_device_packs_need_dependency_pass() is True
+
+
[email protected]("host", [dict(pinned = True), dict(nvidia = True), dict(tag = "cpu")])
+def test_setup_fast_path_leaves_other_routes_alone(monkeypatch, installed, host):
+ packages = _fast_path_host(monkeypatch, installed, **host)
+ del packages["amd-torch-device-gfx110x"]
+ assert stack_mod._windows_rocm_device_packs_need_dependency_pass() is False
+
+
+def test_setup_ps1_consults_the_device_pack_probe():
+ from pathlib import Path
+ source = (Path(stack_mod.__file__).parent / "setup.ps1").read_text(encoding = "utf-8")
+ assert "--windows-rocm-device-packs-need-dependency-pass" in source
diff --git a/tests/studio/install/test_rocm_support.py b/tests/studio/install/test_rocm_support.py
index e916000d2ca..30f9df201ce 100644
--- a/tests/studio/install/test_rocm_support.py
+++ b/tests/studio/install/test_rocm_support.py
@@ -1014,6 +1014,21 @@ class TestEnsureRocmTorch:
pip_install_try mock so callers can assert on the reinstall."""
probe = MagicMock(returncode = 0, stdout = _MARK + "2.10.0+rocm7.1|7.1|\n")
pip_try = MagicMock(return_value = True)
+ from importlib.metadata import PackageNotFoundError
+ from types import SimpleNamespace
+
+ packages = {d.metadata["Name"].lower().replace("_", "-"): d for d in dists}
+ for package in ("torch", "torchvision"):
+ packages[package] = SimpleNamespace(
+ metadata = {"Name": package},
+ requires = [f'amd-{package}-device-{gfx}==2.11.0; extra == "device-{gfx}"'],
+ )
+
+ def distribution(name):
+ if name not in packages:
+ raise PackageNotFoundError(name)
+ return packages[name]
+
with patch.dict(os.environ, {}, clear = False):
os.environ.pop("UNSLOTH_ROCM_TORCH_INSTALLED", None)
with (
@@ -1033,6 +1048,7 @@ class TestEnsureRocmTorch:
patch.object(stack_mod, "pip_install_try", pip_try),
patch("subprocess.run", return_value = probe),
patch("importlib.metadata.distributions", return_value = list(dists)),
+ patch("importlib.metadata.distribution", side_effect = distribution),
):
_ensure_rocm_torch()
return pip_try
@@ -1076,6 +1092,8 @@ class TestEnsureRocmTorch:
for n in names:
d = MagicMock()
d.metadata = {"Name": n}
+ d.version = "2.11.0"
+ d.requires = []
out.append(d)
return out