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.

Fix diffusion load cancellation during construction (#10780)

Michael Han93b3dedd11a3
diff --git a/studio/backend/core/inference/diffusion.py b/studio/backend/core/inference/diffusion.py
index e398a4dcf2b..630ec0d0f4c 100644
--- a/studio/backend/core/inference/diffusion.py
+++ b/studio/backend/core/inference/diffusion.py
@@ -26,6 +26,7 @@ import re
import sys
import threading
import time
+import traceback
from dataclasses import dataclass, replace
from pathlib import Path
from typing import Any, Callable, Optional, Sequence
@@ -919,6 +920,34 @@ class _LoadingState:
# Where the companion BYTES land: ``base_repo``, or its mirror when one was swapped in. Never surfaced
# (``base_repo`` stays the id status() reports), but the cache scan and the delete guard must look here.
fetch_repo: Optional[str] = None
+ account_id: Optional[str] = None
+
+
+def _account_owned_load(method):
+ @functools.wraps(method)
+ def wrapped(self, *args, **kwargs):
+ request = object()
+ inherited = kwargs.get("_load_token")
+ while True:
+ if inherited is None:
+ # Wait the in-flight ejects out and take the epoch they leave; a worker inherits one.
+ self._wait_for_pending_unloads()
+ with self._load_cancel_lock:
+ token = self._load_token if inherited is None else inherited
+ # Read under the lock that registers: an eject arriving in the gap above bumps the
+ # epoch too, so re-reading it would admit this load into the teardown it walked into.
+ if inherited is None and self._unload_waiters:
+ continue
+ self._raise_if_load_cancelled(token)
+ self._load_accounts[request] = (token, current_account_id())
+ break
+ try:
+ return method(self, *args, **{**kwargs, "_load_token": token})
+ finally:
+ with self._load_cancel_lock:
+ self._load_accounts.pop(request, None)
+
+ return wrapped
@dataclass
@@ -1194,20 +1223,37 @@ def _memory_request_forces_offload(memory_mode: Optional[str], cpu_offload: bool
return mode is None and bool(cpu_offload)
+def _clear_exception_frames(exc: BaseException) -> None:
+ """Release failed-call locals while preserving traceback locations."""
+ errors, seen = [exc], set()
+ while errors:
+ error = errors.pop()
+ if id(error) in seen:
+ continue
+ seen.add(id(error))
+ traceback.clear_frames(error.__traceback__)
+ errors.extend(cause for cause in (error.__cause__, error.__context__) if cause is not None)
+
+
class DiffusionBackend:
"""Holds at most one loaded diffusers pipeline. All mutations are serialised."""
def __init__(self) -> None:
- # _lock serialises the small state mutations; the status/progress readers stay lock-free.
+ # _lock serialises pipeline mutations; the status/progress readers stay lock-free.
self._lock = threading.Lock()
+ # Protect load metadata without waiting for construction.
+ # Never acquire pipeline locks while holding this lock.
+ self._load_cancel_lock = threading.Lock()
+ self._unload_waiters = 0
# _generate_lock serialises generations and is the ONLY lock the denoise holds.
self._generate_lock = threading.Lock()
self._state: Optional[_LoadState] = None
self._loading: Optional[_LoadingState] = None
# Bumped on begin_load/unload so a superseded worker neither commits nor stamps progress
self._load_token = 0
- # Set by unload() to abort an in-flight download. Replaced, never cleared, so a cancelled worker stays
- # cancelled.
+ # Includes preflight and direct loads that have no background marker.
+ self._load_accounts: dict[object, tuple[int, str]] = {}
+ # Replaced per load so cancelled workers stay cancelled.
self._cancel_event = threading.Event()
# Keep Stop responsive while a replacement holds _lock.
self._generation_cancel_lock = threading.Lock()
@@ -1225,6 +1271,12 @@ class DiffusionBackend:
# Set when no teardown is reserved; an Event keeps waiting independent of _lock.
self._teardown_drained = threading.Event()
self._teardown_drained.set()
+ # Repos a cancelled load is still reading, per epoch; see draining_repo_ids().
+ self._draining_repos: dict[int, set[str]] = {}
+ # Set when no eject holds the load fence. Its own event: _teardown_drained stays SET from the
+ # eject being accepted until construction releases _lock, so waiting on that spun a core.
+ self._unload_fence_clear = threading.Event()
+ self._unload_fence_clear.set()
# Written by the callback, read lock-free by generate_progress().
self._gen: Optional[_GenState] = None
# img2img/inpaint pipes built via from_pipe (shared modules, no extra VRAM); cleared on unload
@@ -1247,6 +1299,36 @@ class DiffusionBackend:
# The INDEXED string, so _resolve_device_target can rebuild a selection an override would erase.
return target.torch_device, target.dtype
+ def _raise_if_load_cancelled(self, token: int) -> None:
+ # The epoch alone: unload() bumps _load_token before any teardown, so a load that started
+ # after the eject carries the current token and was never cancelled.
+ # Refusing on a bare _unload_waiters count 409'd an ordinary model switch for the length of
+ # the denoise; such a request waits in _wait_for_pending_unloads instead.
+ if token != self._load_token:
+ raise RuntimeError("Diffusion load was cancelled.")
+
+ def _wait_for_pending_unloads(self, timeout: float = 900.0) -> None:
+ """Queue a FRESH load behind every eject that is already tearing down.
+
+ Replacement loads stay fenced until each pending eject finishes, including a failed teardown:
+ the eject frees the very pipeline this load is about to replace. Waiting is the whole point --
+ raising here would report a cancellation that never happened. Only requests entering with no
+ epoch of their own wait; a worker that already holds one is governed by the epoch instead, so
+ a cancelled load never sits here waiting for the eject that cancelled it.
+
+ Nothing is held while waiting (this is called before ``_lock``), so it cannot deadlock against
+ an eject that is itself waiting for ``_lock`` or for the active denoise.
+ """
+ deadline = time.monotonic() + timeout
+ while True:
+ with self._load_cancel_lock:
+ if not self._unload_waiters:
+ return
+ if time.monotonic() >= deadline:
+ raise RuntimeError("Timed out waiting for a diffusion unload to finish.")
+ # A sleep with an early wake, not the condition itself: the counter above decides.
+ self._unload_fence_clear.wait(timeout = 0.1)
+
def _reserve_teardown_locked(self) -> None:
"""Fence queued generations off the pipeline this teardown is about to free. Call only while
holding ``_lock``, so the count and the gate move together."""
@@ -1306,7 +1388,7 @@ class DiffusionBackend:
if not self._teardown_waiters:
with self._generation_cancel_lock:
cancelled = cancel.is_set()
- if not cancelled:
+ if not cancelled and not self._unload_waiters:
self._queued_generate_cancels.discard(cancel)
self._active_generate_cancel = cancel
self._active_generate_account = current_account_id()
@@ -1322,7 +1404,12 @@ class DiffusionBackend:
while True:
if cancel.is_set():
raise RuntimeError(DIFFUSION_CANCELLED_MSG)
- if self._teardown_drained.wait(timeout = 0.1):
+ # Whichever fence turned it away: _teardown_drained is still SET before the
+ # teardown is reserved, so waiting on that spun against the eject's own _lock.
+ with self._load_cancel_lock:
+ fenced_by_unload = bool(self._unload_waiters)
+ gate = self._unload_fence_clear if fenced_by_unload else self._teardown_drained
+ if gate.wait(timeout = 0.1):
break
from hub.services.models.account_access import media_generation_slot
try:
@@ -1971,6 +2058,7 @@ class DiffusionBackend:
# the Hub.
assert_pick_is_not_speech(repo_id, gguf_filename, hf_token, allow_network)
+ @_account_owned_load
def begin_load(
self,
repo_id: str,
@@ -1995,8 +2083,12 @@ class DiffusionBackend:
gpu_ids: Optional[list[int]] = None,
# The ordinal the ROUTE already ranked, so the preflight and the load agree on one card.
gpu_ordinal: Optional[int] = None,
+ _load_token: Optional[int] = None,
) -> dict[str, Any]:
"""Validate, then run the (slow) load on a daemon thread. Returns at once."""
+ with self._load_cancel_lock:
+ entry_token = _load_token
+ self._raise_if_load_cancelled(entry_token)
hf_token = (hf_token.strip() if isinstance(hf_token, str) else hf_token) or None
# Resolved ONCE, here, and carried to the worker: outside it so a bad pick is the route's 400 rather than a
# load that dies mid-download, and only once so free VRAM cannot re-rank the choice after the weights land.
@@ -2027,7 +2119,8 @@ class DiffusionBackend:
gpu_ordinal = gpu_ordinal,
)
- with self._lock:
+ with self._lock, self._load_cancel_lock:
+ self._raise_if_load_cancelled(entry_token)
# Allow starting over a previously-failed load, but not over a live one.
if self._loading is not None and self._loading.error is None:
raise RuntimeError("A diffusion load is already in progress.")
@@ -2039,7 +2132,9 @@ class DiffusionBackend:
cancel_event = threading.Event()
self._cancel_event = cancel_event
# Seed with the family fallback; the worker resolves the real base and updates this.
- self._loading = _LoadingState(repo_id = repo_id, base_repo = fam.base_repo)
+ self._loading = _LoadingState(
+ repo_id = repo_id, base_repo = fam.base_repo, account_id = current_account_id()
+ )
account_thread(
target = self._run_load,
@@ -2183,7 +2278,7 @@ class DiffusionBackend:
shortfall,
)
raise RuntimeError(shortfall)
- with self._lock:
+ with self._load_cancel_lock:
if self._load_token == token and self._loading is not None:
self._loading.base_repo = base
self._loading.fetch_repo = fetch_base
@@ -2206,7 +2301,7 @@ class DiffusionBackend:
or base_snapshot
)
self.load_pipeline(**kwargs)
- with self._lock:
+ with self._load_cancel_lock:
# Only clear the marker if this load is still current (a superseder has its own token).
if self._load_token == token:
self._loading = None
@@ -2241,9 +2336,13 @@ class DiffusionBackend:
)
except Exception: # noqa: BLE001
text = str(exc)
- with self._lock:
+ with self._load_cancel_lock:
if self._load_token == token and self._loading is not None:
self._loading.error = redact_native_paths(text)
+ finally:
+ # Nothing else knows when the prefetch returned, so this is the drain's only owner.
+ with self._load_cancel_lock:
+ self._draining_repos.pop(token, None)
def load_progress(self) -> dict[str, Any]:
"""Phase + downloaded/total bytes for the in-flight load (cache-scan based)."""
@@ -2280,13 +2379,28 @@ class DiffusionBackend:
target repo (or its companion base) would yank blobs and snapshot files from under the
download/assembly. Includes the mirror when one was swapped in: that is where the
companion bytes land."""
- with self._lock:
+ # _load_cancel_lock alone: _loading lives under it, and this predicate runs inside the GPU
+ # arbiter's lock (release_if), so taking _lock here let a multi-minute build stall every
+ # other modality's acquire.
+ with self._load_cancel_lock:
loading = self._loading
if loading is None or loading.error is not None:
return ()
ids = (loading.repo_id, loading.base_repo, loading.fetch_repo)
return tuple(dict.fromkeys(r for r in ids if r))
+ def draining_repo_ids(self) -> tuple[str, ...]:
+ """Repo ids a cancelled load is still reading, for the delete-cached guard only.
+
+ The eject drops ``_loading`` at once so the load cancels promptly, but its thread reads on
+ until it unwinds, holding no lock at all inside ``_prefetch_files``.
+
+ NOT part of ``loading_repo_ids()``: that answers "is a load in flight", which the arbiter's
+ ``release_if``, keep-warm and the media auto-switch read as ownership.
+ """
+ with self._load_cancel_lock:
+ return tuple(dict.fromkeys(r for repos in self._draining_repos.values() for r in repos))
+
@staticmethod
def _te_prequant_plan_files(
fam: Any,
@@ -3370,6 +3484,7 @@ class DiffusionBackend:
return DiffusionBackend._union_over_cached_revs(base, _params, staged_dir) * 2
+ @_account_owned_load
def load_pipeline(
self,
repo_id: str,
@@ -3401,6 +3516,10 @@ class DiffusionBackend:
# prefetch phase.
_fetch_base: Optional[str] = None,
) -> dict[str, Any]:
+ with self._load_cancel_lock:
+ if _load_token is None:
+ _load_token = self._load_token
+ self._raise_if_load_cancelled(_load_token)
# A blank token must degrade to anonymous, not be passed as a credential. Normalize once.
hf_token = hf_token.strip() if isinstance(hf_token, str) else hf_token
hf_token = hf_token or None
@@ -3468,8 +3587,7 @@ class DiffusionBackend:
pass
with self._lock:
- if _load_token is not None and _load_token != self._load_token:
- raise RuntimeError("Diffusion load was cancelled.")
+ self._raise_if_load_cancelled(_load_token)
with self._generation_cancel_lock:
if self._active_generate_cancel is not None:
self._active_generate_cancel.set()
@@ -3477,8 +3595,7 @@ class DiffusionBackend:
with self._model_transition_slot():
with self._lock:
try:
- if _load_token is not None and _load_token != self._load_token:
- raise RuntimeError("Diffusion load was cancelled.")
+ self._raise_if_load_cancelled(_load_token)
self._unload_locked()
finally:
@@ -3550,7 +3667,8 @@ class DiffusionBackend:
else normalize_transformer_quant(transformer_quant_requested)
)
- pipe = None
+ pipe = transformer = None
+ pipe_kwargs: dict[str, Any] = {}
transformer_quant_engaged = None
quant_plan = None
# Why the dense quant did not engage, in the caller's terms. Threaded into `resolved` so a fallback is
@@ -4061,346 +4179,370 @@ class DiffusionBackend:
else "no hosted pre-quantised checkpoint is available and the "
"dense bf16 transformer cannot be built on this host"
)
- if (
- kind == "gguf"
- and normalize_transformer_quant(transformer_quant) is not None
- and dense_transformer_supported(target)
- and not dense_declined
- and (plan.offload_policy == OFFLOAD_NONE or quant_plan is not None)
- ):
- try:
- pipe, transformer_quant_engaged = self._load_dense_quant_pipeline(
- transformer_cls,
- pipeline_cls,
- base,
- device,
- dtype,
- hf_token,
- target,
- transformer_quant,
- transformer_quant_fast_accum,
- fam = fam,
- base_local_dir = _base_local_dir,
- prequant_path = transformer_prequant_path,
- allow_dense_fallback = dense_fallback_allowed,
- lora_specs = loras,
- text_encoder_quant = text_encoder_quant,
- fetch_base = fetch_base,
- local_files_only = local_files_only,
- )
- except Exception as exc: # noqa: BLE001 - fall back to the GGUF build
- logger.warning(
- "diffusion.transformer_quant_fallback: %s (loading GGUF)", exc
- )
- pipe = None
- transformer_quant_engaged = None
- # Formatted BEFORE the del below, and redacted: this reaches the client both as a status
- # tooltip and (for an explicit ask) as the refusal message.
- from utils.native_path_leases import redact_native_paths
-
- transformer_quant_decline = redact_native_paths(
- f"the quantised transformer build failed ({exc})"
- )
- # Drop the exception before clearing the cache: its traceback pins the dense transformer's
- # VRAM.
- del exc
+ backend_flags_before = None
+ eager_patched = False
+ compile_ctx = None
+ state_committed = False
+ state = None
+ try:
+ self._raise_if_load_cancelled(_load_token)
+ if (
+ kind == "gguf"
+ and normalize_transformer_quant(transformer_quant) is not None
+ and dense_transformer_supported(target)
+ and not dense_declined
+ and (plan.offload_policy == OFFLOAD_NONE or quant_plan is not None)
+ ):
try:
- clear_gpu_cache()
- except Exception: # noqa: BLE001
- pass
- if transformer_quant_engaged is not None and quant_plan is not None:
- # The engaged dense build uses the re-planned placement; the GGUF-size plan stays for fallback.
- plan = quant_plan
+ pipe, transformer_quant_engaged = self._load_dense_quant_pipeline(
+ transformer_cls,
+ pipeline_cls,
+ base,
+ device,
+ dtype,
+ hf_token,
+ target,
+ transformer_quant,
+ transformer_quant_fast_accum,
+ fam = fam,
+ base_local_dir = _base_local_dir,
+ prequant_path = transformer_prequant_path,
+ allow_dense_fallback = dense_fallback_allowed,
+ lora_specs = loras,
+ text_encoder_quant = text_encoder_quant,
+ fetch_base = fetch_base,
+ local_files_only = local_files_only,
+ _load_token = _load_token,
+ )
+ except Exception as exc: # noqa: BLE001 - fall back to the GGUF build
+ self._raise_if_load_cancelled(_load_token)
+ logger.warning(
+ "diffusion.transformer_quant_fallback: %s (loading GGUF)", exc
+ )
+ pipe = None
+ transformer_quant_engaged = None
+ # Formatted before cleanup and redacted: this reaches the client both as a status
+ # tooltip and (for an explicit ask) as the refusal message.
+ from utils.native_path_leases import redact_native_paths
+
+ transformer_quant_decline = redact_native_paths(
+ f"the quantised transformer build failed ({exc})"
+ )
+ _clear_exception_frames(exc)
+ try:
+ clear_gpu_cache()
+ except Exception: # noqa: BLE001
+ pass
+ if transformer_quant_engaged is not None and quant_plan is not None:
+ # The engaged dense build uses the re-planned placement; the GGUF-size plan stays for fallback.
+ plan = quant_plan
- if (
- pipe is None
- and kind == "gguf"
- and normalize_transformer_quant(transformer_quant) is not None
- and _has_active_lora(loras)
- ):
- # Adapters were requested BAKED but that build failed, and the GGUF fallback cannot carry them;
- # fail loudly.
- raise RuntimeError(
- "The requested LoRA adapters could not be applied: baking adapters "
- "requires the quantized (int8/fp8) transformer build, which was "
- "declined or failed on this device (see the server log), and the "
- "GGUF fallback cannot carry them. Retry without transformer_quant "
- "adapters, free VRAM, or pick a smaller model."
- )
+ if (
+ pipe is None
+ and kind == "gguf"
+ and normalize_transformer_quant(transformer_quant) is not None
+ and _has_active_lora(loras)
+ ):
+ # Adapters were requested BAKED but that build failed, and the GGUF fallback cannot carry them;
+ # fail loudly.
+ raise RuntimeError(
+ "The requested LoRA adapters could not be applied: baking adapters "
+ "requires the quantized (int8/fp8) transformer build, which was "
+ "declined or failed on this device (see the server log), and the "
+ "GGUF fallback cannot carry them. Retry without transformer_quant "
+ "adapters, free VRAM, or pick a smaller model."
+ )
- # Fail closed on a declined EXPLICIT precision. Loading the GGUF here produced a perfectly good image
- # at a precision the caller never asked for, and nothing in the response said so, which is why a
- # successful render could not be taken as proof the requested precision ran. `auto` is untouched:
- # falling down the ladder is what it asks for.
- if (
- pipe is None
- and transformer_quant_pinned is not None
- and not precision_fallback_allowed()
- ):
- raise RuntimeError(
- precision_refusal_message(
- "transformer_quant",
- transformer_quant_pinned,
- transformer_quant_decline
- or "the quantised transformer build did not engage on this host",
- off_label = "Off to run the checkpoint as-is",
+ # Fail closed on a declined EXPLICIT precision. Loading the GGUF here produced a perfectly good image
+ # at a precision the caller never asked for, and nothing in the response said so, which is why a
+ # successful render could not be taken as proof the requested precision ran. `auto` is untouched:
+ # falling down the ladder is what it asks for.
+ if (
+ pipe is None
+ and transformer_quant_pinned is not None
+ and not precision_fallback_allowed()
+ ):
+ raise RuntimeError(
+ precision_refusal_message(
+ "transformer_quant",
+ transformer_quant_pinned,
+ transformer_quant_decline
+ or "the quantised transformer build did not engage on this host",
+ off_label = "Off to run the checkpoint as-is",
+ )
)
- )
- if pipe is None:
- if kind == "pipeline":
- if fam.name == KREA2_FAMILY_NAME:
- # krea ships transformers-5.x configs the 4.x line cannot parse, so assemble
- # per-component; that path never sees pipe_kwargs, so pass the pre-cast TE. Fetches EVERY
- # component from the id given, so it must get the mirror.
- pipe = load_krea2_pipeline(
- fetch_base,
- dtype,
- hf_token = hf_token,
- # The branch never sees pipe_kwargs, so the one keyword that keeps the no-download
- # promise has to be handed over with the rest
- local_files_only = local_files_only,
- text_encoder = te_prequant_pipe_kwargs(
- fam,
+ if pipe is None:
+ if kind == "pipeline":
+ if fam.name == KREA2_FAMILY_NAME:
+ # krea ships transformers-5.x configs the 4.x line cannot parse, so assemble
+ # per-component; that path never sees pipe_kwargs, so pass the pre-cast TE. Fetches EVERY
+ # component from the id given, so it must get the mirror.
+ pipe = load_krea2_pipeline(
fetch_base,
- te_quant_mode = text_encoder_quant,
- target = target,
- dtype = dtype,
+ dtype,
hf_token = hf_token,
- logger = logger,
+ check_cancelled = lambda: self._raise_if_load_cancelled(
+ _load_token
+ ),
+ # The branch never sees pipe_kwargs, so the one keyword that keeps the no-download
+ # promise has to be handed over with the rest
local_files_only = local_files_only,
- ).get("text_encoder"),
- )
- elif fam.name == IDEOGRAM4_FAMILY_NAME:
- # ideogram ships the same transformers-5.x Qwen stack as krea; assemble per-component too,
- # from the mirror for the same reason.
- pipe = load_ideogram4_pipeline(fetch_base, dtype, hf_token = hf_token)
- else:
- pipe_kwargs: dict[str, Any] = {
- "local_files_only": local_files_only,
- "torch_dtype": dtype,
- "cache_dir": hub_cache_dir(),
- }
- if hf_token:
- pipe_kwargs["token"] = hf_token
- if fam.name == HIDREAM_FAMILY_NAME:
- # The repo names a Llama text_encoder_4 it does not ship; supply it from the open
- # mirror
- pipe_kwargs.update(
- hidream_te4_kwargs(
- dtype,
- hf_token,
- fam = fam,
+ text_encoder = te_prequant_pipe_kwargs(
+ fam,
+ fetch_base,
te_quant_mode = text_encoder_quant,
target = target,
+ dtype = dtype,
+ hf_token = hf_token,
+ logger = logger,
local_files_only = local_files_only,
- )
+ ).get("text_encoder"),
)
- # A hosted pre-cast fp8 text encoder skips the dense TE download; the cast re-applies
- # idempotently.
- pipe_kwargs.update(
- te_prequant_pipe_kwargs(
- fam,
+ elif fam.name == IDEOGRAM4_FAMILY_NAME:
+ # ideogram ships the same transformers-5.x Qwen stack as krea; assemble per-component too,
+ # from the mirror for the same reason.
+ pipe = load_ideogram4_pipeline(
fetch_base,
- te_quant_mode = text_encoder_quant,
- target = target,
- dtype = dtype,
+ dtype,
hf_token = hf_token,
- logger = logger,
- local_files_only = local_files_only,
+ check_cancelled = lambda: self._raise_if_load_cancelled(
+ _load_token
+ ),
)
- )
- # The prefetched snapshot dir keeps from_pretrained off the hub (24 GB per FLUX.1
- # otherwise)
- pipe = pipeline_cls.from_pretrained(
- _base_local_dir or fetch_base, **pipe_kwargs
- )
- elif kind == "single_file" and fam.single_file_is_pipeline:
- # A single-file SDXL-style checkpoint is the WHOLE pipeline: load it through the pipeline
- # class with ``config`` on the base repo.
- sf_pipe_kwargs: dict[str, Any] = {
- "local_files_only": local_files_only,
- "torch_dtype": dtype,
- # ``config`` is a REPO FETCH ahead of the mirrored load, so a gated id would 401 here
- # first
- "config": fetch_base,
- "cache_dir": hub_cache_dir(),
- }
- if hf_token:
- sf_pipe_kwargs["token"] = hf_token
- pipe = pipeline_cls.from_single_file(single_file_path, **sf_pipe_kwargs)
- else:
- # Transformer-only single file; VAE/text-encoder/scheduler come from the base repo.
- sf_kwargs: dict[str, Any] = {
- "torch_dtype": dtype,
- "config": fetch_base,
- "subfolder": "transformer",
- "token": hf_token,
- "cache_dir": hub_cache_dir(),
- # config is a REPO ID, and diffusers forwards this into the load_config() that resolves
- # it, so without the flag this branch reaches the Hub on a load nobody asked for. The
- # pipeline assembly below was already guarded; this call was not.
- "local_files_only": local_files_only,
- }
- if kind == "gguf":
- # Dequantise the GGUF transformer on-device at the compute dtype.
- sf_kwargs["quantization_config"] = diffusers.GGUFQuantizationConfig(
- compute_dtype = dtype
- )
- # sd.cpp GGUFs prefix tensors with model.diffusion_model.; the FLUX.2 / Qwen converters
- # choke.
- _install_gguf_prefix_strip(transformer_cls, logger)
- # A safetensors single-file (fp8) carries its own dtype: no GGUF dequant config.
- transformer = transformer_cls.from_single_file(
- single_file_path, **sf_kwargs
- )
-
- if fam.name == KREA2_FAMILY_NAME:
- pipe = load_krea2_pipeline(
- fetch_base,
- dtype,
- hf_token = hf_token,
- transformer = transformer,
- # Same reason as the full-pipeline branch: the single file supplies only the denoiser,
- # so the encoder, VAE and tokenizer below are still GB this load promised not to
- # fetch.
- local_files_only = local_files_only,
- text_encoder = te_prequant_pipe_kwargs(
- fam,
- fetch_base,
- te_quant_mode = text_encoder_quant,
- target = target,
- dtype = dtype,
- hf_token = hf_token,
- logger = logger,
- local_files_only = local_files_only,
- ).get("text_encoder"),
- )
- else:
- pipe_kwargs = {
+ else:
+ pipe_kwargs = {
+ "local_files_only": local_files_only,
+ "torch_dtype": dtype,
+ "cache_dir": hub_cache_dir(),
+ }
+ if hf_token:
+ pipe_kwargs["token"] = hf_token
+ if fam.name == HIDREAM_FAMILY_NAME:
+ # The repo names a Llama text_encoder_4 it does not ship; supply it from the open
+ # mirror
+ pipe_kwargs.update(
+ hidream_te4_kwargs(
+ dtype,
+ hf_token,
+ fam = fam,
+ te_quant_mode = text_encoder_quant,
+ target = target,
+ local_files_only = local_files_only,
+ )
+ )
+ self._raise_if_load_cancelled(_load_token)
+ # A hosted pre-cast fp8 text encoder skips the dense TE download; the cast re-applies
+ # idempotently.
+ pipe_kwargs.update(
+ te_prequant_pipe_kwargs(
+ fam,
+ fetch_base,
+ te_quant_mode = text_encoder_quant,
+ target = target,
+ dtype = dtype,
+ hf_token = hf_token,
+ logger = logger,
+ local_files_only = local_files_only,
+ )
+ )
+ self._raise_if_load_cancelled(_load_token)
+ # The prefetched snapshot dir keeps from_pretrained off the hub (24 GB per FLUX.1
+ # otherwise)
+ pipe = pipeline_cls.from_pretrained(
+ _base_local_dir or fetch_base, **pipe_kwargs
+ )
+ elif kind == "single_file" and fam.single_file_is_pipeline:
+ # A single-file SDXL-style checkpoint is the WHOLE pipeline: load it through the pipeline
+ # class with ``config`` on the base repo.
+ sf_pipe_kwargs: dict[str, Any] = {
"local_files_only": local_files_only,
"torch_dtype": dtype,
- "transformer": transformer,
+ # ``config`` is a REPO FETCH ahead of the mirrored load, so a gated id would 401 here
+ # first
+ "config": fetch_base,
"cache_dir": hub_cache_dir(),
}
if hf_token:
- pipe_kwargs["token"] = hf_token
- if fam.name == HIDREAM_FAMILY_NAME:
+ sf_pipe_kwargs["token"] = hf_token
+ pipe = pipeline_cls.from_single_file(single_file_path, **sf_pipe_kwargs)
+ else:
+ # Transformer-only single file; VAE/text-encoder/scheduler come from the base repo.
+ sf_kwargs: dict[str, Any] = {
+ "torch_dtype": dtype,
+ "config": fetch_base,
+ "subfolder": "transformer",
+ "token": hf_token,
+ "cache_dir": hub_cache_dir(),
+ # config is a REPO ID, and diffusers forwards this into the load_config() that resolves
+ # it, so without the flag this branch reaches the Hub on a load nobody asked for. The
+ # pipeline assembly below was already guarded; this call was not.
+ "local_files_only": local_files_only,
+ }
+ if kind == "gguf":
+ # Dequantise the GGUF transformer on-device at the compute dtype.
+ sf_kwargs["quantization_config"] = diffusers.GGUFQuantizationConfig(
+ compute_dtype = dtype
+ )
+ # sd.cpp GGUFs prefix tensors with model.diffusion_model.; the FLUX.2 / Qwen converters
+ # choke.
+ _install_gguf_prefix_strip(transformer_cls, logger)
+ # A safetensors single-file (fp8) carries its own dtype: no GGUF dequant config.
+ transformer = transformer_cls.from_single_file(
+ single_file_path, **sf_kwargs
+ )
+ self._raise_if_load_cancelled(_load_token)
+
+ if fam.name == KREA2_FAMILY_NAME:
+ pipe = load_krea2_pipeline(
+ fetch_base,
+ dtype,
+ hf_token = hf_token,
+ check_cancelled = lambda: self._raise_if_load_cancelled(
+ _load_token
+ ),
+ transformer = transformer,
+ # Same reason as the full-pipeline branch: the single file supplies only the denoiser,
+ # so the encoder, VAE and tokenizer below are still GB this load promised not to
+ # fetch.
+ local_files_only = local_files_only,
+ text_encoder = te_prequant_pipe_kwargs(
+ fam,
+ fetch_base,
+ te_quant_mode = text_encoder_quant,
+ target = target,
+ dtype = dtype,
+ hf_token = hf_token,
+ logger = logger,
+ local_files_only = local_files_only,
+ ).get("text_encoder"),
+ )
+ else:
+ pipe_kwargs = {
+ "local_files_only": local_files_only,
+ "torch_dtype": dtype,
+ "transformer": transformer,
+ "cache_dir": hub_cache_dir(),
+ }
+ if hf_token:
+ pipe_kwargs["token"] = hf_token
+ if fam.name == HIDREAM_FAMILY_NAME:
+ pipe_kwargs.update(
+ hidream_te4_kwargs(
+ dtype,
+ hf_token,
+ fam = fam,
+ te_quant_mode = text_encoder_quant,
+ target = target,
+ local_files_only = local_files_only,
+ )
+ )
+ self._raise_if_load_cancelled(_load_token)
+ # Same pre-cast TE injection as above: the GGUF supplies the transformer, so the TE is the
+ # big download.
pipe_kwargs.update(
- hidream_te4_kwargs(
- dtype,
- hf_token,
- fam = fam,
+ te_prequant_pipe_kwargs(
+ fam,
+ fetch_base,
te_quant_mode = text_encoder_quant,
target = target,
+ dtype = dtype,
+ hf_token = hf_token,
+ logger = logger,
local_files_only = local_files_only,
)
)
- # Same pre-cast TE injection as above: the GGUF supplies the transformer, so the TE is the
- # big download.
- pipe_kwargs.update(
- te_prequant_pipe_kwargs(
- fam,
- fetch_base,
- te_quant_mode = text_encoder_quant,
- target = target,
- dtype = dtype,
- hf_token = hf_token,
- logger = logger,
- local_files_only = local_files_only,
+ self._raise_if_load_cancelled(_load_token)
+ pipe = pipeline_cls.from_pretrained(
+ _base_local_dir or fetch_base, **pipe_kwargs
)
- )
- pipe = pipeline_cls.from_pretrained(
- _base_local_dir or fetch_base, **pipe_kwargs
- )
- # Effective speed: GGUF defaults to `default` (~2.2x, below the quant noise floor); dense stays
- # bit-identical `off`.
- effective_speed = resolve_speed_mode(speed_mode, is_gguf = kind == "gguf")
- # A torchao-quantized dense transformer must be compiled (eager is ~30x slower, losing to GGUF)
- if transformer_quant_engaged is not None and effective_speed == SPEED_OFF:
- logger.info(
- "diffusion.transformer_quant: forcing speed_mode=default "
- "(quantized transformer must be compiled; eager is ~30x slower)"
+ self._raise_if_load_cancelled(_load_token)
+ # Lazy import (these modules import torch) keeps diffusion.py torch-free to import.
+ from .diffusion_eager_patches import (
+ install_compile_safe_patches,
+ uninstall_patches,
)
- effective_speed = SPEED_DEFAULT
- # Deferred speed auto for dense: stay eager and engage `default` on the 3rd image, where compile
- # amortises. Only when speed was unset.
- speed_deferred = (
- speed_mode is None
- and effective_speed == SPEED_OFF
- and transformer_quant_engaged is None
- and compile_eligible(target, is_gguf = False, family = fam)
- )
- # Speed optims run BEFORE placement, so snapshot the global backend flags first for unload restore.
- # The dense transformer quant above builds quiet configs, so it mutated none of these flags.
- backend_flags_before = snapshot_backend_flags()
- # Pick the attention kernel BEFORE compile: auto upgrades to cuDNN fused attention on NVIDIA (~1.18x)
- attention_engaged = apply_attention_backend(
- pipe,
- select_attention_backend(
- target, attention_backend, speed_active = effective_speed != SPEED_OFF
- ),
- logger = logger,
- target = target,
- )
- # Step caching (First-Block-Cache), also before compile: reuses the transformer tail across steps and
- # drops compile fullgraph. Tri-state: unset/auto -> FBCACHE_MIN_STEPS policy; off/fbcache pinned.
- cache_request = normalize_transformer_cache(transformer_cache)
- cache_auto = transformer_cache is None or cache_request == TC_AUTO
- cache_quant_active = transformer_quant_engaged is not None or bool(gguf_filename)
- default_steps: Optional[int] = None
- if cache_auto:
- default_steps, _ = default_generation_params(
- gguf_filename, repo_id, base, fam.name
+ from .diffusion_arch_patches import (
+ install_arch_patches,
+ uninstall_arch_patches,
)
- cache_request = TC_FBCACHE if default_steps >= FBCACHE_MIN_STEPS else None
- cache_engaged = apply_step_cache(
- pipe,
- mode = cache_request,
- threshold = transformer_cache_threshold,
- # GGUF transformers are quantized too, so the cache needs the higher threshold.
- quant_active = cache_quant_active,
- logger = logger,
- )
- # An auto decision can flip at generation time, but only on a cache-capable transformer
- cache_may_toggle = cache_auto and callable(
- getattr(getattr(pipe, "transformer", None), "enable_cache", None)
- )
- if cache_auto:
- if cache_engaged:
- cache_reason = (
- f"auto: {default_steps}-step default schedule reaches "
- f"{FBCACHE_MIN_STEPS}; re-checked per generation"
+
+ # Effective speed: GGUF defaults to `default` (~2.2x, below the quant noise floor); dense stays
+ # bit-identical `off`.
+ effective_speed = resolve_speed_mode(speed_mode, is_gguf = kind == "gguf")
+ # A torchao-quantized dense transformer must be compiled (eager is ~30x slower, losing to GGUF)
+ if transformer_quant_engaged is not None and effective_speed == SPEED_OFF:
+ logger.info(
+ "diffusion.transformer_quant: forcing speed_mode=default "
+ "(quantized transformer must be compiled; eager is ~30x slower)"
)
- elif cache_request is not None:
- cache_reason = "auto: model does not support step caching"
- else:
- cache_reason = (
- f"auto: {default_steps}-step default schedule is below "
- f"{FBCACHE_MIN_STEPS}; re-checked per generation"
+ effective_speed = SPEED_DEFAULT
+ # Deferred speed auto for dense: stay eager and engage `default` on the 3rd image, where compile
+ # amortises. Only when speed was unset.
+ speed_deferred = (
+ speed_mode is None
+ and effective_speed == SPEED_OFF
+ and transformer_quant_engaged is None
+ and compile_eligible(target, is_gguf = False, family = fam)
+ )
+ # Speed optims run BEFORE placement, so snapshot the global backend flags first for unload restore.
+ # The dense transformer quant above builds quiet configs, so it mutated none of these flags.
+ backend_flags_before = snapshot_backend_flags()
+ # Pick the attention kernel BEFORE compile: auto upgrades to cuDNN fused attention on NVIDIA (~1.18x)
+ attention_engaged = apply_attention_backend(
+ pipe,
+ select_attention_backend(
+ target, attention_backend, speed_active = effective_speed != SPEED_OFF
+ ),
+ logger = logger,
+ target = target,
+ )
+ self._raise_if_load_cancelled(_load_token)
+ # Step caching (First-Block-Cache), also before compile: reuses the transformer tail across steps and
+ # drops compile fullgraph. Tri-state: unset/auto -> FBCACHE_MIN_STEPS policy; off/fbcache pinned.
+ cache_request = normalize_transformer_cache(transformer_cache)
+ cache_auto = transformer_cache is None or cache_request == TC_AUTO
+ cache_quant_active = transformer_quant_engaged is not None or bool(
+ gguf_filename
+ )
+ default_steps: Optional[int] = None
+ if cache_auto:
+ default_steps, _ = default_generation_params(
+ gguf_filename, repo_id, base, fam.name
)
- else:
- cache_reason = "requested"
- # Everything to the _LoadState commit mutates PROCESS-WIDE state; the try/finally below restores it on
- # failure. gguf_transformer: the dense fast path still sets gguf_filename, but pipe.transformer is
- # dense (REGIONAL compile).
- gguf_transformer = kind == "gguf" and transformer_quant_engaged is None
-
- eager_patched = False
- compile_ctx = None
- state_committed = False
- # Lazy import (these modules import torch) keeps diffusion.py torch-free to import.
- from .diffusion_eager_patches import (
- install_compile_safe_patches,
- uninstall_patches,
- )
- from .diffusion_arch_patches import (
- install_arch_patches,
- uninstall_arch_patches,
- )
+ cache_request = TC_FBCACHE if default_steps >= FBCACHE_MIN_STEPS else None
+ cache_engaged = apply_step_cache(
+ pipe,
+ mode = cache_request,
+ threshold = transformer_cache_threshold,
+ # GGUF transformers are quantized too, so the cache needs the higher threshold.
+ quant_active = cache_quant_active,
+ logger = logger,
+ )
+ self._raise_if_load_cancelled(_load_token)
+ # An auto decision can flip at generation time, but only on a cache-capable transformer
+ cache_may_toggle = cache_auto and callable(
+ getattr(getattr(pipe, "transformer", None), "enable_cache", None)
+ )
+ if cache_auto:
+ if cache_engaged:
+ cache_reason = (
+ f"auto: {default_steps}-step default schedule reaches "
+ f"{FBCACHE_MIN_STEPS}; re-checked per generation"
+ )
+ elif cache_request is not None:
+ cache_reason = "auto: model does not support step caching"
+ else:
+ cache_reason = (
+ f"auto: {default_steps}-step default schedule is below "
+ f"{FBCACHE_MIN_STEPS}; re-checked per generation"
+ )
+ else:
+ cache_reason = "requested"
+ # The dense fast path sets gguf_filename, but its transformer is dense.
+ gguf_transformer = kind == "gguf" and transformer_quant_engaged is None
- try:
if effective_speed != SPEED_OFF:
install_compile_safe_patches()
# Per-arch compile-safe fusions; neutral under compile, tracked by the same eager_patched
@@ -4411,6 +4553,7 @@ class DiffusionBackend:
uninstall_patches()
uninstall_arch_patches()
+ self._raise_if_load_cancelled(_load_token)
# Pre-warmed torch.compile cache: a per-fingerprint inductor dir plus a bundle loaded before the
# first compiled forward pays the 25-58s compile once.
if effective_speed in (SPEED_DEFAULT, SPEED_MAX) and compile_eligible(
@@ -4439,6 +4582,7 @@ class DiffusionBackend:
logger = logger,
)
+ self._raise_if_load_cancelled(_load_token)
speed_applied = apply_speed_optims(
pipe,
target,
@@ -4450,6 +4594,7 @@ class DiffusionBackend:
offload_active = plan.offload_policy != OFFLOAD_NONE,
logger = logger,
)
+ self._raise_if_load_cancelled(_load_token)
if transformer_quant_engaged is not None and not speed_applied.get("compiled"):
# Compile could not engage: the quantized transformer runs eager, far slower than the GGUF it
# replaced
@@ -4468,6 +4613,7 @@ class DiffusionBackend:
offload_active = plan.offload_policy != OFFLOAD_NONE,
logger = logger,
)
+ self._raise_if_load_cancelled(_load_token)
te_quant = te_outcome.mode
# Same contract for the other half of the requested precision: an explicit encoder mode that
# engaged NOTHING leaves a dense bf16 encoder the caller did not ask for, and a PARTIAL cast
@@ -4516,6 +4662,7 @@ class DiffusionBackend:
# Apply the planned placement; apply_memory_plan returns what ACTUALLY engaged so status stays
# honest.
+ self._raise_if_load_cancelled(_load_token)
effective_policy, effective_tiling = apply_memory_plan(
pipe,
plan,
@@ -4624,7 +4771,7 @@ class DiffusionBackend:
}
)
- self._state = _LoadState(
+ state = _LoadState(
pipe = pipe,
family = fam,
repo_id = repo_id,
@@ -4663,7 +4810,14 @@ class DiffusionBackend:
base,
),
)
- state_committed = True
+ # Serialize publication with cancellation.
+ with self._load_cancel_lock:
+ self._raise_if_load_cancelled(_load_token)
+ self._state = state
+ state_committed = True
+ except BaseException as exc:
+ _clear_exception_frames(exc)
+ raise
finally:
# Pre-commit failure: roll back the process-wide mutations (symmetric with _unload_locked).
if not state_committed:
@@ -4674,6 +4828,8 @@ class DiffusionBackend:
if eager_patched:
uninstall_patches()
uninstall_arch_patches()
+ state = pipe = transformer = None
+ pipe_kwargs.clear()
clear_gpu_cache()
logger.info(
@@ -4707,6 +4863,7 @@ class DiffusionBackend:
text_encoder_quant: Optional[str] = None,
fetch_base: Optional[str] = None,
local_files_only: bool = False,
+ _load_token: Optional[int] = None,
) -> tuple[Any, str]:
"""Build the opt-in fast pipeline and return ``(pipe, engaged_scheme)``.
@@ -4730,6 +4887,13 @@ class DiffusionBackend:
download uses ``fetch_base``. A gated base 401s on both the prequant config read and the
dense pull, and a nonzero baked LoRA refuses the GGUF fallback, so that 401 fails the load.
"""
+ if _load_token is None:
+ _load_token = self._load_token
+
+ def check_cancelled() -> None:
+ self._raise_if_load_cancelled(_load_token)
+
+ check_cancelled()
fetch_base = fetch_base or prefer_ungated_mirror(base, hf_token)
# 1. Pre-quantized checkpoint, when one is configured for the resolved scheme.
scheme = select_transformer_quant_scheme(target, mode, family = getattr(fam, "name", None))
@@ -4744,6 +4908,7 @@ class DiffusionBackend:
source = resolve_prequant_source(
fam, scheme, path_override = prequant_path, base_repo = base
)
+ check_cancelled()
if source is not None:
transformer = load_prequantized_transformer(
transformer_cls,
@@ -4767,6 +4932,7 @@ class DiffusionBackend:
cache_dir = hub_cache_dir(),
logger = logger,
)
+ check_cancelled()
if transformer is not None:
pipe = self._assemble_pipe(
pipeline_cls,
@@ -4781,7 +4947,9 @@ class DiffusionBackend:
target = target,
fetch_base = fetch_base,
local_files_only = local_files_only,
+ check_cancelled = check_cancelled,
)
+ check_cancelled()
return pipe, scheme
# 2. Fallback: materialise the dense bf16 transformer and quantise it on-device.
@@ -4795,6 +4963,7 @@ class DiffusionBackend:
# raises rather than falling back to the hub) and a sharded load raises per missing shard, so a partial
# snapshot would drop a build the hub id completes. Off the hub id a base only the other root holds costs a
# re-download, or 401s into the GGUF fallback.
+ check_cancelled()
transformer = transformer_cls.from_pretrained(
fetch_base,
subfolder = "transformer",
@@ -4805,6 +4974,7 @@ class DiffusionBackend:
# refused here rather than allowed to pull it.
local_files_only = local_files_only,
)
+ check_cancelled()
pipe = self._assemble_pipe(
pipeline_cls,
base,
@@ -4818,7 +4988,9 @@ class DiffusionBackend:
target = target,
fetch_base = fetch_base,
local_files_only = local_files_only,
+ check_cancelled = check_cancelled,
)
+ check_cancelled()
if _has_active_lora(lora_specs):
# Bake the adapters BEFORE quantize_: peft wraps the dense Linears (post-quant torchao dispatch would
# TypeError), then quantize_ converts only each wrapper's frozen base_layer while the "lora_" side path
@@ -4829,7 +5001,9 @@ class DiffusionBackend:
hf_token = hf_token,
)
for name, path, _weight in baked:
+ check_cancelled()
pipe.load_lora_weights(path, adapter_name = name)
+ check_cancelled()
pipe.set_adapters(
[n for (n, _p, _w) in baked],
adapter_weights = [w for (_n, _p, w) in baked],
@@ -4841,6 +5015,7 @@ class DiffusionBackend:
len(baked),
scheme,
)
+ check_cancelled()
scheme = quantize_transformer(
pipe,
target,
@@ -4849,6 +5024,7 @@ class DiffusionBackend:
fast_accum = fast_accum,
logger = logger,
)
+ check_cancelled()
if scheme is None:
raise RuntimeError("transformer quant unsupported for this device/scheme")
return pipe, scheme
@@ -4867,11 +5043,14 @@ class DiffusionBackend:
target: Any = None,
fetch_base: Optional[str] = None,
local_files_only: bool = False,
+ check_cancelled: Optional[Callable[[], None]] = None,
) -> Any:
"""Assemble the diffusers pipeline around ``transformer`` and place it on ``device`` (a
no-op for an already-placed pre-quantized transformer; it moves the companions).
Everything below reads the base only to FETCH, so it uses ``fetch_base``. Matters when
``base_local_dir`` is None: nothing was staged, so a gated upstream would 401 here."""
+ check_cancelled = check_cancelled or (lambda: None)
+ check_cancelled()
base = fetch_base or prefer_ungated_mirror(base, hf_token)
if getattr(fam, "name", None) == KREA2_FAMILY_NAME:
# krea ships transformers-5.x configs and no top-level tokenizer files, so assemble per-component.
@@ -4887,16 +5066,19 @@ class DiffusionBackend:
logger = logger,
local_files_only = local_files_only,
).get("text_encoder")
+ check_cancelled()
pipe = load_krea2_pipeline(
base_local_dir or base,
dtype,
hf_token = hf_token,
transformer = transformer,
text_encoder = krea_te,
+ check_cancelled = check_cancelled,
# ``base_local_dir`` is None whenever nothing was staged, and then this is a repo id: the same guard
# the pipe_kwargs below carry for every other family.
local_files_only = local_files_only,
)
+ check_cancelled()
pipe.to(device)
return pipe
pipe_kwargs: dict[str, Any] = {
@@ -4919,6 +5101,7 @@ class DiffusionBackend:
)
)
if target is not None:
+ check_cancelled()
pipe_kwargs.update(
te_prequant_pipe_kwargs(
fam,
@@ -4931,7 +5114,9 @@ class DiffusionBackend:
local_files_only = local_files_only,
)
)
+ check_cancelled()
pipe = pipeline_cls.from_pretrained(base_local_dir or base, **pipe_kwargs)
+ check_cancelled()
pipe.to(device)
return pipe
@@ -6299,8 +6484,16 @@ class DiffusionBackend:
return True
if self._generation_owns_slot:
return False
- # Only teardown or transition ownership makes queued waiters cancellable.
- if not self._teardown_waiters and not self._transition_owns_slot:
+ # Only teardown, transition, or an ACCEPTED eject makes queued waiters cancellable. The
+ # eject raises _unload_waiters the moment it is admitted and reserves the teardown only
+ # once construction releases _lock, which can be minutes later. That window is exactly
+ # when the same counter denies these waiters admission, so without it here Stop answered
+ # False throughout and the request it could not cancel went on to run.
+ if (
+ not self._teardown_waiters
+ and not self._transition_owns_slot
+ and not self._unload_waiters
+ ):
return False
# Recheck live state so timed waiters observe a replacement handoff.
cancels = set(self._queued_generate_cancels)
@@ -6311,43 +6504,79 @@ class DiffusionBackend:
return True
def unload(self, *, expected_account: Optional[str] = None) -> dict[str, Any]:
- with self._lock:
- if expected_account is not None:
- from .gpu_arbiter import DIFFUSION, GpuBusyForAnotherAccountError
- from hub.services.models.account_access import require_resident_control
+ # fenced, and the try that owns it, start BEFORE the counter moves: a leaked _unload_waiters
+ # would make _wait_for_pending_unloads block every later load for the life of the process,
+ # and the flag keeps the finally honest when authorization refuses before the fence is raised.
+ fenced = False
+ try:
+ with self._generation_cancel_lock, self._load_cancel_lock:
+ if expected_account is not None:
+ from .gpu_arbiter import DIFFUSION, GpuBusyForAnotherAccountError
+ from hub.services.models.account_access import require_resident_control
- # Recheck under the generation-admitting lock before setting any cancel event.
- if (
- self._active_generate_cancel is not None
- and self._active_generate_account != expected_account
- ):
- raise GpuBusyForAnotherAccountError(DIFFUSION, 1)
- require_resident_control(
- DIFFUSION, self._state.repo_id if self._state is not None else None
- )
- # Abort an in-flight (lock-free) download so unload returns promptly. Under the lock, like video.py:
- # begin_load rebinds this attribute, so an unlocked read could set an event the current load no longer
- # watches.
- self._cancel_event.set()
- with self._generation_cancel_lock:
+ # Authorize before changing either cancellation event.
+ if (
+ self._active_generate_cancel is not None
+ and self._active_generate_account != expected_account
+ ):
+ raise GpuBusyForAnotherAccountError(DIFFUSION, 1)
+ require_resident_control(DIFFUSION, getattr(self._state, "repo_id", None))
+ # A published resident outranks a pending load: require_resident_control above has
+ # already authorized this caller against the model that is actually loaded, and a
+ # newcomer queueing a replacement over it must not cost the owner the right to
+ # eject its own model. Only with no resident to speak for does pending ownership
+ # decide, which is the window the CPU-load advisory was about.
+ loading = self._loading
+ if self._state is not None:
+ foreign_load = False
+ elif loading is not None and loading.error is None:
+ foreign_load = loading.account_id != expected_account
+ else:
+ foreign_load = any(
+ token == self._load_token and account != expected_account
+ for token, account in self._load_accounts.values()
+ )
+ if foreign_load:
+ raise GpuBusyForAnotherAccountError(DIFFUSION, 1)
+ # Fence loads and generations before waiting for construction.
+ self._unload_waiters += 1
+ self._unload_fence_clear.clear()
+ fenced = True
+ # The cancelled load's own epoch; _load_token is bumped just below.
+ cancelled_token = self._load_token
+ loading = self._loading
+ if loading is not None and loading.error is None:
+ # _run_load's finally drops this, so it spans the prefetch too, where nothing
+ # is registered in _load_accounts.
+ self._draining_repos.setdefault(cancelled_token, set()).update(
+ r for r in (loading.repo_id, loading.base_repo, loading.fetch_repo) if r
+ )
+ self._cancel_event.set()
+ self._load_token += 1
+ self._loading = None
if self._active_generate_cancel is not None:
self._active_generate_cancel.set()
- # Fence queued generations too: they are intentionally not cancelled by model lifecycle changes, so they
- # must wait and observe the post-teardown state.
- self._reserve_teardown_locked()
- self._load_token += 1
- self._loading = None
- # Wait for the signalled denoise to exit BEFORE tearing down: _unload_locked uninstalls process-wide state
- # (attention patches, GGUF compile hooks, backend flags, compile cache) the denoise still depends on.
- with self._model_transition_slot():
with self._lock:
- try:
- self._unload_locked()
- finally:
- # Released in a finally, exactly like begin_load: _unload_locked ends in clear_gpu_cache(), which
- # raises on a sticky CUDA fault, and an un-drained fence would refuse every later generation for
- # the life of the process.
- self._release_teardown_locked()
+ # Fence queued generations too: they are intentionally not cancelled by model lifecycle changes, so they
+ # must wait and observe the post-teardown state.
+ self._reserve_teardown_locked()
+ # Wait for the signalled denoise to exit BEFORE tearing down: _unload_locked uninstalls process-wide state
+ # (attention patches, GGUF compile hooks, backend flags, compile cache) the denoise still depends on.
+ with self._model_transition_slot():
+ with self._lock:
+ try:
+ self._unload_locked()
+ finally:
+ # Released in a finally, exactly like begin_load: _unload_locked ends in clear_gpu_cache(), which
+ # raises on a sticky CUDA fault, and an un-drained fence would refuse every later generation for
+ # the life of the process.
+ self._release_teardown_locked()
+ finally:
+ if fenced:
+ with self._load_cancel_lock:
+ self._unload_waiters -= 1
+ if not self._unload_waiters:
+ self._unload_fence_clear.set()
return self.status()
def _unload_locked(self) -> None:
diff --git a/studio/backend/core/inference/diffusion_ideogram4.py b/studio/backend/core/inference/diffusion_ideogram4.py
index 11569a04188..f97e74edb06 100644
--- a/studio/backend/core/inference/diffusion_ideogram4.py
+++ b/studio/backend/core/inference/diffusion_ideogram4.py
@@ -32,7 +32,7 @@ from __future__ import annotations
import inspect
import json
from pathlib import Path
-from typing import Any, Optional
+from typing import Any, Callable, Optional
from loggers import get_logger
@@ -76,13 +76,20 @@ def _patch_create_causal_mask() -> None:
_QKV_SPLIT = ("to_q", "to_k", "to_v")
-def _transformer_shard_paths(repo_id: str, subfolder: str, token: Optional[str]) -> list[str]:
+def _transformer_shard_paths(
+ repo_id: str,
+ subfolder: str,
+ token: Optional[str],
+ check_cancelled: Optional[Callable[[], None]] = None,
+) -> list[str]:
"""The local safetensors shard paths for ``repo_id/subfolder``.
Prefers the sharded index; falls back to the single-file name when the subfolder
ships one file. Resolves through a local dir when ``repo_id`` is a path, else the
Hub cache.
"""
+ check_cancelled = check_cancelled or (lambda: None)
+ check_cancelled()
from huggingface_hub import hf_hub_download
local_root = Path(repo_id).expanduser()
@@ -104,7 +111,11 @@ def _transformer_shard_paths(repo_id: str, subfolder: str, token: Optional[str])
shards = sorted(set(weight_map.values()))
except Exception: # noqa: BLE001 -- single-file subfolder has no index
shards = ["diffusion_pytorch_model.safetensors"]
- return [hf_hub_download(repo_id, f"{subfolder}/{name}", token = token) for name in shards]
+ paths = []
+ for name in shards:
+ check_cancelled()
+ paths.append(hf_hub_download(repo_id, f"{subfolder}/{name}", token = token))
+ return paths
def _read_transformer_config(repo_id: str, subfolder: str, token: Optional[str]) -> dict[str, Any]:
@@ -118,13 +129,19 @@ def _read_transformer_config(repo_id: str, subfolder: str, token: Optional[str])
return json.loads(Path(path).read_text(encoding = "utf-8"))
-def _convert_fp8_state_dict(raw: dict, hidden_size: int, dtype) -> dict:
+def _convert_fp8_state_dict(
+ raw: dict,
+ hidden_size: int,
+ dtype,
+ check_cancelled: Optional[Callable[[], None]] = None,
+) -> dict:
"""Dequantize + rename the vendor fp8 shards into the diffusers split layout.
A ``*.weight`` with a companion ``*.weight_scale`` is float8 per-channel (real weight =
``fp8.float() * weight_scale[:, None]``). Fused ``attention.qkv`` -> ``to_q``/``to_k``/``to_v``
(Q/K/V order), ``attention.o`` -> ``to_out.0``. Dense tensors pass through cast to ``dtype``.
"""
+ check_cancelled = check_cancelled or (lambda: None)
import torch
def dequantize(name: str):
@@ -135,6 +152,7 @@ def _convert_fp8_state_dict(raw: dict, hidden_size: int, dtype) -> dict:
converted: dict = {}
for key, value in raw.items():
+ check_cancelled()
if key.endswith("_scale"):
continue
if key + "_scale" not in raw:
@@ -160,8 +178,14 @@ def _convert_fp8_state_dict(raw: dict, hidden_size: int, dtype) -> dict:
return converted
-def _text_encoder_shard_paths(repo_id: str, token: Optional[str]) -> list[str]:
+def _text_encoder_shard_paths(
+ repo_id: str,
+ token: Optional[str],
+ check_cancelled: Optional[Callable[[], None]] = None,
+) -> list[str]:
"""The local safetensors shard paths for ``repo_id/text_encoder`` (index or single file)."""
+ check_cancelled = check_cancelled or (lambda: None)
+ check_cancelled()
from huggingface_hub import hf_hub_download
local_root = Path(repo_id).expanduser()
@@ -184,7 +208,11 @@ def _text_encoder_shard_paths(repo_id: str, token: Optional[str]) -> list[str]:
shards = sorted(set(weight_map.values()))
except Exception: # noqa: BLE001 -- single-file text encoder has no index
shards = ["model.safetensors"]
- return [hf_hub_download(repo_id, f"text_encoder/{name}", token = token) for name in shards]
+ paths = []
+ for name in shards:
+ check_cancelled()
+ paths.append(hf_hub_download(repo_id, f"text_encoder/{name}", token = token))
+ return paths
def _text_encoder_is_fp8(repo_id: str, token: Optional[str]) -> bool:
@@ -221,6 +249,7 @@ def load_ideogram4_text_encoder(
repo_id: str,
dtype,
hf_token: Optional[str] = None,
+ check_cancelled: Optional[Callable[[], None]] = None,
):
"""The Qwen3-VL text encoder for ``repo_id``.
@@ -229,9 +258,15 @@ def load_ideogram4_text_encoder(
dequant is required. The ``-nf4`` and dense repos fall through to the shared krea shim (which
also applies the rope_parameters remap).
"""
+ check_cancelled = check_cancelled or (lambda: None)
+ check_cancelled()
token = hf_token or None
- if not _text_encoder_is_fp8(repo_id, token):
- return load_krea2_text_encoder(repo_id, dtype, hf_token = token)
+ is_fp8 = _text_encoder_is_fp8(repo_id, token)
+ check_cancelled()
+ if not is_fp8:
+ return load_krea2_text_encoder(
+ repo_id, dtype, hf_token = token, check_cancelled = check_cancelled
+ )
import safetensors
import torch
@@ -243,16 +278,20 @@ def load_ideogram4_text_encoder(
if token:
config_kwargs["token"] = token
config = AutoConfig.from_pretrained(repo_id, **config_kwargs)
+ check_cancelled()
remap_rope_parameters(getattr(config, "text_config", config))
raw: dict = {}
- for path in _text_encoder_shard_paths(repo_id, token):
+ for path in _text_encoder_shard_paths(repo_id, token, check_cancelled = check_cancelled):
+ check_cancelled()
with safetensors.safe_open(path, "pt") as handle:
for key in handle.keys():
+ check_cancelled()
raw[key] = handle.get_tensor(key)
state_dict: dict = {}
for key, value in raw.items():
+ check_cancelled()
if key.endswith("_scale"):
continue
if key + "_scale" in raw:
@@ -263,13 +302,17 @@ def load_ideogram4_text_encoder(
else:
state_dict[key] = value.to(dtype)
+ check_cancelled()
# build at the target dtype: this ~8B scaffold loads FIRST, so the fp32 default can OOM a 64 GB host
default_dtype = torch.get_default_dtype()
torch.set_default_dtype(dtype)
try:
- model = Qwen3VLModel(config).to(dtype)
+ model = Qwen3VLModel(config)
+ check_cancelled()
+ model.to(dtype)
finally:
torch.set_default_dtype(default_dtype)
+ check_cancelled()
missing, unexpected = model.load_state_dict(state_dict, strict = False)
real_missing = [k for k in missing if not k.endswith("inv_freq")]
if real_missing or unexpected:
@@ -305,6 +348,7 @@ def load_ideogram4_transformer(
subfolder: str,
dtype,
hf_token: Optional[str] = None,
+ check_cancelled: Optional[Callable[[], None]] = None,
):
"""An ``Ideogram4Transformer2DModel`` for ``repo_id/subfolder`` (still on CPU).
@@ -312,22 +356,29 @@ def load_ideogram4_transformer(
layout and loads into a config-constructed model. Already-split ``-nf4`` repos (with a
``quantization_config``) delegate to stock ``from_pretrained`` so bnb re-applies the 4-bit weights.
"""
+ check_cancelled = check_cancelled or (lambda: None)
+ check_cancelled()
import diffusers
import safetensors
import torch
token = hf_token or None
config = _read_transformer_config(repo_id, subfolder, token)
- shard_paths = _transformer_shard_paths(repo_id, subfolder, token)
+ check_cancelled()
+ shard_paths = _transformer_shard_paths(
+ repo_id, subfolder, token, check_cancelled = check_cancelled
+ )
# Detect fp8 from shard HEADERS (keys() reads metadata only), checking all shards so a dense-first multi-shard
# export still routes to the dequant path. Only fp8 materializes tensors; -nf4 goes straight to from_pretrained.
is_fp8 = False
for path in shard_paths:
+ check_cancelled()
with safetensors.safe_open(path, "pt") as handle:
if any(key.endswith("_scale") for key in handle.keys()):
is_fp8 = True
break
+ check_cancelled()
if not is_fp8:
# Already the diffusers split layout (-nf4): let from_pretrained re-apply its quantization_config.
model_kwargs: dict[str, Any] = {"subfolder": subfolder, "torch_dtype": dtype}
@@ -337,10 +388,13 @@ def load_ideogram4_transformer(
raw: dict = {}
for path in shard_paths:
+ check_cancelled()
with safetensors.safe_open(path, "pt") as handle:
for key in handle.keys():
+ check_cancelled()
raw[key] = handle.get_tensor(key)
+ check_cancelled()
config.pop("quantization_config", None)
hidden_size = int(config["attention_head_dim"]) * int(config["num_attention_heads"])
# build at the target dtype: from_config materializes the full ~9B module while the first DiT and the encoder are
@@ -351,7 +405,9 @@ def load_ideogram4_transformer(
model = diffusers.Ideogram4Transformer2DModel.from_config(config)
finally:
torch.set_default_dtype(default_dtype)
- state_dict = _convert_fp8_state_dict(raw, hidden_size, dtype)
+ check_cancelled()
+ state_dict = _convert_fp8_state_dict(raw, hidden_size, dtype, check_cancelled = check_cancelled)
+ check_cancelled()
missing, unexpected = model.load_state_dict(state_dict, strict = False)
# rotary_emb.inv_freq is the only expected "missing" key (built in __init__); a real gap or leftover key must fail
# loudly rather than ship a partly random model.
@@ -361,6 +417,7 @@ def load_ideogram4_transformer(
f"ideogram4 fp8 remap left keys unmatched for {repo_id}/{subfolder}: "
f"missing={real_missing[:8]} unexpected={unexpected[:8]}"
)
+ check_cancelled()
model.to(dtype)
return model
@@ -369,30 +426,44 @@ def load_ideogram4_pipeline(
repo_id: str,
dtype,
hf_token: Optional[str] = None,
+ check_cancelled: Optional[Callable[[], None]] = None,
):
"""Assemble Ideogram4Pipeline from ``repo_id`` per-component (see module doc)."""
+ check_cancelled = check_cancelled or (lambda: None)
+ check_cancelled()
import diffusers
# The pipeline's text-encoder call uses a 5.x create_causal_mask signature; adapt it first.
_patch_create_causal_mask()
+ check_cancelled()
token = hf_token or None
model_kwargs: dict[str, Any] = {"torch_dtype": dtype}
if token:
model_kwargs["token"] = token
- text_encoder = load_ideogram4_text_encoder(repo_id, dtype, hf_token = token)
- tokenizer = load_krea2_tokenizer(repo_id, hf_token = token)
- transformer = load_ideogram4_transformer(repo_id, "transformer", dtype, hf_token = token)
+ text_encoder = load_ideogram4_text_encoder(
+ repo_id, dtype, hf_token = token, check_cancelled = check_cancelled
+ )
+ check_cancelled()
+ tokenizer = load_krea2_tokenizer(repo_id, hf_token = token, check_cancelled = check_cancelled)
+ check_cancelled()
+ transformer = load_ideogram4_transformer(
+ repo_id, "transformer", dtype, hf_token = token, check_cancelled = check_cancelled
+ )
+ check_cancelled()
# The second DiT drives the unconditional branch of Ideogram's dual-branch CFG (same class and size, always
# required).
unconditional_transformer = load_ideogram4_transformer(
- repo_id, "unconditional_transformer", dtype, hf_token = token
+ repo_id, "unconditional_transformer", dtype, hf_token = token, check_cancelled = check_cancelled
)
+ check_cancelled()
vae = diffusers.AutoencoderKLFlux2.from_pretrained(repo_id, subfolder = "vae", **model_kwargs)
+ check_cancelled()
scheduler = diffusers.FlowMatchEulerDiscreteScheduler.from_pretrained(
repo_id, subfolder = "scheduler", token = token
)
+ check_cancelled()
logger.info("diffusion.ideogram4: assembled pipeline from %s per-component", repo_id)
return diffusers.Ideogram4Pipeline(
scheduler = scheduler,
diff --git a/studio/backend/core/inference/diffusion_krea2.py b/studio/backend/core/inference/diffusion_krea2.py
index 3b380b93f11..b5b2af06a2b 100644
--- a/studio/backend/core/inference/diffusion_krea2.py
+++ b/studio/backend/core/inference/diffusion_krea2.py
@@ -27,7 +27,7 @@ from __future__ import annotations
import json
from pathlib import Path
-from typing import Any, Optional
+from typing import Any, Callable, Optional
from loggers import get_logger
@@ -55,8 +55,11 @@ def load_krea2_tokenizer(
repo_id: str,
hf_token: Optional[str] = None,
local_files_only: bool = False,
+ check_cancelled: Optional[Callable[[], None]] = None,
):
"""The Krea 2 tokenizer, tolerating the repo's transformers-5.x tokenizer config."""
+ if check_cancelled is not None:
+ check_cancelled()
from transformers import AutoTokenizer
kwargs: dict[str, Any] = {
@@ -69,6 +72,8 @@ def load_krea2_tokenizer(
try:
return AutoTokenizer.from_pretrained(repo_id, **kwargs)
except Exception as exc: # noqa: BLE001 -- 4.x config-parse failure, retry with override
+ if check_cancelled is not None:
+ check_cancelled()
logger.info("diffusion.krea2 tokenizer compat fallback: %s", exc)
return AutoTokenizer.from_pretrained(repo_id, extra_special_tokens = {}, **kwargs)
@@ -88,8 +93,11 @@ def load_krea2_text_encoder(
dtype,
hf_token: Optional[str] = None,
local_files_only: bool = False,
+ check_cancelled: Optional[Callable[[], None]] = None,
):
"""The Qwen3-VL text encoder, remapping 5.x ``rope_parameters`` for a 4.x runtime."""
+ if check_cancelled is not None:
+ check_cancelled()
from transformers import AutoConfig, Qwen3VLModel
kwargs: dict[str, Any] = {
@@ -100,6 +108,8 @@ def load_krea2_text_encoder(
if hf_token:
kwargs["token"] = hf_token
config = AutoConfig.from_pretrained(repo_id, **kwargs)
+ if check_cancelled is not None:
+ check_cancelled()
remap_rope_parameters(getattr(config, "text_config", config))
return Qwen3VLModel.from_pretrained(repo_id, config = config, dtype = dtype, **kwargs)
@@ -157,6 +167,7 @@ def load_krea2_pipeline(
with_transformer: bool = True,
text_encoder = None,
local_files_only: bool = False,
+ check_cancelled: Optional[Callable[[], None]] = None,
):
"""A ready ``Krea2Pipeline`` for ``repo_id`` (still on CPU; caller places it).
@@ -174,6 +185,8 @@ def load_krea2_pipeline(
component load below therefore resolves from the cache or raises, which is what the
caller's ``pipe_kwargs`` already does for every non-Krea family.
"""
+ check_cancelled = check_cancelled or (lambda: None)
+ check_cancelled()
import diffusers
# diffusers gained Krea2Pipeline in 0.39; on an older install the getattr chain below dies with a bare
@@ -190,11 +203,23 @@ def load_krea2_pipeline(
# A few KB, and it configures the components, so it is read before them: read last, a corrupt index only surfaced
# after the encoder, the VAE and the 26 GB transformer were already built.
model_index = _load_model_index(repo_id, hf_token = token, local_files_only = local_files_only)
- tokenizer = load_krea2_tokenizer(repo_id, hf_token = token, local_files_only = local_files_only)
+ check_cancelled()
+ tokenizer = load_krea2_tokenizer(
+ repo_id,
+ hf_token = token,
+ local_files_only = local_files_only,
+ check_cancelled = check_cancelled,
+ )
+ check_cancelled()
if text_encoder is None:
text_encoder = load_krea2_text_encoder(
- repo_id, dtype, hf_token = token, local_files_only = local_files_only
+ repo_id,
+ dtype,
+ hf_token = token,
+ local_files_only = local_files_only,
+ check_cancelled = check_cancelled,
)
+ check_cancelled()
scheduler = diffusers.FlowMatchEulerDiscreteScheduler.from_pretrained(
repo_id,
subfolder = "scheduler",
@@ -202,6 +227,7 @@ def load_krea2_pipeline(
local_files_only = local_files_only,
cache_dir = cache_dir,
)
+ check_cancelled()
vae = diffusers.AutoencoderKLQwenImage.from_pretrained(
repo_id,
subfolder = "vae",
@@ -210,6 +236,7 @@ def load_krea2_pipeline(
local_files_only = local_files_only,
cache_dir = cache_dir,
)
+ check_cancelled()
if transformer is None and with_transformer:
transformer = diffusers.Krea2Transformer2DModel.from_pretrained(
repo_id,
@@ -219,6 +246,7 @@ def load_krea2_pipeline(
local_files_only = local_files_only,
cache_dir = cache_dir,
)
+ check_cancelled()
return diffusers.Krea2Pipeline(
scheduler = scheduler,
vae = vae,
diff --git a/studio/backend/hub/services/models/deletion.py b/studio/backend/hub/services/models/deletion.py
index 0b66dcd99a0..21ce726714a 100644
--- a/studio/backend/hub/services/models/deletion.py
+++ b/studio/backend/hub/services/models/deletion.py
@@ -649,6 +649,10 @@ def _diffusion_blocks_delete(repo_id: str) -> Optional[str]:
for lid in getattr(engine, "loading_repo_ids", tuple)():
if _loaded_id_matches_repo(str(lid), repo_id):
return "An Images model load is using this repo; wait for it to finish"
+ # Cancelled but not yet unwound: deleting here yanks blobs from under a live Hub call.
+ for lid in getattr(engine, "draining_repo_ids", tuple)():
+ if _loaded_id_matches_repo(str(lid), repo_id):
+ return "An Images model load is still releasing this repo; wait for it to finish"
return None
diff --git a/studio/backend/tests/multi_account/test_media_unload_handoff.py b/studio/backend/tests/multi_account/test_media_unload_handoff.py
index ed2b2b9054e..705a144d712 100644
--- a/studio/backend/tests/multi_account/test_media_unload_handoff.py
+++ b/studio/backend/tests/multi_account/test_media_unload_handoff.py
@@ -6,6 +6,7 @@
import sys
import secrets
import threading
+import time
from pathlib import Path
from types import SimpleNamespace
@@ -23,7 +24,15 @@ from core.inference.diffusion_families import DIFFUSION_CANCELLED_MSG
from hub.services.models import account_access as access
from routes import inference, video
from state import active_generations
-from utils.account_context import bind_account, reset_account
+from utils.account_context import bind_account, current_account_id, reset_account
+
+from ..test_diffusion_backend import _FakePipeline
+from ..test_diffusion_backend import fake_runtime as _fake_runtime
+
+# Re-exported under its own name because pytest resolves a fixture by NAME, not by reference: the
+# tests below take `fake_runtime` as a parameter and never load the import, which reads to
+# scripts/verify_import_hoist.py as a hoisted import nothing uses.
+fake_runtime = _fake_runtime
def client_for(account):
@@ -42,6 +51,224 @@ def client_for(account):
return TestClient(app)
[email protected]("unloader", ["alice", "bob", "unsloth"])
+ "load_method,phase",
+ [
+ ("begin_load", "preflight"),
+ ("begin_load", "prefetch"),
+ ("begin_load", "construction"),
+ ("load_pipeline", "preflight"),
+ ("load_pipeline", "construction"),
+ ],
+)
+def test_cpu_load_cancellation_requires_its_owner(
+ monkeypatch, accounts, fake_runtime, tmp_path, unloader, load_method, phase
+):
+ from core.inference import diffusion as diff_mod
+
+ backend = DiffusionBackend()
+ entered, release, response_ready = (threading.Event() for _ in range(3))
+ threads, errors, responses = [], [], []
+ (tmp_path / "model_index.json").write_text("{}", encoding = "utf-8")
+ monkeypatch.setattr(gpu_arbiter, "_owner", None)
+ monkeypatch.setattr(gpu_arbiter, "_owner_account", None)
+ for name in ("_resident_accounts", "_prior_resident_accounts", "_resident_sharers"):
+ monkeypatch.setattr(access, name, {})
+ monkeypatch.setattr(diffusion_engine_router, "get_active_diffusion_engine", lambda: backend)
+ monkeypatch.setattr(backend, "_estimate_download_bytes", lambda *a, **k: (0, []))
+ monkeypatch.setattr(backend, "_prefetch_files", lambda *a, **k: str(tmp_path))
+ real_thread = diff_mod.account_thread
+
+ def tracked_thread(**kwargs):
+ thread = real_thread(**kwargs)
+ threads.append(thread)
+ return thread
+
+ monkeypatch.setattr(diff_mod, "account_thread", tracked_thread)
+ target, name = {
+ "preflight": (backend, "validate_load_request"),
+ "prefetch": (backend, "_prefetch_files"),
+ "construction": (_FakePipeline, "from_pretrained"),
+ }[phase]
+ original = getattr(target, name)
+
+ def parked(*args, **kwargs):
+ entered.set()
+ assert release.wait(10), "load barrier timed out"
+ return original(*args, **kwargs)
+
+ monkeypatch.setattr(target, name, parked)
+
+ def load():
+ try:
+ getattr(backend, load_method)(
+ str(tmp_path), family_override = "z-image", local_files_only = True
+ )
+ except RuntimeError as exc:
+ errors.append(str(exc))
+
+ def unload():
+ with client_for(accounts[unloader]) as client:
+ responses.append(client.post("/api/inference/images/unload"))
+ response_ready.set()
+
+ account_token = bind_account(accounts["alice"])
+ try:
+ access.note_resident_account("diffusion", str(tmp_path))
+ loader = tracked_thread(target = load, daemon = True)
+ finally:
+ reset_account(account_token)
+ ejector = threading.Thread(target = unload, daemon = True)
+ loader.start()
+ try:
+ assert entered.wait(10), errors
+ assert backend._state is None
+ assert gpu_arbiter.current_owner() is None
+ token, cancel = backend._load_token, backend._cancel_event
+ ejector.start()
+ deadline = time.monotonic() + 5
+ while not response_ready.is_set() and not cancel.is_set() and time.monotonic() < deadline:
+ response_ready.wait(0.01)
+ if unloader == "alice":
+ assert cancel.is_set(), "the owner could not cancel its load"
+ else:
+ assert response_ready.is_set(), "a foreign eject waited on construction"
+ assert responses[0].status_code == 409, responses[0].text
+ assert responses[0].json()["error"] == "gpu_busy"
+ assert not cancel.is_set()
+ assert backend._load_token == token
+ finally:
+ release.set()
+ loader.join(10)
+ for thread in [*threads, ejector]:
+ if thread.ident is not None:
+ thread.join(10)
+ assert not thread.is_alive()
+ if unloader == "alice":
+ assert responses[0].status_code == 200, responses[0].text
+ assert backend._state is None
+ assert all("cancelled" in error for error in errors)
+ else:
+ assert not errors
+ assert backend.is_loaded
+ backend.unload()
+
+
[email protected]("phase", ["prefetch", "construction", "resident"])
[email protected]("unloader", ["alice", "bob", "unsloth"])
+def test_pending_caller_cannot_block_load_owner_eject(
+ monkeypatch, accounts, fake_runtime, tmp_path, phase, unloader
+):
+ from core.inference import diffusion as diff_mod
+
+ backend = DiffusionBackend()
+ entered, pending, release, response_ready = (threading.Event() for _ in range(4))
+ threads, errors, responses = [], [], {}
+ (tmp_path / "model_index.json").write_text("{}", encoding = "utf-8")
+ monkeypatch.setattr(gpu_arbiter, "_owner", None)
+ monkeypatch.setattr(gpu_arbiter, "_owner_account", None)
+ for name in ("_resident_accounts", "_prior_resident_accounts", "_resident_sharers"):
+ monkeypatch.setattr(access, name, {})
+ monkeypatch.setattr(diffusion_engine_router, "get_active_diffusion_engine", lambda: backend)
+ monkeypatch.setattr(backend, "_estimate_download_bytes", lambda *a, **k: (0, []))
+ monkeypatch.setattr(backend, "_prefetch_files", lambda *a, **k: str(tmp_path))
+ real_thread = diff_mod.account_thread
+
+ def tracked_thread(**kwargs):
+ thread = real_thread(**kwargs)
+ threads.append(thread)
+ return thread
+
+ monkeypatch.setattr(diff_mod, "account_thread", tracked_thread)
+
+ def start(account, target):
+ token = bind_account(accounts[account])
+ try:
+ tracked_thread(target = target, daemon = True).start()
+ finally:
+ reset_account(token)
+
+ target, name = (
+ (backend, "_prefetch_files") if phase == "prefetch" else (_FakePipeline, "from_pretrained")
+ )
+ original = getattr(target, name)
+
+ def parked(*args, **kwargs):
+ if phase != "resident":
+ entered.set()
+ assert release.wait(10), "load barrier timed out"
+ return original(*args, **kwargs)
+
+ monkeypatch.setattr(target, name, parked)
+ validate = backend.validate_load_request
+
+ def pending_validation(*args, **kwargs):
+ if current_account_id() == accounts["bob"].account_id:
+ pending.set()
+ assert release.wait(10), "validation barrier timed out"
+ return validate(*args, **kwargs)
+
+ monkeypatch.setattr(backend, "validate_load_request", pending_validation)
+
+ def load():
+ try:
+ backend.begin_load(str(tmp_path), family_override = "z-image", local_files_only = True)
+ except RuntimeError as exc:
+ errors.append(str(exc))
+
+ def unload(account):
+ with client_for(accounts[account]) as client:
+ responses[account] = client.post("/api/inference/images/unload")
+ response_ready.set()
+
+ try:
+ if phase == "resident":
+ account_token = bind_account(accounts["alice"])
+ try:
+ backend.load_pipeline(
+ str(tmp_path), family_override = "z-image", local_files_only = True
+ )
+ access.note_resident_account("diffusion", str(tmp_path))
+ finally:
+ reset_account(account_token)
+ assert backend.is_loaded
+ assert backend._loading is None
+ else:
+ start("alice", load)
+ assert entered.wait(10), errors
+ assert backend._loading.account_id == accounts["alice"].account_id
+ assert backend._state is None
+ assert gpu_arbiter.current_owner() is None
+ start("bob", load)
+ assert pending.wait(10), errors
+ token, cancel = backend._load_token, backend._cancel_event
+ start(unloader, lambda: unload(unloader))
+ can_eject = unloader == "alice" or (phase == "resident" and accounts[unloader].is_owner)
+ if not can_eject:
+ assert response_ready.wait(5), "foreign eject waited on construction"
+ if phase == "resident":
+ assert responses[unloader].status_code == 404, responses[unloader].text
+ else:
+ assert responses[unloader].status_code == 409, responses[unloader].text
+ assert responses[unloader].json()["error"] == "gpu_busy"
+ assert not cancel.is_set()
+ assert backend._load_token == token
+ start("alice", lambda: unload("alice"))
+ assert cancel.wait(5), "a pending caller blocked the load owner's eject"
+ finally:
+ release.set()
+ for thread in threads:
+ thread.join(10)
+ assert not thread.is_alive()
+ response = responses[unloader if can_eject else "alice"]
+ assert response.status_code == 200, response.text
+ assert backend._state is None
+ assert backend._loading is None
+ assert not backend._load_accounts
+ assert errors and all("cancelled" in error for error in errors)
+
+
@pytest.mark.parametrize("unloader", ["alice", "unsloth"])
def test_unload_does_not_cancel_foreign_generation_started_after_route_check(
monkeypatch, accounts, unloader
diff --git a/studio/backend/tests/test_cached_gguf_routes.py b/studio/backend/tests/test_cached_gguf_routes.py
index f93af1c7ba1..db20fec6362 100644
--- a/studio/backend/tests/test_cached_gguf_routes.py
+++ b/studio/backend/tests/test_cached_gguf_routes.py
@@ -2968,6 +2968,57 @@ def test_delete_cached_refuses_repo_a_diffusion_load_is_downloading(monkeypatch)
assert "An Images model load is using this repo" in e.detail
+def test_delete_cached_refuses_repo_a_cancelled_diffusion_load_is_releasing(monkeypatch):
+ # An eject drops _loading at once so the load cancels promptly, but that thread keeps reading:
+ # through _prefetch_files it holds no lock and only checks the cancel event either side of the
+ # blocking Hub call. loading_repo_ids() is empty by then, so the drain list has to refuse.
+ from fastapi import HTTPException
+ from hub.services.models import deletion
+ import core.inference.diffusion_engine_router as der
+ import core.inference.video as video_mod
+
+ _clear_chat_delete_guards(monkeypatch)
+ monkeypatch.setattr(
+ der,
+ "get_active_diffusion_engine",
+ lambda: SimpleNamespace(
+ status = lambda: {"loaded": False, "repo_id": None},
+ loaded_repo_ids = lambda: (),
+ loading_repo_ids = lambda: (),
+ draining_repo_ids = lambda: ("unsloth/Qwen-Image-2512-GGUF",),
+ ),
+ )
+ monkeypatch.setattr(video_mod, "get_video_backend", _idle_video_backend)
+
+ try:
+ asyncio.run(deletion.delete_cached_model_response("unsloth/Qwen-Image-2512-GGUF"))
+ assert False, "expected HTTPException refusing the delete while the load unwinds"
+ except HTTPException as e:
+ assert e.status_code == 400
+ assert "still releasing this repo" in e.detail
+
+
+def test_delete_cached_is_unaffected_by_a_backend_without_a_drain(monkeypatch):
+ # sd.cpp and the video backend expose no draining_repo_ids; the guard must not start refusing.
+ from hub.services.models import deletion
+ import core.inference.diffusion_engine_router as der
+ import core.inference.video as video_mod
+
+ _clear_chat_delete_guards(monkeypatch)
+ monkeypatch.setattr(
+ der,
+ "get_active_diffusion_engine",
+ lambda: SimpleNamespace(
+ status = lambda: {"loaded": False, "repo_id": None},
+ loaded_repo_ids = lambda: (),
+ loading_repo_ids = lambda: (),
+ ),
+ )
+ monkeypatch.setattr(video_mod, "get_video_backend", _idle_video_backend)
+
+ assert deletion._diffusion_blocks_delete("unsloth/Qwen-Image-2512-GGUF") is None
+
+
def test_delete_cached_allows_sibling_of_loaded_diffusion_repo(monkeypatch):
# A loaded Images repo must not block deleting a different cached repo sharing a name prefix; the guard is `/`-boundary aware.
from fastapi import HTTPException
diff --git a/studio/backend/tests/test_diffusion_backend.py b/studio/backend/tests/test_diffusion_backend.py
index 54ef937a561..50ec3f35d8f 100644
--- a/studio/backend/tests/test_diffusion_backend.py
+++ b/studio/backend/tests/test_diffusion_backend.py
@@ -851,7 +851,7 @@ def fake_runtime(monkeypatch):
monkeypatch.setattr(
"core.inference.diffusion.load_ideogram4_pipeline",
- lambda repo_id, dtype, hf_token = None: _FakePipe(),
+ lambda repo_id, dtype, hf_token = None, check_cancelled = None: _FakePipe(),
)
monkeypatch.setitem(sys.modules, "torch", torch)
@@ -2502,6 +2502,756 @@ def test_unload_sets_cancel_event(fake_runtime):
assert backend._cancel_event.is_set()
[email protected]("reason", ["generation", "resident"])
+def test_rejected_unload_preserves_pending_work(fake_runtime, monkeypatch, reason):
+ from fastapi import HTTPException
+ from core.inference.gpu_arbiter import GpuBusyForAnotherAccountError
+ from hub.services.models import account_access
+
+ backend = DiffusionBackend()
+ pending = object()
+ backend._loading = pending
+ active = threading.Event()
+ backend._active_generate_cancel = active
+ backend._active_generate_account = "bob" if reason == "generation" else "alice"
+
+ def refuse(*args):
+ raise HTTPException(status_code = 404, detail = "Model not found")
+
+ monkeypatch.setattr(account_access, "require_resident_control", refuse)
+ error = GpuBusyForAnotherAccountError if reason == "generation" else HTTPException
+ with pytest.raises(error):
+ backend.unload(expected_account = "alice")
+ assert not active.is_set() and not backend._cancel_event.is_set()
+ assert backend._load_token == backend._unload_waiters == backend._teardown_waiters == 0
+ assert backend._loading is pending
+
+
+def test_generation_waits_for_unload_before_teardown_reservation(fake_runtime, monkeypatch):
+ backend = DiffusionBackend()
+ parked, release, attempted, started = (threading.Event() for _ in range(4))
+ real_lock = backend._lock
+ torn_down = []
+ observed = []
+ errors = []
+
+ class GateLock:
+ def __enter__(self):
+ if threading.current_thread() is ejector:
+ parked.set()
+ assert release.wait(5)
+ real_lock.acquire()
+
+ def __exit__(self, *args):
+ real_lock.release()
+ if threading.current_thread() is generator:
+ attempted.set()
+
+ monkeypatch.setattr(backend, "_lock", GateLock())
+ monkeypatch.setattr(backend, "_unload_locked", lambda: torn_down.append(True))
+
+ def eject():
+ try:
+ backend.unload()
+ except Exception as exc:
+ errors.append(str(exc))
+
+ def generate():
+ with backend._generation_slot(threading.Event()):
+ observed.append(bool(torn_down))
+ started.set()
+
+ ejector = threading.Thread(target = eject, daemon = True)
+ generator = threading.Thread(target = generate, daemon = True)
+ ejector.start()
+ try:
+ assert parked.wait(5)
+ generator.start()
+ assert attempted.wait(5)
+ assert not started.wait(0.1), "generation started before the accepted eject"
+ finally:
+ release.set()
+ ejector.join(5)
+ if generator.ident is not None:
+ generator.join(5)
+ assert not errors and not ejector.is_alive() and not generator.is_alive()
+ assert observed == [True]
+ assert backend._unload_waiters == backend._teardown_waiters == 0
+
+
+ "phase",
+ [
+ "validation",
+ "preinstall",
+ "resolution",
+ "memory_plan",
+ "dense_plan",
+ "transformer_error",
+ "pipeline_error",
+ "dense_error",
+ "dense_fallback",
+ "transformer",
+ "pipeline",
+ "dense",
+ "attention_error",
+ "cache_error",
+ "attention",
+ "step_cache",
+ "compile_cache",
+ "speed",
+ "quantize",
+ "component_plan",
+ "conditioning",
+ "placement",
+ "publication",
+ ],
+)
[email protected]("account_scoped", [False, True])
+def test_unload_cancels_pipeline_construction(
+ fake_runtime, tmp_path, monkeypatch, phase, account_scoped
+):
+ import gc
+ import weakref
+ from core.inference import diffusion as diff_mod
+ from core.inference import diffusion_eager_patches as ep
+
+ (tmp_path / "model.gguf").write_bytes(b"weights")
+ # ep.is_installed() is process-global, and other tests in this file leave the eager patches
+ # installed (test_generate_other_family_never_passes_cfg_trunc_ratio is one). Without this clean
+ # slate the assertion below reads THEIR leftovers and fails for 16 of the 46 cases whenever the
+ # file runs whole, while passing when this test is selected alone. Same idiom as
+ # test_failed_load_rolls_back_eager_patches.
+ ep.uninstall_patches()
+ backend = DiffusionBackend()
+ entered, release = threading.Event(), threading.Event()
+ outcome = {}
+ live = weakref.WeakSet()
+ reclaimed = []
+ pipelines = []
+ transformer_calls = []
+ setup_calls = []
+
+ def tracked():
+ value = _FakePipe()
+ value.cycle = value
+ live.add(value)
+ return value
+
+ def reclaim():
+ gc.collect()
+ reclaimed.append((len(live), backend._transition_owns_slot, backend._lock.locked()))
+
+ def park(value):
+ entered.set()
+ assert release.wait(5)
+ return value
+
+ def transformer(cls, *args, **kwargs):
+ transformer_calls.append(True)
+ value = tracked()
+ if phase == "transformer_error":
+ park(None)
+ raise RuntimeError("setup failed")
+ return park(value) if phase == "transformer" else value
+
+ def pipeline(cls, *args, **kwargs):
+ value = tracked()
+ value.transformer = kwargs["transformer"]
+ value.text_encoder = kwargs["text_encoder"]
+ pipelines.append(weakref.ref(value))
+ if phase == "pipeline_error":
+ park(None)
+ raise RuntimeError("setup failed")
+ return park(value) if phase == "pipeline" else value
+
+ def dense(*args, **kwargs):
+ value = tracked()
+ value.transformer = tracked()
+ pipelines.append(weakref.ref(value))
+ if phase in ("dense_error", "dense_fallback"):
+ park(None)
+ raise RuntimeError("setup failed")
+ return park(value), "int8"
+
+ def load():
+ try:
+ outcome["loaded"] = _load_into(
+ backend,
+ tmp_path,
+ speed_mode = "default" if phase == "compile_cache" else "eager",
+ transformer_quant = None
+ if phase == "dense_fallback"
+ else "int8"
+ if phase.startswith("dense")
+ else "off",
+ )
+ except Exception as exc:
+ outcome["error"] = str(exc)
+
+ with monkeypatch.context() as mp:
+ mp.setattr(diff_mod, "clear_gpu_cache", reclaim)
+ mp.setattr(_FakeTransformer, "from_single_file", classmethod(transformer))
+ mp.setattr(_FakePipeline, "from_pretrained", classmethod(pipeline))
+ mp.setattr(diff_mod, "te_prequant_pipe_kwargs", lambda *a, **k: {"text_encoder": tracked()})
+ if phase in ("attention", "step_cache", "compile_cache", "speed"):
+ if phase == "compile_cache":
+ mp.setattr(diff_mod, "compile_eligible", lambda *a, **k: True)
+ mp.setattr(diff_mod.compile_cache, "begin", lambda **k: None)
+ for stage, owner, name in (
+ ("attention", diff_mod, "apply_attention_backend"),
+ ("step_cache", diff_mod, "apply_step_cache"),
+ ("compile_cache", diff_mod.compile_cache, "begin"),
+ ("speed", diff_mod, "apply_speed_optims"),
+ ("quantize", diff_mod, "quantize_text_encoders"),
+ ):
+ original = getattr(owner, name)
+
+ def setup(
+ *args,
+ _stage = stage,
+ _original = original,
+ **kwargs,
+ ):
+ setup_calls.append(_stage)
+ result = _original(*args, **kwargs)
+ return park(result) if phase == _stage else result
+
+ mp.setattr(owner, name, setup)
+ if phase.startswith("dense"):
+ mp.setattr(diff_mod, "dense_transformer_supported", lambda target: True)
+ mp.setattr(diff_mod, "select_transformer_quant_scheme", lambda *a, **k: "int8")
+ mp.setattr(
+ backend,
+ "_dense_transformer_resident_bytes",
+ lambda *a, **k: park(0) if phase == "dense_plan" else 0,
+ )
+ mp.setattr(backend, "_load_dense_quant_pipeline", dense)
+ elif phase in ("resolution", "memory_plan"):
+ name = "_resolve_gguf_path" if phase == "resolution" else "_plan_memory"
+ original = getattr(backend, name)
+ mp.setattr(backend, name, lambda *a, **k: park(original(*a, **k)))
+ elif phase in ("validation", "preinstall"):
+ if phase == "validation":
+ original = backend.validate_load_request
+ mp.setattr(
+ backend, "validate_load_request", lambda *a, **k: park(original(*a, **k))
+ )
+ else:
+ mp.setattr(diff_mod, "select_attention_backend", lambda *a, **k: "test")
+ mp.setattr(
+ diff_mod, "_ensure_attention_backend_installed", lambda *a, **k: park(None)
+ )
+ elif phase in ("attention_error", "cache_error"):
+
+ def fail_setup(*args, **kwargs):
+ park(None)
+ raise RuntimeError("setup failed")
+
+ name = "apply_attention_backend" if phase == "attention_error" else "apply_step_cache"
+ mp.setattr(diff_mod, name, fail_setup)
+ elif phase in ("component_plan", "conditioning"):
+ owner, name = (
+ (diff_mod, "refine_memory_plan_for_components")
+ if phase == "component_plan"
+ else (diff_mod.cond_cache, "install")
+ )
+ original = getattr(owner, name)
+ mp.setattr(owner, name, lambda *a, **k: park(original(*a, **k)))
+ place = diff_mod.apply_memory_plan
+
+ def placement(*args, **kwargs):
+ setup_calls.append("placement")
+ return place(*args, **kwargs)
+
+ mp.setattr(diff_mod, "apply_memory_plan", placement)
+ elif phase in ("quantize", "placement", "publication"):
+ name = {
+ "quantize": "quantize_text_encoders",
+ "placement": "apply_memory_plan",
+ "publication": "_LoadState",
+ }[phase]
+ original = getattr(diff_mod, name)
+
+ def parked(*args, **kwargs):
+ return park(original(*args, **kwargs))
+
+ mp.setattr(diff_mod, name, parked)
+
+ loader = threading.Thread(target = load, daemon = True)
+ ejector = threading.Thread(
+ target = backend.unload,
+ kwargs = {"expected_account": diff_mod.current_account_id()} if account_scoped else {},
+ daemon = True,
+ )
+ loader.start()
+ try:
+ assert entered.wait(5), "load did not reach the blocked construction stage"
+ ejector.start()
+ assert backend._cancel_event.wait(2), "eject could not signal during construction"
+ if phase in ("validation", "preinstall"):
+ ejector.join(5)
+ assert not ejector.is_alive()
+ else:
+ assert ejector.is_alive(), "teardown must wait for the constructor to unwind"
+ finally:
+ release.set()
+ loader.join(5)
+ if ejector.ident is not None:
+ ejector.join(5)
+
+ assert not loader.is_alive() and not ejector.is_alive()
+ assert "loaded" not in outcome, "a cancelled pipeline was published as ready"
+ assert (
+ "setup failed" if phase.endswith("_error") and phase != "dense_error" else "cancelled"
+ ) in outcome["error"]
+ assert not backend.is_loaded
+ assert not ep.is_installed()
+ assert backend._teardown_waiters == 0
+ if phase in ("validation", "preinstall"):
+ assert not live and not reclaimed
+ else:
+ assert reclaimed and all(item == (0, True, True) for item in reclaimed), reclaimed
+ if phase in ("resolution", "memory_plan", "dense_plan"):
+ assert not transformer_calls and not pipelines, "cancelled planning constructed weights"
+ if phase == "dense_fallback":
+ assert not transformer_calls, "cancelled dense attempt started a GGUF fallback"
+ if phase == "transformer":
+ assert not pipelines, "cancelled load still constructed its companions"
+ if phase in ("attention", "step_cache", "compile_cache", "speed"):
+ assert setup_calls[-1] == phase, setup_calls
+ if phase in ("component_plan", "conditioning"):
+ assert not setup_calls, "cancelled setup still placed the pipeline"
+
+ # A fresh load still serves consecutive generations.
+ _load_into(backend, tmp_path)
+ pipe = backend._state.pipe
+ for _ in range(2):
+ assert len(backend.generate(prompt = "a sloth", steps = 2)["images"]) == 1
+ assert backend._state.pipe is pipe
+ backend.unload()
+
+
+ "phase",
+ [
+ "index",
+ "tokenizer",
+ "tokenizer_error",
+ "encoder_config",
+ "text_encoder",
+ "scheduler",
+ "vae",
+ "transformer",
+ "pipeline",
+ ],
+)
[email protected]("cancel", [False, True])
+def test_krea_component_load_honors_eject(fake_runtime, tmp_path, monkeypatch, phase, cancel):
+ import gc
+ import weakref
+ from core.inference import diffusion as diff_mod, diffusion_krea2 as krea
+
+ backend = DiffusionBackend()
+ calls, ejectors, reclaimed = [], [], []
+ live = weakref.WeakSet()
+ (tmp_path / "model_index.json").write_text("{}", encoding = "utf-8")
+
+ def record(name, value):
+ calls.append(name)
+ if name == phase and cancel:
+ ejector = threading.Thread(target = backend.unload, daemon = True)
+ ejectors.append(ejector)
+ ejector.start()
+ assert backend._cancel_event.wait(5), "eject could not signal during assembly"
+ return value
+
+ def component(name):
+ value = _FakePipe()
+ value.cycle = value
+ live.add(value)
+ return record(name, value)
+
+ def pretrained(name):
+ return types.SimpleNamespace(from_pretrained = lambda *a, **k: component(name))
+
+ def tokenizer(*args, **kwargs):
+ if phase == "tokenizer_error" and "extra_special_tokens" not in kwargs:
+ record("tokenizer_error", None)
+ raise ValueError("tokenizer config requires the compatibility fallback")
+ return component("tokenizer_retry" if phase == "tokenizer_error" else "tokenizer")
+
+ def reclaim():
+ gc.collect()
+ reclaimed.append(len(live))
+
+ diffusers = sys.modules["diffusers"]
+ diffusers.Krea2Pipeline = lambda **kwargs: component("pipeline")
+ diffusers.Krea2Transformer2DModel = pretrained("transformer")
+ diffusers.FlowMatchEulerDiscreteScheduler = pretrained("scheduler")
+ diffusers.AutoencoderKLQwenImage = pretrained("vae")
+ monkeypatch.setitem(
+ sys.modules,
+ "transformers",
+ types.SimpleNamespace(
+ AutoTokenizer = types.SimpleNamespace(from_pretrained = tokenizer),
+ AutoConfig = types.SimpleNamespace(
+ from_pretrained = lambda *a, **k: record("encoder_config", types.SimpleNamespace())
+ ),
+ Qwen3VLModel = pretrained("text_encoder"),
+ ),
+ )
+ monkeypatch.setattr(krea, "_load_model_index", lambda *a, **k: record("index", {}))
+ monkeypatch.setattr(diff_mod, "clear_gpu_cache", reclaim)
+ expected = [
+ "index",
+ "tokenizer",
+ "encoder_config",
+ "text_encoder",
+ "scheduler",
+ "vae",
+ "transformer",
+ "pipeline",
+ ]
+ if phase == "tokenizer_error":
+ expected[1:2] = ["tokenizer_error", "tokenizer_retry"]
+ try:
+ if cancel:
+ with pytest.raises(RuntimeError, match = "cancelled"):
+ backend.load_pipeline(
+ str(tmp_path), family_override = "krea-2", local_files_only = True
+ )
+ assert calls == expected[: expected.index(phase) + 1]
+ assert not backend.is_loaded
+ assert reclaimed and not any(reclaimed), reclaimed
+ else:
+ assert backend.load_pipeline(
+ str(tmp_path), family_override = "krea-2", local_files_only = True
+ )["loaded"]
+ assert calls == expected
+ for _ in range(2):
+ assert backend.generate(prompt = "a sloth", steps = 2)["images"]
+ finally:
+ for ejector in ejectors:
+ ejector.join(5)
+ assert not ejector.is_alive()
+ backend.unload()
+
+
[email protected]("kind", ["pipeline", "gguf", "single_file"])
+ "family,phase", [("hidream-i1", "te4"), ("hidream-i1", "encoder"), ("z-image", "encoder")]
+)
[email protected]("cancel", [False, True])
+def test_eager_encoder_cancellation_stops_pipeline_build(
+ fake_runtime, tmp_path, monkeypatch, kind, family, phase, cancel
+):
+ import gc
+ import weakref
+ from core.inference import diffusion as mod
+
+ backend = DiffusionBackend()
+ calls, ejectors, reclaimed = [], [], []
+ live = weakref.WeakSet()
+ (tmp_path / "model_index.json").write_text("{}", encoding = "utf-8")
+ filename = "model.gguf" if kind == "gguf" else "model.safetensors"
+ (tmp_path / filename).write_bytes(b"weights")
+ sys.modules["diffusers"].HiDreamImagePipeline = _FakePipeline
+ sys.modules["diffusers"].HiDreamImageTransformer2DModel = _FakeTransformer
+
+ def prepare(name, key):
+ calls.append(name)
+ value = _FakePipe()
+ value.cycle = value
+ live.add(value)
+ if cancel and phase == name:
+ thread = threading.Thread(target = backend.unload, daemon = True)
+ ejectors.append(thread)
+ thread.start()
+ assert backend._cancel_event.wait(5)
+ return {key: value}
+
+ def pipeline(*args, **kwargs):
+ calls.append("pipeline")
+ return _FakePipe()
+
+ def reclaim():
+ gc.collect()
+ reclaimed.append(len(live))
+
+ monkeypatch.setattr(mod, "hidream_te4_kwargs", lambda *a, **k: prepare("te4", "text_encoder_4"))
+ monkeypatch.setattr(
+ mod, "te_prequant_pipe_kwargs", lambda *a, **k: prepare("encoder", "text_encoder")
+ )
+ monkeypatch.setattr(_FakePipeline, "from_pretrained", staticmethod(pipeline))
+ monkeypatch.setattr(mod, "clear_gpu_cache", reclaim)
+ expected = (["te4"] if family == "hidream-i1" else []) + ["encoder", "pipeline"]
+ kwargs = dict(family_override = family, local_files_only = True, transformer_quant = "off")
+ if kind != "pipeline":
+ kwargs.update(gguf_filename = filename, base_repo = str(tmp_path))
+ try:
+ if cancel:
+ with pytest.raises(RuntimeError, match = "cancelled"):
+ backend.load_pipeline(str(tmp_path), **kwargs)
+ assert calls == expected[: expected.index(phase) + 1]
+ assert not backend.is_loaded
+ assert reclaimed and not any(reclaimed)
+ else:
+ assert backend.load_pipeline(str(tmp_path), **kwargs)["loaded"]
+ assert calls == expected
+ assert backend.generate(prompt = "a sloth", steps = 2)["images"]
+ finally:
+ for thread in ejectors:
+ thread.join(5)
+ assert not thread.is_alive()
+ backend.unload()
+
+
+ "phase",
+ [
+ "mask",
+ "text_encoder",
+ "tokenizer",
+ "transformer",
+ "unconditional_transformer",
+ "vae",
+ "scheduler",
+ "pipeline",
+ ],
+)
[email protected]("cancel", [False, True])
+def test_ideogram_component_load_honors_eject(fake_runtime, tmp_path, monkeypatch, phase, cancel):
+ import gc
+ import weakref
+ from core.inference import diffusion as mod, diffusion_ideogram4 as ideogram
+
+ backend = DiffusionBackend()
+ calls, ejectors, reclaimed = [], [], []
+ live = weakref.WeakSet()
+ (tmp_path / "model_index.json").write_text("{}", encoding = "utf-8")
+
+ def component(name):
+ calls.append(name)
+ value = _FakePipe()
+ value.cycle = value
+ live.add(value)
+ if cancel and phase == name:
+ thread = threading.Thread(target = backend.unload, daemon = True)
+ ejectors.append(thread)
+ thread.start()
+ assert backend._cancel_event.wait(5)
+ return value
+
+ def reclaim():
+ gc.collect()
+ reclaimed.append(len(live))
+
+ monkeypatch.setattr(mod, "load_ideogram4_pipeline", ideogram.load_ideogram4_pipeline)
+ monkeypatch.setattr(ideogram, "_patch_create_causal_mask", lambda: component("mask"))
+ monkeypatch.setattr(
+ ideogram, "load_ideogram4_text_encoder", lambda *a, **k: component("text_encoder")
+ )
+ monkeypatch.setattr(ideogram, "load_krea2_tokenizer", lambda *a, **k: component("tokenizer"))
+ monkeypatch.setattr(
+ ideogram,
+ "load_ideogram4_transformer",
+ lambda repo, subfolder, *a, **k: component(subfolder),
+ )
+ diffusers = sys.modules["diffusers"]
+ diffusers.Ideogram4Pipeline = lambda **kwargs: component("pipeline")
+ diffusers.AutoencoderKLFlux2 = types.SimpleNamespace(
+ from_pretrained = lambda *a, **k: component("vae")
+ )
+ diffusers.FlowMatchEulerDiscreteScheduler = types.SimpleNamespace(
+ from_pretrained = lambda *a, **k: component("scheduler")
+ )
+ monkeypatch.setattr(mod, "clear_gpu_cache", reclaim)
+ expected = [
+ "mask",
+ "text_encoder",
+ "tokenizer",
+ "transformer",
+ "unconditional_transformer",
+ "vae",
+ "scheduler",
+ "pipeline",
+ ]
+ try:
+ if cancel:
+ with pytest.raises(RuntimeError, match = "cancelled"):
+ backend.load_pipeline(
+ str(tmp_path), family_override = "ideogram-4", local_files_only = True
+ )
+ assert calls == expected[: expected.index(phase) + 1]
+ assert not backend.is_loaded
+ assert reclaimed and not any(reclaimed)
+ else:
+ assert backend.load_pipeline(
+ str(tmp_path), family_override = "ideogram-4", local_files_only = True
+ )["loaded"]
+ assert calls == expected
+ assert backend.generate(prompt = "a sloth", steps = 2)["images"]
+ finally:
+ for thread in ejectors:
+ thread.join(5)
+ assert not thread.is_alive()
+ backend.unload()
+
+
[email protected]("phase", ["gpu", "validation", "precision"])
+def test_begin_load_remembers_an_eject_during_preflight(fake_runtime, tmp_path, monkeypatch, phase):
+ from core.inference import diffusion as diff_mod
+
+ backend = DiffusionBackend()
+ entered, release, dispatched = threading.Event(), threading.Event(), threading.Event()
+ errors = []
+ (tmp_path / "model.gguf").write_bytes(b"weights")
+ monkeypatch.setattr(backend, "_run_load", lambda **kwargs: dispatched.set())
+
+ def load():
+ return backend.begin_load(
+ str(tmp_path), gguf_filename = "model.gguf", family_override = "z-image", gpu_ids = [0]
+ )
+
+ def invoke():
+ try:
+ load()
+ except Exception as exc:
+ errors.append(str(exc))
+
+ with monkeypatch.context() as mp:
+ owner, name = {
+ "gpu": (diff_mod, "resolve_selected_cuda_ordinal"),
+ "validation": (backend, "validate_load_request"),
+ "precision": (backend, "assert_precision_available"),
+ }[phase]
+ original = getattr(owner, name)
+ if phase == "gpu":
+ mp.setattr(
+ diff_mod,
+ "resolve_diffusion_device_target",
+ lambda: types.SimpleNamespace(device = "cuda"),
+ )
+
+ def parked(*args, **kwargs):
+ entered.set()
+ assert release.wait(5)
+ return 0 if phase == "gpu" else original(*args, **kwargs)
+
+ mp.setattr(owner, name, parked)
+ worker = threading.Thread(target = invoke, daemon = True)
+ worker.start()
+ try:
+ assert entered.wait(5)
+ backend.unload()
+ assert backend._unload_waiters == 0
+ finally:
+ release.set()
+ worker.join(5)
+
+ assert not worker.is_alive()
+ assert errors and "cancelled" in errors[0], errors
+ assert not dispatched.is_set()
+ assert backend._loading is None
+ load()
+ assert dispatched.wait(5)
+ backend.unload()
+
+
[email protected]("load_method", ["begin_load", "load_pipeline"])
+def test_replacement_load_waits_for_every_unload(fake_runtime, tmp_path, monkeypatch, load_method):
+ backend = DiffusionBackend()
+ (tmp_path / "model.gguf").write_bytes(b"weights")
+ parked = [threading.Event(), threading.Event()]
+ release = [threading.Event(), threading.Event()]
+ real_lock = backend._lock
+ errors = []
+ dispatched = threading.Event()
+ monkeypatch.setattr(backend, "_run_load", lambda **kwargs: dispatched.set())
+
+ class GateLock:
+ def __init__(self):
+ self.waited = set()
+
+ def __enter__(self):
+ name = threading.current_thread().name
+ if name.startswith("eject-") and name not in self.waited:
+ self.waited.add(name)
+ index = int(name[-1])
+ parked[index].set()
+ assert release[index].wait(5)
+ real_lock.acquire()
+
+ def __exit__(self, *args):
+ real_lock.release()
+
+ monkeypatch.setattr(backend, "_lock", GateLock())
+
+ def eject():
+ try:
+ backend.unload()
+ except Exception as exc:
+ errors.append(str(exc))
+
+ def load():
+ return getattr(backend, load_method)(
+ str(tmp_path),
+ gguf_filename = "model.gguf",
+ base_repo = "base/repo",
+ family_override = "z-image",
+ )
+
+ # The replacement WAITS for every pending eject; it is not refused. A load arriving after an
+ # eject started was never cancelled -- the eject bumped the epoch before this request existed --
+ # so failing it reported a cancellation that never happened, and turned an ordinary model switch
+ # during a generation into a 409 for the whole length of the denoise. Queue, then run.
+ replacement = {}
+
+ def replacement_load():
+ try:
+ load()
+ replacement["ok"] = True
+ except BaseException as exc: # noqa: BLE001
+ replacement["error"] = repr(exc)
+
+ ejectors = [threading.Thread(target = eject, name = f"eject-{i}", daemon = True) for i in range(2)]
+ for thread in ejectors:
+ thread.start()
+ waiter = None
+ try:
+ assert all(event.wait(5) for event in parked)
+ waiter = threading.Thread(target = replacement_load, name = "replacement", daemon = True)
+ waiter.start()
+ # Still queued behind BOTH ejects, including the one whose teardown has not been released.
+ waiter.join(0.5)
+ assert waiter.is_alive() and not replacement and not dispatched.is_set()
+ release[0].set()
+ ejectors[0].join(5)
+ assert not ejectors[0].is_alive()
+ waiter.join(0.5)
+ assert waiter.is_alive() and not replacement, "one eject left, the load must still wait"
+ finally:
+ for event in release:
+ event.set()
+ for thread in ejectors:
+ thread.join(5)
+
+ assert not errors and all(not thread.is_alive() for thread in ejectors)
+ # Once the last eject is done the queued replacement runs on its own, with no retry from the caller.
+ waiter.join(5)
+ assert not waiter.is_alive()
+ assert replacement.get("ok"), replacement
+ assert backend._teardown_waiters == 0
+ assert backend._unload_waiters == 0
+ if load_method == "begin_load":
+ assert dispatched.wait(5)
+ backend._loading = None # the worker is stubbed out, so retire its marker by hand
+ _load_into(backend, tmp_path)
+ assert backend.generate(prompt = "after eject", steps = 2)["images"]
+ backend.unload()
+
+
def test_prefetch_aborts_when_cancelled(tmp_path):
# A prefetch interrupted by unload raises instead of pulling the whole base, so the load can be preempted.
backend = DiffusionBackend()
@@ -2662,6 +3412,7 @@ def test_pipeline_kind_assembles_krea_and_ideogram_from_the_mirror(fake_runtime,
repo_id,
dtype,
hf_token = None,
+ check_cancelled = None,
):
seen["ideogram"] = repo_id
return _FakePipe()
@@ -3290,6 +4041,125 @@ def _stub_dense_quant(monkeypatch, *, scheme = "fp8"):
return calls
+ "stage",
+ [
+ "prequant",
+ "prequant_miss",
+ "transformer",
+ "encoder",
+ "pipeline",
+ "placement",
+ "lora_resolve",
+ "lora_first",
+ "lora_last",
+ "lora_set",
+ "quantize",
+ ],
+)
[email protected]("cancel", [False, True])
+def test_dense_build_cancellation_boundaries(fake_runtime, tmp_path, monkeypatch, stage, cancel):
+ import gc
+ import weakref
+ from core.inference import diffusion as dmod
+
+ backend = DiffusionBackend()
+ _stub_dense_quant(monkeypatch, scheme = "int8")
+ monkeypatch.setattr(backend, "_dense_transformer_resident_bytes", lambda *a, **k: 0)
+ (tmp_path / "model.gguf").write_bytes(b"weights")
+ entered, release = threading.Event(), threading.Event()
+ calls, outcome = [], {}
+ live = weakref.WeakSet()
+
+ def record(name, value = None):
+ calls.append(name)
+ if name == stage:
+ entered.set()
+ assert release.wait(5)
+ return value
+
+ def transformer(*args, **kwargs):
+ value = _FakePipe()
+ live.add(value)
+ return record("transformer", value)
+
+ class Pipe(_FakePipe):
+ def to(self, device):
+ return record("placement", super().to(device))
+
+ def load_lora_weights(self, path, adapter_name):
+ record("lora_first" if adapter_name == "first" else "lora_last")
+
+ def set_adapters(self, *args, **kwargs):
+ record("lora_set")
+
+ def pipeline(cls, base, **kwargs):
+ value = Pipe()
+ value.transformer = kwargs["transformer"]
+ live.add(value)
+ return record("pipeline", value)
+
+ monkeypatch.setattr(
+ _FakeTransformer, "from_pretrained", staticmethod(transformer), raising = False
+ )
+ monkeypatch.setattr(_FakePipeline, "from_pretrained", classmethod(pipeline))
+ monkeypatch.setattr(dmod, "te_prequant_pipe_kwargs", lambda *a, **k: record("encoder", {}))
+ monkeypatch.setattr(
+ backend,
+ "_resolve_lora_set",
+ lambda *a, **k: record("lora_resolve", (("first", "one", 1.0), ("last", "two", 0.5))),
+ )
+ monkeypatch.setattr(dmod, "quantize_transformer", lambda *a, **k: record("quantize", "int8"))
+ prequant = stage.startswith("prequant")
+ if prequant:
+ monkeypatch.setattr(dmod, "resolve_prequant_source", lambda *a, **k: object())
+ monkeypatch.setattr(
+ dmod,
+ "load_prequantized_transformer",
+ lambda *a, **k: record(stage, None if stage == "prequant_miss" else _FakePipe()),
+ )
+
+ def load():
+ try:
+ outcome["result"] = _load_into(
+ backend,
+ tmp_path,
+ transformer_quant = "int8",
+ local_files_only = True,
+ loras = None if prequant else [("one", 1.0), ("two", 0.5)],
+ )
+ except Exception as exc:
+ outcome["error"] = str(exc)
+
+ loader = threading.Thread(target = load, daemon = True)
+ ejector = threading.Thread(target = backend.unload, daemon = True)
+ loader.start()
+ try:
+ assert entered.wait(5), outcome
+ if cancel:
+ ejector.start()
+ assert backend._cancel_event.wait(2)
+ finally:
+ release.set()
+ loader.join(5)
+ if ejector.ident is not None:
+ ejector.join(5)
+ assert not loader.is_alive() and not ejector.is_alive()
+ assert backend._unload_waiters == backend._teardown_waiters == 0
+ if cancel:
+ assert "cancelled" in outcome.get("error", ""), outcome
+ assert calls[-1] == stage, calls
+ assert not backend.is_loaded
+ gc.collect()
+ assert not live
+ else:
+ assert "error" not in outcome, outcome
+ assert backend.is_loaded
+ assert backend.status()["transformer_quant"] == "int8"
+ assert calls.count("quantize") == (0 if stage == "prequant" else 1)
+ backend.unload()
+
+
def test_default_load_autos_dense_gate_and_falls_back(fake_runtime, tmp_path, monkeypatch):
# An unset dtype follows the hardware ladder: the dense gate is consulted, and a device without dense support falls back to GGUF.
from core.inference import diffusion as dmod
@@ -4464,7 +5334,9 @@ def test_assemble_pipe_routes_krea2_per_component(monkeypatch):
# production signature, and this branch never sees the guarded pipe_kwargs, so the keyword
# that keeps the no-download promise has to be one _assemble_pipe really passes.
local_files_only = False,
+ check_cancelled = None,
):
+ assert callable(check_cancelled)
calls["base"] = base
calls["transformer"] = transformer
calls["local_files_only"] = local_files_only
diff --git a/studio/backend/tests/test_diffusion_eject_ownership.py b/studio/backend/tests/test_diffusion_eject_ownership.py
new file mode 100644
index 00000000000..22f486b93ec
--- /dev/null
+++ b/studio/backend/tests/test_diffusion_eject_ownership.py
@@ -0,0 +1,328 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Who may eject, and in which order the claims are read.
+
+Three claims can speak for the backend at once: a PUBLISHED resident, an admitted BACKGROUND load,
+and a bare INVOCATION record for a caller still in preflight (a CPU Diffusers load claims no GPU and
+publishes nothing, so for its whole construction it is only that record). They disagree, so the order
+matters:
+
+ * the resident wins, because require_resident_control has already authorized the caller against the
+ model that is actually loaded -- a newcomer queueing a replacement over it must not cost the owner
+ the right to eject its own model;
+ * with no resident, the admitted background load decides;
+ * with neither, the invocation record decides, which is what keeps a second account from cancelling
+ someone else's pending CPU load.
+"""
+
+from __future__ import annotations
+
+import threading
+import time
+from types import SimpleNamespace
+
+import pytest
+
+from core.inference.diffusion import DiffusionBackend, _LoadingState
+from hub.services.models import account_access
+
+OWNER = "owner"
+ALICE = "a" * 32
+BOB = "b" * 32
+
+
+def backend(monkeypatch):
+ engine = DiffusionBackend()
+ # The eject path's own authorization is exercised here, not the hub's: require_resident_control
+ # answers "may this account touch the RESIDENT", and every case below has already decided that.
+ monkeypatch.setattr(account_access, "require_resident_control", lambda *a, **k: None)
+ # Stands in for the real teardown, which frees weights this test never allocated. It still drops
+ # the resident, so status() afterwards reads what a real eject would leave.
+ monkeypatch.setattr(engine, "_unload_locked", lambda: setattr(engine, "_state", None))
+ return engine
+
+
+def _resident(engine, repo_id = "org/model"):
+ engine._state = SimpleNamespace(repo_id = repo_id)
+
+
+def _background_load(
+ engine,
+ account_id,
+ repo_id = "org/other",
+):
+ engine._loading = _LoadingState(repo_id = repo_id, base_repo = repo_id, account_id = account_id)
+
+
+def _pending_invocation(engine, account_id):
+ """What a direct load_pipeline / a caller still inside begin_load preflight leaves behind."""
+ engine._load_accounts[object()] = (engine._load_token, account_id)
+
+
+def test_the_resident_owner_can_eject_while_another_account_queues_a_replacement(backend):
+ _resident(backend)
+ _background_load(backend, ALICE)
+ # Alice is merely downloading. Bob owns what is loaded, and require_resident_control said so.
+ assert backend.unload(expected_account = BOB)["loaded"] is False
+ assert backend._unload_waiters == 0
+
+
+def test_a_foreign_account_cannot_cancel_a_pending_background_load(backend):
+ _background_load(backend, ALICE)
+ with pytest.raises(account_access.GpuBusyForAnotherAccountError):
+ backend.unload(expected_account = BOB)
+ # Refused before the fence moved: the victim's load is untouched.
+ assert backend._unload_waiters == 0 and not backend._cancel_event.is_set()
+ assert backend._loading is not None
+
+
+def test_a_foreign_account_cannot_cancel_a_pending_cpu_load(backend):
+ # No GPU claim and no published resident: the invocation record is the only owner there is.
+ _pending_invocation(backend, ALICE)
+ with pytest.raises(account_access.GpuBusyForAnotherAccountError):
+ backend.unload(expected_account = BOB)
+ assert backend._unload_waiters == 0 and not backend._cancel_event.is_set()
+
+
+def test_the_account_that_started_the_load_can_still_cancel_it(backend):
+ _background_load(backend, ALICE)
+ _pending_invocation(backend, ALICE)
+ backend.unload(expected_account = ALICE)
+ assert backend._cancel_event.is_set() and backend._loading is None
+ assert backend._unload_waiters == 0
+
+
+def test_an_active_foreign_generation_still_refuses_the_eject(backend):
+ _resident(backend)
+ backend._active_generate_cancel = threading.Event()
+ backend._active_generate_account = ALICE
+ with pytest.raises(account_access.GpuBusyForAnotherAccountError):
+ backend.unload(expected_account = BOB)
+ assert not backend._active_generate_cancel.is_set()
+
+
+def test_a_refused_eject_leaves_no_fence_behind(backend, monkeypatch):
+ """Whatever raises, _unload_waiters comes back to zero: a leaked count would make every later
+ load wait out a teardown that is not happening."""
+ _resident(backend)
+ boom = RuntimeError("teardown exploded")
+
+ def explode():
+ raise boom
+
+ monkeypatch.setattr(backend, "_unload_locked", explode)
+ with pytest.raises(RuntimeError, match = "teardown exploded"):
+ backend.unload()
+ assert backend._unload_waiters == 0 and backend._teardown_waiters == 0
+
+
+def test_the_owner_can_eject_an_idle_backend(backend):
+ assert backend.unload(expected_account = OWNER)["loaded"] is False
+
+
+def test_a_preflight_caller_cannot_block_the_owner_of_the_load_in_flight(backend):
+ """Bob is inside begin_load validation (recorded, not admitted) while Alice's background load
+ runs. The admitted load owns the epoch, so Alice can still cancel her own construction."""
+ _background_load(backend, ALICE)
+ _pending_invocation(backend, BOB)
+ backend.unload(expected_account = ALICE)
+ assert backend._cancel_event.is_set() and backend._loading is None
+
+
+def test_a_preflight_caller_cannot_block_the_resident_owner(backend):
+ """Same, with a published resident instead of a load in flight."""
+ _resident(backend)
+ _pending_invocation(backend, BOB)
+ assert backend.unload(expected_account = ALICE)["loaded"] is False
+
+
+def test_an_eject_arriving_between_the_wait_and_the_lock_is_waited_out(backend, monkeypatch):
+ """An eject landing between the wait and the registration lock bumps the epoch too, so a
+ re-read adopts the eject's OWN token and the load is admitted into its teardown."""
+ from core.inference.diffusion import _account_owned_load
+
+ calls = {"waits": 0}
+ real_wait = backend._wait_for_pending_unloads
+ started = threading.Event()
+
+ def racing_wait(*args, **kwargs):
+ # Counted on ENTRY: the second call is the one that blocks, and the thread that releases the
+ # fence has to know it has started before it can let go of it.
+ calls["waits"] += 1
+ if calls["waits"] >= 2:
+ started.set()
+ real_wait(*args, **kwargs)
+ if calls["waits"] == 1:
+ # Exactly the gap: the eject lands after the wait returned and before the caller can
+ # take _load_cancel_lock.
+ with backend._load_cancel_lock:
+ backend._unload_waiters += 1
+ backend._load_token += 1
+
+ monkeypatch.setattr(backend, "_wait_for_pending_unloads", racing_wait)
+
+ @_account_owned_load
+ def admitted(self, *, _load_token = None):
+ return _load_token
+
+ def release():
+ started.wait(timeout = 10)
+ with backend._load_cancel_lock:
+ backend._unload_waiters -= 1
+ backend._unload_fence_clear.set()
+
+ releaser = threading.Thread(target = release, daemon = True)
+ releaser.start()
+ token = admitted(backend)
+ releaser.join(timeout = 10)
+
+ assert calls["waits"] == 2, "the load registered without waiting the racing eject out"
+ assert token == backend._load_token
+ assert backend._load_accounts == {}
+
+
+def test_a_load_waiting_out_an_eject_sleeps_instead_of_spinning(backend):
+ """_teardown_drained is still SET between the eject being accepted and the teardown being
+ reserved, so waiting on it there returned instantly and burned a core per waiter."""
+ with backend._load_cancel_lock:
+ backend._unload_waiters += 1
+ backend._unload_fence_clear.clear()
+ # Exactly the gap: no teardown is reserved yet, so this stays set the whole time.
+ assert backend._teardown_drained.is_set()
+
+ polls = {"n": 0}
+ real_wait = backend._unload_fence_clear.wait
+
+ def counted(timeout = None):
+ polls["n"] += 1
+ return real_wait(timeout = timeout)
+
+ backend._unload_fence_clear.wait = counted
+
+ def release():
+ time.sleep(0.5)
+ with backend._load_cancel_lock:
+ backend._unload_waiters -= 1
+ backend._unload_fence_clear.set()
+
+ releaser = threading.Thread(target = release, daemon = True)
+ releaser.start()
+ backend._wait_for_pending_unloads()
+ releaser.join(timeout = 10)
+
+ # ~5 polls at the 0.1s timeout. A spin does tens of thousands in the same half second.
+ assert polls["n"] <= 20, polls
+
+
+def test_stop_cancels_a_queued_generation_while_an_eject_waits_for_the_lock(backend):
+ """An eject raises the load fence when it is ACCEPTED and reserves the teardown only once
+ construction releases _lock. Through that window the same counter denies a queued generation
+ admission, so Stop had to be able to reach it: it answered False instead, and the request it
+ could not cancel went on to run once the eject finished."""
+ queued = threading.Event()
+ backend._queued_generate_cancels.add(queued)
+ with backend._load_cancel_lock:
+ backend._unload_waiters += 1
+ backend._unload_fence_clear.clear()
+ # Exactly the pre-reservation window: neither of the old predicates is true yet.
+ assert not backend._teardown_waiters and not backend._transition_owns_slot
+
+ assert backend.cancel_generate() is True
+ assert queued.is_set()
+
+
+def test_stop_still_reports_nothing_to_cancel_on_an_idle_backend(backend):
+ backend._queued_generate_cancels.add(threading.Event())
+ assert backend.cancel_generate() is False
+
+
+def test_a_cancelled_load_still_reports_the_repos_it_is_reading(backend):
+ """The eject drops _loading at once, but that load's thread reads on until it unwinds, holding
+ no lock inside _prefetch_files. The delete guard must keep refusing until it is done."""
+ backend._loading = _LoadingState(
+ repo_id = "org/model-GGUF",
+ base_repo = "org/base",
+ account_id = ALICE,
+ fetch_repo = "mirror/base",
+ )
+ everything = {"org/model-GGUF", "org/base", "mirror/base"}
+ cancelled_token = backend._load_token
+
+ backend.unload(expected_account = ALICE)
+
+ assert backend._loading is None
+ assert set(backend.draining_repo_ids()) == everything, "deletable while still being read"
+ # Not loading_repo_ids: release_if, keep-warm and the auto-switch read that as ownership.
+ assert backend.loading_repo_ids() == ()
+
+ # What _run_load's finally does when the load thread returns.
+ with backend._load_cancel_lock:
+ backend._draining_repos.pop(cancelled_token, None)
+ assert backend.draining_repo_ids() == ()
+
+
+def test_the_load_thread_releases_its_own_drain(backend, monkeypatch):
+ """Nothing else knows when a prefetch returned, and during one there is no record to key on."""
+ backend._loading = _LoadingState(
+ repo_id = "org/model-GGUF", base_repo = "org/base", account_id = ALICE
+ )
+ token = backend._load_token
+ with backend._load_cancel_lock:
+ backend._draining_repos[token] = {"org/model-GGUF", "org/base"}
+
+ monkeypatch.setattr(
+ backend, "load_pipeline", lambda **kw: (_ for _ in ()).throw(RuntimeError("cancelled"))
+ )
+ monkeypatch.setattr("core.inference.diffusion.detect_family_for_pick", lambda *a, **k: None)
+ backend._run_load(repo_id = "org/model-GGUF", _load_token = token)
+
+ assert backend.draining_repo_ids() == (), "the thread returned and nothing released its repos"
+
+
+def test_an_eject_with_no_load_in_flight_holds_nothing(backend):
+ """Nothing is reading, so holding ids would only refuse deletes for no reason."""
+ _resident(backend)
+ backend.unload(expected_account = ALICE)
+ assert backend._draining_repos == {} and backend.draining_repo_ids() == ()
+
+
+def test_a_generation_turned_away_by_the_load_fence_sleeps_on_it(backend):
+ """The retry waited on _teardown_drained, still SET in that window, so it spun against the
+ very _lock the eject needed."""
+ with backend._load_cancel_lock:
+ backend._unload_waiters += 1
+ backend._unload_fence_clear.clear()
+ assert backend._teardown_drained.is_set(), "the window this test is about"
+
+ polls = {"teardown": 0, "fence": 0}
+ real_fence = backend._unload_fence_clear.wait
+ real_teardown = backend._teardown_drained.wait
+
+ def counted_teardown(timeout = None):
+ polls["teardown"] += 1
+ return real_teardown(timeout = timeout)
+
+ def counted_fence(timeout = None):
+ polls["fence"] += 1
+ return real_fence(timeout = timeout)
+
+ backend._teardown_drained.wait = counted_teardown
+ backend._unload_fence_clear.wait = counted_fence
+
+ def release():
+ time.sleep(0.4)
+ with backend._load_cancel_lock:
+ backend._unload_waiters -= 1
+ backend._unload_fence_clear.set()
+
+ releaser = threading.Thread(target = release, daemon = True)
+ releaser.start()
+ with backend._generation_slot(threading.Event()):
+ pass
+ releaser.join(timeout = 10)
+
+ # ~4 sleeps across the 0.4s fence. A spin does tens of thousands, on the wrong event.
+ assert polls["fence"] >= 2, polls
+ assert polls["teardown"] == 0, "the retry slept on the fence that was already clear"
diff --git a/studio/backend/tests/test_diffusion_krea2.py b/studio/backend/tests/test_diffusion_krea2.py
index f16784120c3..b421f1379d9 100644
--- a/studio/backend/tests/test_diffusion_krea2.py
+++ b/studio/backend/tests/test_diffusion_krea2.py
@@ -198,13 +198,18 @@ def test_load_krea2_pipeline_threads_init_config(monkeypatch, tmp_path):
"core.inference.diffusion_krea2.load_krea2_tokenizer",
# Hand-written fakes with EXACT signatures, so they have to follow the production one:
# load_krea2_pipeline now passes local_files_only down to every component load.
- lambda repo_id, hf_token = None, local_files_only = False: SimpleNamespace(tag = "tokenizer"),
+ lambda repo_id,
+ hf_token = None,
+ local_files_only = False,
+ check_cancelled = None: SimpleNamespace(tag = "tokenizer"),
)
monkeypatch.setattr(
"core.inference.diffusion_krea2.load_krea2_text_encoder",
- lambda repo_id, dtype, hf_token = None, local_files_only = False: SimpleNamespace(
- tag = "text_encoder"
- ),
+ lambda repo_id,
+ dtype,
+ hf_token = None,
+ local_files_only = False,
+ check_cancelled = None: SimpleNamespace(tag = "text_encoder"),
)
pipe = load_krea2_pipeline(str(tmp_path), "bf16")
diff --git a/studio/backend/tests/test_diffusion_load_cancel_platform_matrix.py b/studio/backend/tests/test_diffusion_load_cancel_platform_matrix.py
new file mode 100644
index 00000000000..287ae8629b0
--- /dev/null
+++ b/studio/backend/tests/test_diffusion_load_cancel_platform_matrix.py
@@ -0,0 +1,174 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Load cancellation across [Windows, Linux, WSL, macOS] x [NVIDIA, AMD, Intel XPU, Apple MPS, CPU].
+
+Simulation notice. This host is Linux with an NVIDIA card. The OS axis is `sys.platform` /
+`platform.system` / `platform.release` (the WSL marker), the way
+`test_gpu_arch_gate_os_matrix_7624.py` and `test_llama_extra_args_platforms.py` do it, and the device
+axis is the documented per-instance seam `DiffusionBackend._pick_device_and_dtype`, the way
+`_force_cuda_target` in `test_diffusion_backend.py` does it. So these cells prove that the
+cancellation LOGIC is device- and platform-independent -- which is the claim under test, since none
+of it branches on either -- and they do NOT prove ROCm kernels, Metal placement, oneAPI or real VRAM
+reclamation. Only hardware can do that.
+
+What each cell asserts, from the three defects this file was added with:
+ * an eject cancels a load that was already in flight (the epoch, not a counter, decides);
+ * a load that arrives AFTER the eject started waits for teardown and then runs -- it is not
+ refused with "Diffusion load was cancelled.", which is a cancellation that never happened and,
+ through the route's 409, surfaced to the user as a failed model switch;
+ * both fences drain: `_unload_waiters` and `_teardown_waiters` return to zero, so no later load or
+ generation inherits a raised fence.
+"""
+
+import importlib.util
+import sys
+import threading
+from pathlib import Path
+
+import pytest
+
+from core.inference.diffusion import DiffusionBackend
+
+# The fake torch/diffusers runtime is reused rather than re-declared. Loaded by path because the
+# test directory is not a package, which is the same idiom test_mlx_context_platform_matrix.py uses.
+_SIBLING = "test_diffusion_backend"
+if _SIBLING in sys.modules:
+ _backend_tests = sys.modules[_SIBLING]
+else:
+ _spec = importlib.util.spec_from_file_location(
+ _SIBLING, Path(__file__).with_name(f"{_SIBLING}.py")
+ )
+ _backend_tests = importlib.util.module_from_spec(_spec)
+ sys.modules[_SIBLING] = _backend_tests
+ _spec.loader.exec_module(_backend_tests)
+
+fake_runtime = _backend_tests.fake_runtime
+
+# (sys.platform, platform.system(), platform.release() marker)
+OS_CELLS = {
+ "windows": ("win32", "Windows", "10.0.22631"),
+ "linux": ("linux", "Linux", "6.8.0-45-generic"),
+ # Indistinguishable from Linux except for this marker, which is exactly why the row exists.
+ "wsl": ("linux", "Linux", "5.15.153.1-microsoft-standard-WSL2"),
+ "macos": ("darwin", "Darwin", "24.1.0"),
+}
+
+# (device string handed to the loader, dtype attribute name on the fake torch)
+VENDOR_CELLS = {
+ "nvidia": ("cuda:0", "bfloat16"),
+ "amd": ("cuda:0", "float16"), # ROCm reports through the CUDA device string
+ "xpu": ("xpu:0", "bfloat16"),
+ "mps": ("mps", "float16"),
+ "cpu": ("cpu", "float32"),
+}
+
+# Cells a user can actually be in: no CUDA/ROCm/XPU on macOS, no Metal anywhere else.
+CELLS = [
+ (os_key, vendor)
+ for os_key in OS_CELLS
+ for vendor in VENDOR_CELLS
+ if (vendor == "mps") == (os_key == "macos") or vendor == "cpu"
+]
+
+
+def cell(request, monkeypatch, fake_runtime): # noqa: F811
+ """Place the process in one [OS, vendor] cell and hand back a backend pinned to it."""
+ import platform as platform_mod
+ import sys
+
+ os_key, vendor = request.param
+ platform_name, system_name, release = OS_CELLS[os_key]
+ device, dtype_name = VENDOR_CELLS[vendor]
+
+ monkeypatch.setattr(sys, "platform", platform_name)
+ monkeypatch.setattr(platform_mod, "system", lambda: system_name)
+ monkeypatch.setattr(platform_mod, "release", lambda: release)
+ if os_key == "wsl":
+ monkeypatch.setenv("WSL_DISTRO_NAME", "Ubuntu")
+ else:
+ monkeypatch.delenv("WSL_DISTRO_NAME", raising = False)
+
+ backend = DiffusionBackend()
+ dtype = getattr(sys.modules["torch"], dtype_name)
+ monkeypatch.setattr(backend, "_pick_device_and_dtype", lambda ordinal = None: (device, dtype))
+ backend._cell = (os_key, vendor, device)
+ return backend
+
+
[email protected]("cell", CELLS, indirect = True, ids = [f"{o}-{v}" for o, v in CELLS])
+def test_an_eject_cancels_the_load_that_was_already_in_flight(cell, tmp_path):
+ backend = cell
+ (tmp_path / "model.gguf").write_bytes(b"weights")
+ token = backend._load_token
+ backend.unload()
+ # The worker carries the epoch it was given; the eject bumped it, so the worker is cancelled.
+ with pytest.raises(RuntimeError, match = "cancelled"):
+ backend.load_pipeline(
+ str(tmp_path),
+ gguf_filename = "model.gguf",
+ base_repo = "base/repo",
+ family_override = "z-image",
+ _load_token = token,
+ )
+ assert backend._unload_waiters == 0 and backend._teardown_waiters == 0
+
+
[email protected]("cell", CELLS, indirect = True, ids = [f"{o}-{v}" for o, v in CELLS])
+def test_a_load_arriving_during_an_eject_queues_and_then_runs(cell, tmp_path, monkeypatch):
+ backend = cell
+ (tmp_path / "model.gguf").write_bytes(b"weights")
+ held, release, outcome = threading.Event(), threading.Event(), {}
+ dispatched = threading.Event()
+ monkeypatch.setattr(backend, "_run_load", lambda **kwargs: dispatched.set())
+
+ def hold_pipeline_lock():
+ # Stands in for the multi-minute constructor (or the active denoise) the eject must wait for.
+ with backend._lock:
+ held.set()
+ release.wait(10)
+
+ def eject():
+ try:
+ backend.unload()
+ outcome["eject"] = "done"
+ except BaseException as exc: # noqa: BLE001
+ outcome["eject"] = repr(exc)
+
+ def replacement():
+ try:
+ backend.begin_load(
+ str(tmp_path),
+ gguf_filename = "model.gguf",
+ base_repo = "base/repo",
+ family_override = "z-image",
+ )
+ outcome["load"] = "accepted"
+ except BaseException as exc: # noqa: BLE001
+ outcome["load"] = repr(exc)
+
+ holder = threading.Thread(target = hold_pipeline_lock, daemon = True)
+ holder.start()
+ assert held.wait(5)
+ ejector = threading.Thread(target = eject, daemon = True)
+ ejector.start()
+ for _ in range(500):
+ if backend._unload_waiters:
+ break
+ threading.Event().wait(0.01)
+ assert backend._unload_waiters == 1, "the eject never raised its fence"
+
+ waiter = threading.Thread(target = replacement, daemon = True)
+ waiter.start()
+ waiter.join(0.5)
+ assert waiter.is_alive() and "load" not in outcome, f"{backend._cell}: the load should queue"
+
+ release.set()
+ holder.join(5)
+ ejector.join(5)
+ waiter.join(5)
+ assert outcome.get("eject") == "done", outcome
+ assert outcome.get("load") == "accepted", f"{backend._cell}: {outcome}"
+ assert dispatched.wait(5)
+ assert backend._unload_waiters == 0 and backend._teardown_waiters == 0
diff --git a/studio/backend/tests/test_media_family_assembler_offline.py b/studio/backend/tests/test_media_family_assembler_offline.py
index 6ec1ae03c7a..1dcef2cdfa2 100644
--- a/studio/backend/tests/test_media_family_assembler_offline.py
+++ b/studio/backend/tests/test_media_family_assembler_offline.py
@@ -473,8 +473,6 @@ def test_the_krea_assembler_pins_every_component_to_the_live_cache(
def test_the_krea_tokenizer_and_encoder_helpers_pin_internally(monkeypatch, live_cache_root):
"""Both build their own kwargs dict, so the pin has to be inside each one."""
- transformers = pytest.importorskip("transformers")
-
from core.inference import diffusion_krea2
seen: dict = {}
@@ -487,9 +485,15 @@ def test_the_krea_tokenizer_and_encoder_helpers_pin_internally(monkeypatch, live
seen[self.tag] = kwargs
return SimpleNamespace(tag = self.tag, text_config = SimpleNamespace())
- monkeypatch.setattr(transformers, "AutoTokenizer", _Component("tokenizer"), raising = False)
- monkeypatch.setattr(transformers, "AutoConfig", _Component("config"), raising = False)
- monkeypatch.setattr(transformers, "Qwen3VLModel", _Component("text_encoder"), raising = False)
+ monkeypatch.setitem(
+ sys.modules,
+ "transformers",
+ SimpleNamespace(
+ AutoTokenizer = _Component("tokenizer"),
+ AutoConfig = _Component("config"),
+ Qwen3VLModel = _Component("text_encoder"),
+ ),
+ )
diffusion_krea2.load_krea2_tokenizer("krea/Krea-2-Turbo", local_files_only = True)
diffusion_krea2.load_krea2_text_encoder("krea/Krea-2-Turbo", "bf16", local_files_only = True)