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): let diffusion load on Windows ROCm, and say what a gated repo needs (#7981)
Leo Borcherding6e18ebf53107
diff --git a/studio/backend/core/_torchao_stub.py b/studio/backend/core/_torchao_stub.pyindex 6336954bd51..e024027409b 100644--- a/studio/backend/core/_torchao_stub.py+++ b/studio/backend/core/_torchao_stub.py@@ -1,7 +1,7 @@# SPDX-License-Identifier: AGPL-3.0-only# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0-"""Shared torchao Windows-ROCm import stub.+"""Shared Windows-ROCm import stubs.torchao (pulled in by transformers.quantizers) imports distributed_c10d.pyunconditionally, which crashes on Windows ROCm because the RCCL backend@@ -9,14 +9,21 @@ unconditionally, which crashes on Windows ROCm because the RCCL backendimport chain; _StubSubpackageFinder handles any depth of torchao.xxx.yyy.Worker subprocesses call install_torchao_windows_rocm_stub() before importingtransformers / unsloth_zoo.++xformers hits the same absent backend and takes diffusers with it, so the diffusion paths+install both stubs before importing diffusers."""from __future__ import annotations+import os+import reimport sysimport typesimport importlib.abcimport importlib.machinery+import importlib.util+from typing import Optional_STUB_SENTINEL = object()@@ -100,29 +107,108 @@ class _StubSubpackageFinder(importlib.abc.MetaPathFinder):)+def _module_is_rocm(mod) -> bool:+ """Whether an already-imported torch module is a ROCm build. Some ROCm wheels lack+ torch.version.hip but still encode "rocm" in __version__."""+ return bool(+ getattr(getattr(mod, "version", None), "hip", None)+ or "rocm" in getattr(mod, "__version__", "").lower()+ )+++# torch/version.py is generated, always as ``hip: Optional[str] = None`` on CUDA, ``= '6.4.5...'`` on ROCm.+_HIP_LINE_RE = re.compile(r"^hip\s*(?::[^=]*)?=\s*(.+?)\s*$", re.MULTILINE)+++def _version_is_rocm_tagged() -> Optional[bool]:+ """Whether the installed wheel's version carries a rocm tag. None if unreadable."""+ try:+ from importlib.metadata import version+ return "rocm" in version("torch").lower()+ except Exception: # noqa: BLE001 -- no dist-info / unreadable METADATA+ return None+++def _hip_field_is_set() -> Optional[bool]:+ """Whether torch/version.py's ``hip`` field names a ROCm version, None if unreadable.+ find_spec resolves the path without executing torch."""+ try:+ spec = importlib.util.find_spec("torch")+ origin = getattr(spec, "origin", None) if spec is not None else None+ if not origin:+ return None+ with open(+ os.path.join(os.path.dirname(origin), "version.py"),+ encoding = "utf-8",+ errors = "replace",+ ) as handle:+ found = _HIP_LINE_RE.search(handle.read())+ if found is None:+ return None+ return found.group(1).strip().strip("\"'") not in ("None", "")+ except Exception: # noqa: BLE001 -- an unreadable tree is not a verdict+ return None+++def _installed_torch_is_rocm() -> Optional[bool]:+ """ROCm or not, read off disk without importing torch. None when it cannot be told.++ Avoiding the import is the point: run.py calls this at import time, where torch costs seconds,+ sizes the OpenMP/BLAS pools before configure_cpu_threads() can set them, and on Windows ROCm+ can fail outright until main.py has registered the HIP DLL directories. Neither signal alone+ is enough: AMD's Windows build (torch-2.8.0a0+gitfc14c65) carries no rocm tag so only ``hip``+ answers, while a wheel without dist-info has no version to read. So a NEGATIVE needs BOTH+ signals legible and both saying no.+ """+ tagged = _version_is_rocm_tagged()+ if tagged:+ return True+ hip = _hip_field_is_set()+ if hip:+ return True+ return False if (tagged is False and hip is False) else None+++def _is_windows_rocm() -> bool:+ """True on a Windows host whose active torch is a ROCm build."""+ # Gate on the active torch runtime, not env vars: HIP_PATH/ROCM_PATH outlive a revert to CUDA.+ if sys.platform != "win32":+ return False+ mod = sys.modules.get("torch")+ if mod is not None:+ return _module_is_rocm(mod)+ verdict = _installed_torch_is_rocm()+ if verdict is not None:+ return verdict+ # Neither on-disk signal was readable, so importing is the only way left.+ try:+ import torch+ except Exception:+ return False+ return _module_is_rocm(torch)+++def _ensure_finder() -> None:+ """Register the subpackage finder once, however many stubs are installed."""+ if not any(isinstance(f, _StubSubpackageFinder) for f in sys.meta_path):+ sys.meta_path.append(_StubSubpackageFinder())+++def is_stubbed(package: str) -> bool:+ """True iff ``package`` resolves to one of these stubs. ``find_spec`` and even+ ``from torchao.quantization import quantize_`` succeed against a stub, so any caller+ that needs the package to WORK must ask this first."""+ return getattr(sys.modules.get(package), "_unsloth_stub", None) is _STUB_SENTINEL++def install_torchao_windows_rocm_stub() -> None:"""Pre-stub torchao on Windows ROCm so transformers/peft imports don't crash.No-op elsewhere (incl. Windows CUDA, where torchao is real). Must run beforeimporting transformers / unsloth_zoo. Safe to call once per worker."""- # Gate on the active torch runtime, not env-var presence -- HIP_PATH/ROCM_PATH- # persist after reverting to a CUDA wheel. Some ROCm wheels lack- # torch.version.hip but still encode "rocm" in __version__, so accept either.- _is_win32_rocm = False- if sys.platform == "win32":- try:- import torch as _torch_probe- _is_win32_rocm = bool(- getattr(getattr(_torch_probe, "version", None), "hip", None)- or "rocm" in getattr(_torch_probe, "__version__", "").lower()- )- del _torch_probe- except Exception:- pass- if _is_win32_rocm:- # Register the finder only on Windows ROCm.- sys.meta_path.append(_StubSubpackageFinder())+ if _is_windows_rocm():+ _ensure_finder()# Seed torchao top-level + key submodules; the finder handles the rest.for _tao_name in ("torchao",@@ -133,3 +219,15 @@ def install_torchao_windows_rocm_stub() -> None:):if _tao_name not in sys.modules:sys.modules[_tao_name] = _make_mod_stub(_tao_name)+++def install_xformers_windows_rocm_stub() -> None:+ """Pre-stub xformers on Windows ROCm so diffusers can import at all. No-op elsewhere, and must+ precede diffusers: the Windows xformers pin is CUDA-only, so against a ROCm torch (no+ distributed backend) ``import xformers.ops`` dies in torch.distributed, and diffusers imports+ xformers on sight, taking every model import with it."""+ if _is_windows_rocm():+ _ensure_finder()+ for _xf_name in ("xformers", "xformers.ops"):+ if _xf_name not in sys.modules:+ sys.modules[_xf_name] = _make_mod_stub(_xf_name)diff --git a/studio/backend/core/inference/diffusion.py b/studio/backend/core/inference/diffusion.pyindex fd3eb6e7f0a..a66f982cff2 100644--- a/studio/backend/core/inference/diffusion.py+++ b/studio/backend/core/inference/diffusion.py@@ -21,12 +21,17 @@ from __future__ import annotationsimport inspectimport jsonimport os+import reimport threadingimport timefrom dataclasses import dataclassfrom pathlib import Pathfrom typing import Any, Callable, Optional+from core._torchao_stub import (+ install_torchao_windows_rocm_stub,+ install_xformers_windows_rocm_stub,+)from loggers import get_loggerfrom utils.hardware import clear_gpu_cache@@ -131,6 +136,11 @@ from .diffusion_transformer_quant import (logger = get_logger(__name__)+# Every `import diffusers` below is lazy, so this runs first. On Windows ROCm both reach an absent+# distributed backend: diffusers imports xformers on sight, its quantizers torchao.+install_xformers_windows_rocm_stub()+install_torchao_windows_rocm_stub()+# "gguf" and "single_file" take companions from the base repo; "pipeline" is a full diffusers repo._MODEL_KINDS = frozenset({"gguf", "single_file", "pipeline"})@@ -146,6 +156,63 @@ def hub_cache_dir() -> str:return active_hf_hub_cache()+# Repo id out of any hub URL in an error. A gated PUBLIC repo raises a download URL,+# ".../huggingface.co/<owner>/<name>/resolve/..."; auth_check, and model_info on a gated PRIVATE+# repo, raise ".../huggingface.co/api/models/<owner>/<name>", which without the prefix branch would yield "api/models".+_HUB_REPO_RE = re.compile(+ r"huggingface\.co/(?:api/(?:models|datasets|spaces)/)?([\w.\-]+/[\w.\-]+)"+)+++def _gated_in_chain(exc: BaseException) -> Optional[BaseException]:+ """The GatedRepoError in ``exc``'s cause/context chain, or None. Transformers loads re-raise+ the 403 wrapped in an OSError, so the outermost error alone misses the case this exists for.+ Screened by class name across the MRO, so no hub import."""+ seen: set[int] = set()+ while exc is not None and id(exc) not in seen:+ seen.add(id(exc))+ if any(cls.__name__ == "GatedRepoError" for cls in type(exc).__mro__):+ return exc+ # `raise ... from None` means the raiser already wrote a better message (the base-repo preflight does), so stop.+ exc = exc.__cause__ or (None if exc.__suppress_context__ else exc.__context__)+ return None+++def _hf_token_in_play(hf_token: Optional[str]) -> bool:+ """Whether the failing Hub call carried ANY credential, not just Studio's own: with token=None+ huggingface_hub still falls back to HF_TOKEN or the cached CLI login, so keying off the request+ token alone loops an already-authenticated user."""+ if hf_token:+ return True+ try:+ # What build_hf_headers calls: under HF_HUB_DISABLE_IMPLICIT_TOKEN get_token() still answers while the request goes out anonymous.+ from huggingface_hub.utils import get_token_to_send+ return bool(get_token_to_send(None))+ except Exception: # noqa: BLE001 -- assume none; at worst the message says "add a token"+ return False+++def hub_access_message(exc: BaseException, *, had_token: bool) -> Optional[str]:+ """Rewrite a gated-repo failure into the step that actually unblocks the user, else None so an+ unrelated load error keeps its own text. Only the toast is affected; the raw exception, request+ id and resolve URL still reach the log."""+ gated = _gated_in_chain(exc)+ if gated is None:+ return None+ found = _HUB_REPO_RE.search(str(gated))+ # An API URL ends at the repo, so a trailing full stop lands inside the name (dots are legal mid-name, but a name never ends in one).+ repo = found.group(1).rstrip(".") if found else None+ # Any other /api/<endpoint> URL (whoami-v2, ...) would parse as the repo "api/<endpoint>".+ if repo and repo.split("/", 1)[0] == "api":+ repo = None+ where = f"https://huggingface.co/{repo}" if repo else "its Hugging Face page"+ subject = repo or "This model"+ if had_token:+ # A token was sent and still bounced, so the account itself lacks access.+ return f"{subject} is gated and this Hugging Face account is not on its access list. Request access at {where}, then load again."+ return f"{subject} is gated. Request access at {where}, then add a Hugging Face token in Settings and load again."++def resolve_model_kind(gguf_filename: Optional[str], model_kind: Optional[str] = None) -> str:"""Classify a load request into one of ``_MODEL_KINDS``.@@ -1297,12 +1364,20 @@ class DiffusionBackend:clear_gpu_cache()except Exception: # noqa: BLE001pass- # Redact native paths: this error is surfaced verbatim and Studio can be shared.+ # Rewrite a gated-repo 403 into the step that unblocks the user, then redact native paths:+ # this text is surfaced verbatim and Studio can be shared. Guarded because on this daemon+ # thread anything escaping leaves _loading.error unset and load_progress() stuck forever.from utils.native_path_leases import redact_native_paths+ try:+ text = hub_access_message(+ exc, had_token = _hf_token_in_play(kwargs.get("hf_token"))+ ) or str(exc)+ except Exception: # noqa: BLE001+ text = str(exc)with self._lock:if self._load_token == token and self._loading is not None:- self._loading.error = redact_native_paths(str(exc))+ self._loading.error = redact_native_paths(text)def load_progress(self) -> dict[str, Any]:"""Phase + downloaded/total bytes for the in-flight load (cache-scan based)."""diff --git a/studio/backend/core/inference/diffusion_attention.py b/studio/backend/core/inference/diffusion_attention.pyindex 77a8ba6d27b..6ccc3c4fdfb 100644--- a/studio/backend/core/inference/diffusion_attention.py+++ b/studio/backend/core/inference/diffusion_attention.py@@ -102,7 +102,11 @@ def _is_cuda_nvidia(target: Any) -> bool:return Falsetry:import torch- return getattr(torch.version, "hip", None) is None++ # Shared with the stub installer: torch.version.hip alone misreads AMD wheels that only tag+ # __version__, dropping aiter and pointing cuDNN/xformers (stubbed there) at a ROCm card.+ from core._torchao_stub import _module_is_rocm+ return not _module_is_rocm(torch)except Exception: # noqa: BLE001return Falsediff --git a/studio/backend/core/inference/diffusion_precision.py b/studio/backend/core/inference/diffusion_precision.pyindex f253eed1a1b..859c3ea5f7c 100644--- a/studio/backend/core/inference/diffusion_precision.py+++ b/studio/backend/core/inference/diffusion_precision.py@@ -27,11 +27,16 @@ from __future__ import annotationsfrom typing import Any, Optional+# stdlib-only module (no torch), so this stays inside the "imported lazily" promise above.+from core._torchao_stub import is_stubbed+TE_QUANT_FP8 = "fp8"TE_QUANT_NVFP4 = "nvfp4"TE_QUANT_INT8 = "int8"TE_QUANT_FP8_DYNAMIC = "fp8_dynamic"TE_QUANT_MODES = (TE_QUANT_FP8, TE_QUANT_NVFP4, TE_QUANT_INT8, TE_QUANT_FP8_DYNAMIC)+# The modes that go through torchao; plain fp8 is a layerwise torch cast and needs none.+_TE_TORCHAO_MODES = frozenset({TE_QUANT_INT8, TE_QUANT_FP8_DYNAMIC, TE_QUANT_NVFP4})# Pipeline attributes that hold a text encoder, in order._TEXT_ENCODER_ATTRS = ("text_encoder", "text_encoder_2", "text_encoder_3")@@ -68,6 +73,11 @@ def te_quant_supported(target: Any, mode: str) -> bool:Blackwell sm_100+ (nvfp4)."""if getattr(target, "device", None) != "cuda":return False+ # The Windows-ROCm torchao stub's quantize_ is a no-op, so the encoder stays bf16 while+ # quantize_text_encoders reports the mode applied. ROCm answers device "cuda" and a+ # capability pair, so nothing below would catch it.+ if mode in _TE_TORCHAO_MODES and is_stubbed("torchao"):+ return Falsetry:import torchdiff --git a/studio/backend/core/inference/diffusion_transformer_quant.py b/studio/backend/core/inference/diffusion_transformer_quant.pyindex fdd18d57a9a..e9189bbf7d2 100644--- a/studio/backend/core/inference/diffusion_transformer_quant.py+++ b/studio/backend/core/inference/diffusion_transformer_quant.py@@ -25,6 +25,9 @@ from __future__ import annotationsfrom typing import Any, Optional+# stdlib-only module (no torch), so this stays inside the "imported lazily" promise above.+from core._torchao_stub import is_stubbed+TQ_INT8 = "int8"TQ_FP8 = "fp8"TQ_NVFP4 = "nvfp4"@@ -219,6 +222,11 @@ def dense_transformer_supported(target: Any) -> bool:dtype (the only config any torchao dynamic scheme accelerates). Cheap loader pre-check."""if getattr(target, "device", None) != "cuda":return False+ # The Windows-ROCm torchao stub's quantize_ is a no-op, so the smoke probe passes on a+ # still-dense Linear and the transformer gets MARKED quantised without being quantised,+ # giving the wrong VRAM budget and compile policy.+ if is_stubbed("torchao"):+ return Falsetry:import torchreturn getattr(target, "dtype", None) is torch.bfloat16diff --git a/studio/backend/core/inference/worker.py b/studio/backend/core/inference/worker.pyindex 6d7d07630f6..a045c8e228a 100644--- a/studio/backend/core/inference/worker.py+++ b/studio/backend/core/inference/worker.py@@ -1068,8 +1068,7 @@ def run_inference_process(return# ── Windows: check Triton availability ──- # Placed ahead of the torchao stub below (which imports torch on win32 to detect ROCm),- # matching the training and export workers' gate-then-stub ordering.+ # Ahead of the torchao stub below, matching the training and export workers' gate-then-stub order.if sys.platform == "win32":try:import triton # noqa: F401diff --git a/studio/backend/core/training/diffusion_dit_trainer.py b/studio/backend/core/training/diffusion_dit_trainer.pyindex 6a00e00955a..fe4124a894f 100644--- a/studio/backend/core/training/diffusion_dit_trainer.py+++ b/studio/backend/core/training/diffusion_dit_trainer.py@@ -36,6 +36,7 @@ from dataclasses import dataclass, replacefrom pathlib import Pathfrom typing import Any, Callable, Optional+from core._torchao_stub import is_stubbedfrom core.training.diffusion_train_common import (DEFAULT_LORA_FILENAME,DEFAULT_LORA_TARGETS,@@ -483,6 +484,13 @@ def _resolve_base_precision(cfg, spec, device) -> str:"torchao is missing or the non-functional Windows-ROCm stub. Use ""base_precision='nf4', 'bf16', or 'auto'.")+ # The stub answers torchao.float8 / torchao.prototype.mx_formats with a no-op that reports success, so the run would report fp8 while training bf16.+ # Keyed on the stub, not has_functional_torchao(): that probes int8's symbols, and a real-but-partial torchao must still reach the arch checks below.+ if mode in ("fp8", "mxfp8") and is_stubbed("torchao"):+ raise ValueError(+ f"base_precision={mode!r} is not available on this host: torchao is the "+ "non-functional Windows-ROCm stub. Use base_precision='nf4', 'bf16', or 'auto'."+ )# mxfp8 needs Blackwell (sm100+): its MX GEMM raises at the first training step, after a full dense load. Re-check here to fail fast for a stale client.if mode == "mxfp8" and device == "cuda":try:diff --git a/studio/backend/core/training/diffusion_train_common.py b/studio/backend/core/training/diffusion_train_common.pyindex 7659ebaef62..75e0b64b81f 100644--- a/studio/backend/core/training/diffusion_train_common.py+++ b/studio/backend/core/training/diffusion_train_common.py@@ -25,6 +25,11 @@ from dataclasses import dataclass, replacefrom pathlib import Pathfrom typing import Any, Callable, Optional+from core._torchao_stub import (+ install_torchao_windows_rocm_stub,+ install_xformers_windows_rocm_stub,+ is_stubbed,+)from core.inference.diffusion_families import (detect_family,detect_family_for_pick,@@ -32,6 +37,10 @@ from core.inference.diffusion_families import (trainable_family_names,)+# The trainers run in a spawned child that imports diffusers itself, so the inference-side install does not carry over. Both import this module first.+install_xformers_windows_rocm_stub()+install_torchao_windows_rocm_stub()+# Default LoRA target modules: the attention projections common to the SDXL U-Net and the DiTs (the diffusers/kohya convention). A family may override this.DEFAULT_LORA_TARGETS: tuple[str, ...] = ("to_k", "to_q", "to_v", "to_out.0")@@ -397,12 +406,12 @@ def dit_accelerator_missing_reason(resolved_family: str) -> Optional[str]:def training_precision_preflight_error(resolved_family: str, base_precision: str) -> Optional[str]:"""Reason the requested DiT precision cannot run on this host, else None -- checked by thestart route BEFORE evicting resident GPU workloads (the trainer's own checks fire only in the- child, after eviction). Four gates, all mirroring _resolve_base_precision so a doomed run is- rejected before teardown: the bf16-GPU requirement (bf16_unsupported_reason); a host with no- accelerator at all (dit_accelerator_missing_reason, which covers nf4 too); the dense- precisions (bf16/int8/fp8/mxfp8) requiring a CUDA GPU; an explicit int8 needing a FUNCTIONAL- torchao (its _int8_quantize_base has no fallback); and an explicit mxfp8 needing a Blackwell- (sm100+) GPU (its MX GEMM has no kernel below sm100). Never raises."""+ child, after eviction). Every gate mirrors one in _resolve_base_precision, so a doomed run is+ rejected before teardown: the bf16-GPU requirement (bf16_unsupported_reason); no accelerator at+ all (dit_accelerator_missing_reason, which covers nf4 too); the dense precisions+ (bf16/int8/fp8/mxfp8) needing CUDA; explicit int8 needing a FUNCTIONAL torchao (its+ _int8_quantize_base has no fallback); explicit fp8/mxfp8 against the Windows-ROCm torchao stub;+ explicit mxfp8 needing Blackwell (sm100+). Add a gate there, add it here. Never raises."""reason = bf16_unsupported_reason(resolved_family)if reason:return reason@@ -429,6 +438,12 @@ def training_precision_preflight_error(resolved_family: str, base_precision: str"base_precision='int8' needs a functional torchao install; this host's torchao is ""missing or the non-functional Windows-ROCm stub. Use 'nf4', 'bf16', or 'auto'.")+ # Mirrors the child's fp8/mxfp8 stub guard so a doomed run is refused before eviction. Not has_functional_torchao(): that probes int8's symbols.+ if mode in ("fp8", "mxfp8") and is_stubbed("torchao"):+ return (+ f"base_precision={mode!r} is not available on this host: torchao is the "+ "non-functional Windows-ROCm stub. Use 'nf4', 'bf16', or 'auto'."+ )# mxfp8 needs Blackwell (sm100+): its MX GEMM raises at the first training step, AFTER a full dense load. Re-check here so a stale client fails fast before eviction.if mode == "mxfp8":try:diff --git a/studio/backend/run.py b/studio/backend/run.pyindex 86667f8ee39..0f2ed42fec3 100644--- a/studio/backend/run.py+++ b/studio/backend/run.py@@ -125,6 +125,7 @@ backend_dir = Path(__file__).parentif str(backend_dir) not in sys.path:sys.path.insert(0, str(backend_dir))+# First, so these vars land before anything below can size an OpenMP/BLAS pool. Imports stdlib only.from utils.cpu_threads import configure_cpu_threadstry:@@ -133,6 +134,17 @@ except ValueError as exc:configured = os.environ.get("UNSLOTH_CPU_THREADS")raise SystemExit(f"Error: Invalid UNSLOTH_CPU_THREADS value {configured!r}: {exc}") from None+# Windows ROCm ships no distributed backend, so torchao and the CUDA-only xformers both die on import,+# taking diffusers/transformers with them. A stub only seeds a name nothing has imported yet, so both+# must precede the first import below. No-op on other runtimes.+from core._torchao_stub import (+ install_torchao_windows_rocm_stub,+ install_xformers_windows_rocm_stub,+)++install_xformers_windows_rocm_stub()+install_torchao_windows_rocm_stub()+# Anaconda/conda-forge Python: seed platform._sys_version_cache before imports# that trigger attrs -> rich -> structlog -> platform crash.# See: https://github.com/python/cpython/issues/102396diff --git a/studio/backend/tests/test_diffusion_hub_access.py b/studio/backend/tests/test_diffusion_hub_access.pynew file mode 100644index 00000000000..26c774c84d9--- /dev/null+++ b/studio/backend/tests/test_diffusion_hub_access.py@@ -0,0 +1,173 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""A gated model must say how to get in, not paste the 403 back at the user: the load error is+surfaced verbatim in a toast, where a raw GatedRepoError is a request id and a resolve URL+wrapped around one useful sentence.+"""++import sys+from pathlib import Path++import pytest++_BACKEND_ROOT = Path(__file__).resolve().parents[1]+if str(_BACKEND_ROOT) not in sys.path:+ sys.path.insert(0, str(_BACKEND_ROOT))++from core.inference.diffusion import _hf_token_in_play, hub_access_message++_GATED = (+ "403 Client Error. (Request ID: Root=1-6a73b83b) Cannot access gated repo for url "+ "https://huggingface.co/black-forest-labs/FLUX.2-klein-9B/resolve/main/model_index.json. "+ "Access to model black-forest-labs/FLUX.2-klein-9B is restricted and you are not in "+ "the authorized list."+)+++def _gated(text = _GATED):+ """A real GatedRepoError by type, without hub's constructor: HfHubHTTPError.__init__ requires a+ response on hub 1.x but not on 0.x, and the pin spans both. The helper screens on type and+ str() only, so a message-carrying subclass pins the contract on either version."""+ from huggingface_hub.errors import GatedRepoError++ class _Gated(GatedRepoError):+ def __init__(self, message):+ Exception.__init__(self, message)++ return _Gated(text)+++def test_no_token_asks_for_access_and_a_token():+ message = hub_access_message(_gated(), had_token = False)++ assert message is not None+ assert "black-forest-labs/FLUX.2-klein-9B is gated" in message+ assert "https://huggingface.co/black-forest-labs/FLUX.2-klein-9B" in message+ assert "token" in message+ # The resolve URL and request id are the noise this replaces.+ assert "model_index.json" not in message+ assert "Request ID" not in message+++def test_a_token_that_still_bounces_names_the_account():+ message = hub_access_message(_gated(), had_token = True)++ assert message is not None+ assert "not on its access list" in message+ # Telling someone with a token to add a token sends them in a circle.+ assert "add a Hugging Face token" not in message+++def test_a_metadata_api_url_names_the_model_not_the_endpoint():+ """auth_check, and model_info on a gated private repo, raise with /api/models/<owner>/<repo>+ (the shape hub's own GatedRepoError docstring shows); a plain two-segment match on that would+ name "api/models" as the gated repo."""+ message = hub_access_message(+ _gated(+ "403 Client Error. (Request ID: ViT1Bf7O) Cannot access gated repo for url "+ "https://huggingface.co/api/models/ardent-figment/gated-model."+ ),+ had_token = False,+ )++ assert message is not None+ assert "ardent-figment/gated-model is gated" in message+ assert "https://huggingface.co/ardent-figment/gated-model" in message+ assert "api/models" not in message+++def test_a_non_repo_api_url_falls_back_rather_than_inventing_a_repo():+ message = hub_access_message(+ _gated(+ "403 Client Error. Cannot access gated repo for url https://huggingface.co/api/whoami-v2."+ ),+ had_token = False,+ )++ assert message is not None+ assert "its Hugging Face page" in message+ assert "api/" not in message+++def test_an_unparseable_repo_still_gives_the_instruction():+ message = hub_access_message(+ _gated("403 Client Error. Cannot access gated repo."), had_token = False+ )++ assert message is not None+ assert "its Hugging Face page" in message+++ "exc",+ [+ OSError("No space left on device"),+ ValueError("Could not decode image"),+ RuntimeError("CUDA out of memory"),+ ],+)+def test_other_failures_keep_their_own_text(exc):+ # None is the signal to fall back to str(exc); rewriting these would bury the cause.+ assert hub_access_message(exc, had_token = False) is None+++def test_a_wrapped_gated_error_is_still_rewritten():+ """Transformers loads re-raise the 403 inside an OSError, so matching only the outermost exception misses the shape this exists for."""+ try:+ try:+ raise _gated()+ except Exception as inner:+ raise OSError("We couldn't connect to huggingface.co to load this model.") from inner+ except OSError as outer:+ message = hub_access_message(outer, had_token = False)++ assert message is not None+ assert "black-forest-labs/FLUX.2-klein-9B is gated" in message+++def test_a_self_referential_chain_terminates():+ exc = ValueError("boom")+ exc.__context__ = exc++ assert hub_access_message(exc, had_token = False) is None+++def test_an_ambient_token_counts_as_a_token(monkeypatch):+ """With token=None the Hub still uses HF_TOKEN or the cached login, so keying off Studio's+ own token alone tells an already-authenticated user to add a token they have."""+ import huggingface_hub.utils as hub_utils++ monkeypatch.setattr(hub_utils, "get_token_to_send", lambda _t: "hf_ambient")+ assert _hf_token_in_play(None) is True++ monkeypatch.setattr(hub_utils, "get_token_to_send", lambda _t: None)+ assert _hf_token_in_play(None) is False+ assert _hf_token_in_play("hf_explicit") is True+++def test_a_disabled_implicit_token_is_not_a_token(monkeypatch):+ """HF_HUB_DISABLE_IMPLICIT_TOKEN leaves get_token() answering with the cached login while+ build_hf_headers sends no authorization header, so the refusal was anonymous."""+ from huggingface_hub import constants+ from huggingface_hub.utils import _headers++ monkeypatch.setattr(constants, "HF_HUB_DISABLE_IMPLICIT_TOKEN", True)+ monkeypatch.setattr(_headers, "get_token", lambda: "hf_cached_login", raising = False)++ # Real get_token_to_send, so this pins hub's actual policy rather than a stand-in.+ assert _hf_token_in_play(None) is False+ assert _hf_token_in_play("hf_explicit") is True++ monkeypatch.setattr(constants, "HF_HUB_DISABLE_IMPLICIT_TOKEN", False)+ assert _hf_token_in_play(None) is True+++def test_an_unreadable_ambient_token_is_not_a_token(monkeypatch):+ import huggingface_hub.utils as hub_utils++ def _raise(_t):+ raise OSError("token file unreadable")++ monkeypatch.setattr(hub_utils, "get_token_to_send", _raise)+ assert _hf_token_in_play(None) is Falsediff --git a/studio/backend/tests/test_xformers_stub_diffusion_parity.py b/studio/backend/tests/test_xformers_stub_diffusion_parity.pynew file mode 100644index 00000000000..efab7fd2295--- /dev/null+++ b/studio/backend/tests/test_xformers_stub_diffusion_parity.py@@ -0,0 +1,334 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Invariant: the diffusion paths must stub xformers and torchao before importing diffusers.++The Windows xformers pin is CUDA-only, so against a ROCm torch (no distributed backend) ``import+xformers.ops`` dies inside torch.distributed, and diffusers imports xformers on sight, so such a+host cannot load any image or video model and the error names neither xformers nor the cause.+diffusers reaches torchao the same way, through its quantizers.++Every ``import diffusers`` there is lazy, so a module-scope install is what puts the stubs in+first; asserting module scope stops a later edit tucking one inside a skippable function. Those+modules are not enough alone: a stub only seeds names nothing has imported yet, and the server has+already pulled torchao in via the route tree, so run.py installs both before its first import.++CPU-only: source is parsed with ``ast``, and the behaviour tests fake the platform probe.+"""++from __future__ import annotations++import ast+import sys+import types+from pathlib import Path++import pytest++from core import _torchao_stub+from core._torchao_stub import (+ install_torchao_windows_rocm_stub,+ install_xformers_windows_rocm_stub,+)++_BACKEND = Path(__file__).resolve().parent.parent # studio/backend+_CORE = _BACKEND / "core"+# Renaming either installer breaks the import above, loudly, rather than these assertions.+_INSTALLS = frozenset(+ {install_xformers_windows_rocm_stub.__name__, install_torchao_windows_rocm_stub.__name__}+)++# Where diffusers gets imported: the loader, and the trainers' shared module (a spawned child, so the loader's install does not carry over).+_DIFFUSION_MODULES = [+ _CORE / "inference" / "diffusion.py",+ _CORE / "training" / "diffusion_train_common.py",+]++_ENTRY_POINT = _BACKEND / "run.py"+_STUB_MODULE = "core._torchao_stub"+_ML_ROOTS = frozenset({"diffusers", "peft", "torch", "torchao", "transformers", "xformers"})+# Must run BEFORE the installers: these set the env vars torch reads when it sizes its OpenMP/BLAS pools. Imports stdlib only.+_PRE_STUB = frozenset({"utils.cpu_threads"})+++def _import_roots(node) -> set[str]:+ """Top-level package names a module-scope import statement pulls in."""+ if isinstance(node, ast.Import):+ return {alias.name.split(".")[0] for alias in node.names}+ if isinstance(node, ast.ImportFrom) and node.module and node.module != _STUB_MODULE:+ if node.module in _PRE_STUB:+ return set()+ return {node.module.split(".")[0]}+ return set()+++def _reaches_torch(root: str) -> bool:+ # Anything in the backend tree can, transitively; probing the tree keeps this honest as modules come and go. stdlib falls through.+ return root in _ML_ROOTS or (_BACKEND / root).is_dir() or (_BACKEND / f"{root}.py").is_file()+++def _module_level_installs(tree) -> set[str]:+ """Names of the stub installers called as bare module-scope statements."""+ found = set()+ for node in tree.body:+ if not isinstance(node, ast.Expr) or not isinstance(node.value, ast.Call):+ continue+ func = node.value.func+ if isinstance(func, ast.Name) and func.id in _INSTALLS:+ found.add(func.id)+ return found++[email protected]("path", _DIFFUSION_MODULES, ids = lambda p: p.name)+def test_diffusion_modules_install_both_stubs_at_module_scope(path):+ tree = ast.parse(path.read_text(encoding = "utf-8"))++ assert _module_level_installs(tree) == _INSTALLS, (+ f"{path.relative_to(_BACKEND)} must call both stub installers at module scope, before the "+ "lazy `import diffusers` calls below them."+ )++[email protected]("path", _DIFFUSION_MODULES, ids = lambda p: p.name)+def test_diffusion_modules_install_before_any_torch_reaching_import(path):+ """Module scope alone is not the invariant: a sibling imported above the installs can pull+ torchao in first, and a stub only seeds names nothing has imported yet."""+ installed: set[str] = set()+ for node in ast.parse(path.read_text(encoding = "utf-8")).body:+ if isinstance(node, ast.Expr) and isinstance(node.value, ast.Call):+ func = node.value.func+ if isinstance(func, ast.Name) and func.id in _INSTALLS:+ installed.add(func.id)+ continue+ for root in _import_roots(node):+ if root in _ML_ROOTS:+ assert installed == _INSTALLS, (+ f"{path.relative_to(_BACKEND)}:{node.lineno} imports {root} before installing "+ f"{sorted(_INSTALLS - installed)}."+ )+++def test_the_entry_point_installs_both_stubs_before_its_first_heavy_import():+ installed: set[str] = set()+ for node in ast.parse(_ENTRY_POINT.read_text(encoding = "utf-8")).body:+ if isinstance(node, ast.Expr) and isinstance(node.value, ast.Call):+ func = node.value.func+ if isinstance(func, ast.Name) and func.id in _INSTALLS:+ installed.add(func.id)+ continue+ for root in _import_roots(node):+ if _reaches_torch(root):+ assert installed == _INSTALLS, (+ f"run.py:{node.lineno} imports {root} before installing "+ f"{sorted(_INSTALLS - installed)}; a stub set after the first import that "+ "reaches torchao or xformers is a no-op."+ )++ assert installed == _INSTALLS, "run.py must call both stub installers at module scope"+++def _is_stub_key(name: str) -> bool:+ # Both packages: a torchao stub left behind turns a later importorskip("torchao.quantization") into a silent no-op.+ return any(name == p or name.startswith(p + ".") for p in ("xformers", "torchao"))+++def on_windows_rocm(monkeypatch):+ """Force the Windows-ROCm probe on, and leave sys.modules / sys.meta_path as found."""+ monkeypatch.setattr(_torchao_stub, "_is_windows_rocm", lambda: True)+ monkeypatch.setattr(sys, "meta_path", list(sys.meta_path))+ saved = {k: v for k, v in sys.modules.items() if _is_stub_key(k)}+ for name in saved:+ del sys.modules[name]+ yield+ for name in [k for k in sys.modules if _is_stub_key(k)]:+ del sys.modules[name]+ sys.modules.update(saved)+++def test_xformers_is_stubbed_on_windows_rocm(on_windows_rocm):+ install_xformers_windows_rocm_stub()++ # The names diffusers imports, plus a deeper one nothing seeded: the finder covers it.+ import xformers # noqa: F401+ import xformers.ops # noqa: F401+ import xformers.ops.fmha # noqa: F401++ for name in ("xformers", "xformers.ops", "xformers.ops.fmha"):+ assert sys.modules[name]._unsloth_stub is _torchao_stub._STUB_SENTINEL, name+++def test_a_real_xformers_is_left_alone(on_windows_rocm, monkeypatch):+ import types++ real = types.ModuleType("xformers")+ monkeypatch.setitem(sys.modules, "xformers", real)++ install_xformers_windows_rocm_stub()++ assert sys.modules["xformers"] is real+++def test_no_stub_off_windows_rocm(monkeypatch):+ # A CUDA or Linux host has a working xformers; shadowing it would cost real attention kernels.+ monkeypatch.setattr(_torchao_stub, "_is_windows_rocm", lambda: False)+ monkeypatch.delitem(sys.modules, "xformers", raising = False)++ install_xformers_windows_rocm_stub()++ assert "xformers" not in sys.modules+++def test_the_finder_is_registered_once(on_windows_rocm):+ install_xformers_windows_rocm_stub()+ install_torchao_windows_rocm_stub()+ install_xformers_windows_rocm_stub()++ finders = [f for f in sys.meta_path if isinstance(f, _torchao_stub._StubSubpackageFinder)]+ assert len(finders) == 1+++def test_no_stub_survives_this_module():+ """The fixture must hand sys.modules back clean: a leaked torchao stub is silently accepted by a later importorskip."""+ for name in ("xformers", "torchao", "torchao.quantization"):+ assert not _torchao_stub.is_stubbed(name), name+++def _target(dtype = None):+ """A device target. Both guards reject a stub BEFORE looking at the dtype, so the decline tests need no torch."""+ return type("T", (), {"device": "cuda", "dtype": dtype})()+++def _bf16_target():+ torch = pytest.importorskip("torch")+ return _target(torch.bfloat16)+++def test_dense_quant_declines_a_stubbed_torchao(on_windows_rocm):+ """The stub's quantize_ is a no-op, so the smoke probe passes on a still-dense Linear and the transformer gets MARKED quantised."""+ from core.inference.diffusion_transformer_quant import dense_transformer_supported++ install_torchao_windows_rocm_stub()+ assert dense_transformer_supported(_target()) is False+++def test_dense_quant_still_allowed_without_the_stub(on_windows_rocm):+ """The positive control: the guard must reject the stub, not the whole path."""+ from core.inference.diffusion_transformer_quant import dense_transformer_supported++ # The fixture cleared torchao out of sys.modules, so nothing is stubbed here.+ assert dense_transformer_supported(_bf16_target()) is True++[email protected]("mode", ["int8", "fp8_dynamic", "nvfp4"])+def test_te_quant_declines_a_stubbed_torchao(on_windows_rocm, mode):+ """Same no-op, same false report, on the text encoders. ROCm answers device "cuda" and a capability pair, so nothing else catches it."""+ from core.inference.diffusion_precision import te_quant_supported++ install_torchao_windows_rocm_stub()+ assert te_quant_supported(_target(), mode) is False+++def test_layerwise_fp8_te_still_works_under_the_stub(on_windows_rocm):+ """Plain fp8 is a torch cast with no torchao in it, so the guard must not take it away."""+ from core.inference.diffusion_precision import te_quant_supported++ target = _bf16_target()+ install_torchao_windows_rocm_stub()+ import torch++ assert te_quant_supported(target, "fp8") is hasattr(torch, "float8_e4m3fn")++[email protected]("mode", ["fp8", "mxfp8"])+def test_dit_training_refuses_dense_precision_under_the_stub(on_windows_rocm, mode):+ """_apply_fp8_training / _apply_mxfp8_training call the stub, get None and return True, so the run would report fp8 while training bf16."""+ pytest.importorskip("torch")+ from core.training.diffusion_dit_trainer import _resolve_base_precision++ install_torchao_windows_rocm_stub()+ cfg = type("C", (), {"base_precision": mode, "mixed_precision": "bf16"})()+ with pytest.raises(ValueError, match = "Windows-ROCm stub"):+ _resolve_base_precision(cfg, None, "cuda")++[email protected]("mode", ["fp8", "mxfp8"])+def test_the_preflight_refuses_the_stub_too(on_windows_rocm, mode):+ """The child's guard fires after _free_gpu_for_diffusion_training() has already unloaded residents, so the preflight must reject it first."""+ pytest.importorskip("torch")+ from core.training.diffusion_dit_trainer import _resolve_base_precision+ from core.training.diffusion_train_common import training_precision_preflight_error++ install_torchao_windows_rocm_stub()+ cfg = type("C", (), {"base_precision": mode, "mixed_precision": "bf16"})()+ with pytest.raises(ValueError, match = "Windows-ROCm stub"):+ _resolve_base_precision(cfg, None, "cuda")++ # A real DiT family name, or the gate block is skipped and the test proves nothing.+ reason = training_precision_preflight_error("flux.1", mode)+ assert reason and "Windows-ROCm stub" in reason, (+ f"the child refuses {mode} under the stub but the preflight does not, so a start would "+ "evict resident GPU models and only then fail"+ )+++ "dist_version, hip_line, expected",+ [+ # AMD's own Windows build (repo.radeon.com/rocm/windows) carries no "rocm" tag, so only hip answers.+ ("2.8.0a0+gitfc14c65", "hip: Optional[str] = '6.4.50101-9a6572ae7'", True),+ # download.pytorch.org and TheRock DO tag theirs; the fast path must still work.+ ("2.9.1+rocm7.2.1", "hip: Optional[str] = '7.2.1'", True),+ ("2.9.0+rocmsdk20251116", "hip: Optional[str] = None", True),+ ("2.9.1+cu128", "hip: Optional[str] = None", False),+ ("2.9.1", "hip: Optional[str] = None", False),+ ],+)+def test_rocm_is_detected_off_disk_without_importing_torch(+ monkeypatch, tmp_path, dist_version, hip_line, expected+):+ """A rocm tag is sufficient but not necessary, so the version alone cannot decide. The fake torch raises on import, proving none happens."""+ pkg = tmp_path / "torch"+ pkg.mkdir()+ (pkg / "__init__.py").write_text(+ 'raise ImportError("DLL load failed while importing _C: amdhip64.dll not found")\n'+ )+ (pkg / "version.py").write_text(f"from typing import Optional\n{hip_line}\n")++ monkeypatch.setattr(+ _torchao_stub.importlib.util,+ "find_spec",+ lambda name: types.SimpleNamespace(origin = str(pkg / "__init__.py")),+ )+ monkeypatch.delitem(sys.modules, "torch", raising = False)+ monkeypatch.setattr(+ "importlib.metadata.version",+ lambda name: dist_version if name == "torch" else "0",+ )+ monkeypatch.setattr(sys, "platform", "win32")++ assert _torchao_stub._is_windows_rocm() is expected+ assert "torch" not in sys.modules+++# The two ways a ROCm wheel identifies itself: hip set (pytorch.org), or version tag only (AMD SDK / Radeon, per worker.py::_torch_has_hip).+_ROCM_WHEELS = [("7.2.1", "2.9.1+rocm7.2.1"), (None, "2.10.0a0+rocm7.10.0a20251116")]++[email protected]("hip,version", _ROCM_WHEELS)+def test_xformers_is_never_selected_on_a_rocm_target(monkeypatch, hip, version):+ """The one check standing between an API-supplied attention_backend="xformers" and a stub that+ returns None mid-denoise. diffusers' own probe is metadata-based, so it believes the stub is+ usable and will not refuse the backend itself."""+ torch = pytest.importorskip("torch")++ from core.inference.diffusion_attention import select_attention_backend++ monkeypatch.setattr(torch.version, "hip", hip, raising = False)+ monkeypatch.setattr(torch, "__version__", version)+ rocm = _target()+ for speed in (True, False):+ assert select_attention_backend(rocm, "xformers", speed_active = speed) is None+ assert select_attention_backend(rocm, "auto", speed_active = speed) != "_native_cudnn"+ # aiter is the AMD kernel: misreading the wheel as NVIDIA drops the one that works here.+ assert select_attention_backend(rocm, "aiter", speed_active = True) == "aiter"