Skip to content

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

Studio: run the image-load gates before the MLX router's diffusers fallback (#15066)

Daniel Han0b81657b7ce5
diff --git a/studio/backend/core/inference/gpu_residency.py b/studio/backend/core/inference/gpu_residency.py
index 265df81bd85..28120f680eb 100644
--- a/studio/backend/core/inference/gpu_residency.py
+++ b/studio/backend/core/inference/gpu_residency.py
@@ -718,6 +718,45 @@ def media_fit_kwargs(
return kwargs
+def refuse_unless_fits(
+ owner: str,
+ *,
+ policy: str = "off",
+ gpu_ids: Optional[Iterable[int]] = None,
+ need_mib: Optional[dict] = None,
+ cancel: Any = None,
+) -> None:
+ """acquire_for(allow_evict=False)'s check for an owner already holding its claim; mutates nothing.
+
+ For loads inside a generation (MLX diffusers fallback). Gives up on ``cancel``: a lock-holding evictor awaits our drain."""
+ from utils.account_context import current_account_id
+
+ while not arb._lock.acquire(timeout = 0.05):
+ if cancel is not None and cancel.is_set():
+ from core.inference.diffusion_families import DIFFUSION_CANCELLED_MSG
+ raise RuntimeError(DIFFUSION_CANCELLED_MSG)
+ try:
+ arb._sync_from_view()
+ others = [name for name in arb._residents if name != owner]
+ if not others:
+ return
+ if policy != "off" and owner in arb._KEPT_UNDER_ALWAYS:
+ coreside_locked(
+ owner,
+ policy = policy,
+ need_mib = need_mib,
+ gpu_ids = gpu_ids,
+ allow_evict = False,
+ evict_first = False,
+ acting = current_account_id(),
+ evicted = None,
+ )
+ return
+ raise arb.GpuOwnerBusyError(others[-1])
+ finally:
+ arb._lock.release()
+
+
def free_for(
owner: str,
gpu_ids: Optional[Iterable[int]],
diff --git a/studio/backend/core/inference/mlx_diffusion_routing.py b/studio/backend/core/inference/mlx_diffusion_routing.py
index 43041041d9f..cb49220c24c 100644
--- a/studio/backend/core/inference/mlx_diffusion_routing.py
+++ b/studio/backend/core/inference/mlx_diffusion_routing.py
@@ -379,6 +379,15 @@ class _RoutedGenerate:
return self.__self__._generate(**kwargs)
+class FallbackLoadRefusedError(RuntimeError):
+ """A gate a normal load passes refused the on-demand diffusers load; ``http`` is that load's refusal."""
+
+ def __init__(self, http: Any) -> None:
+ self.http = http
+ detail = getattr(http, "detail", None)
+ super().__init__(detail if isinstance(detail, str) else str(http))
+
+
class RoutedMlxEngine:
runs_off_torch_device = False
parses_prompt_attention = False
@@ -399,6 +408,7 @@ class RoutedMlxEngine:
self._route_lock = threading.Lock()
self._lock = threading.Lock()
self._load_kwargs: Optional[dict[str, Any]] = None
+ self._fallback_gate: Optional[Callable[..., Any]] = None
self._epoch = 0
# Replacement loads between their first epoch bump and registering their options: no fallback registers.
self._replacing = 0
@@ -499,7 +509,13 @@ class RoutedMlxEngine:
with self._lock:
return self._diffusers_ours
- def begin_load(self, repo_id: str, **kwargs: Any) -> dict[str, Any]:
+ def begin_load(
+ self,
+ repo_id: str,
+ *,
+ fallback_gate: Optional[Callable[..., Any]] = None,
+ **kwargs: Any,
+ ) -> dict[str, Any]:
# Fenced until this load's options are saved, so no request routes on the old model's options.
ours = self._drain_fallback(replacing = True)
try:
@@ -514,6 +530,7 @@ class RoutedMlxEngine:
self._mlx().begin_load(repo_id, **kwargs)
with self._lock:
self._load_kwargs = {"repo_id": repo_id, **kwargs}
+ self._fallback_gate = fallback_gate
finally:
with self._lock:
# A second bump: a route decided inside the fence holds a stale epoch once it lifts.
@@ -544,6 +561,7 @@ class RoutedMlxEngine:
self._fallback_cancel = cancel
self._fallback_done = done
self._active_generate_account = current_account_id()
+ gate = self._fallback_gate
bind_generation_cancel(cancel)
dropped = False
started = time.perf_counter()
@@ -552,17 +570,25 @@ class RoutedMlxEngine:
repo_id = kwargs.pop("repo_id")
if cancel.is_set() or self._epoch != epoch:
raise RuntimeError(DIFFUSION_CANCELLED_MSG)
- if unload_mlx:
- self._origin_identity = _identity_of(mlx) or self._origin_identity
- mlx.unload()
- dropped = True
+
+ def _start() -> None:
+ nonlocal dropped
+ if unload_mlx:
+ self._origin_identity = _identity_of(mlx) or self._origin_identity
+ mlx.unload()
+ dropped = True
+ with self._lock:
+ self._mlx_dropped = True
+ if cancel.is_set() or self._epoch != epoch:
+ raise RuntimeError(DIFFUSION_CANCELLED_MSG)
+ diffusers.begin_load(repo_id, **kwargs)
with self._lock:
- self._mlx_dropped = True
- if cancel.is_set() or self._epoch != epoch:
- raise RuntimeError(DIFFUSION_CANCELLED_MSG)
- diffusers.begin_load(repo_id, **kwargs)
- with self._lock:
- self._diffusers_ours = True
+ self._diffusers_ours = True
+
+ if gate is None:
+ _start()
+ else:
+ gate(_start, cancel = cancel)
while True:
if cancel.is_set() or self._epoch != epoch:
diffusers.unload()
@@ -784,6 +810,7 @@ class RoutedMlxEngine:
self._origin_identity = None
self._coexist = None
self._load_kwargs = None
+ self._fallback_gate = None
finally:
with self._lock:
self._epoch += 1
diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.py
index 4dbabc3aae9..3aaff1d0fc0 100644
--- a/studio/backend/routes/inference.py
+++ b/studio/backend/routes/inference.py
@@ -51423,6 +51423,77 @@ def _guard_diffusion_load_against_training() -> None:
)
+def _fallback_refusal_http(exc: BaseException) -> HTTPException:
+ from core.inference.gpu_arbiter import MultiModelAlwaysRefusal
+ from core.inference.gpu_residency import ChatLoadInFlightRefusal
+
+ if isinstance(exc, HTTPException):
+ return exc
+ if isinstance(exc, account_access.GpuBusyForAnotherAccountError):
+ return account_access.gpu_busy_error()
+ if isinstance(exc, (MultiModelAlwaysRefusal, ChatLoadInFlightRefusal)):
+ return exc.as_http_exception()
+ return HTTPException(status_code = 409, detail = str(exc))
+
+
+def _mlx_fallback_load_gate(request, gpu_ordinal, multi_model_mode):
+ """The image-load gates, for the MLX engine's diffusers fallback (which runs inside a generation).
+
+ Fit check refuses instead of evicting: a generation must not unload another model. No
+ note_resident_account / media_load_lock: the resident record and DIFFUSION claim stay the MLX
+ load's, and the lock would stall against retire_media_load."""
+ from core.inference.gpu_arbiter import DIFFUSION
+ from core.inference.gpu_residency import (
+ ChatLoadInFlightRefusal,
+ media_fit_kwargs,
+ refuse_unless_fits,
+ )
+ from core.inference.mlx_diffusion_routing import FallbackLoadRefusedError
+
+ def gate(start, cancel = None):
+ with ExitStack() as stack:
+ try:
+ account_access.require_live_account()
+ _guard_diffusion_load_against_training()
+ fit = media_fit_kwargs(DIFFUSION, request, gpu_ordinal, multi_model_mode)
+ stack.enter_context(_diffusion_training_admission())
+ refuse_unless_fits(
+ DIFFUSION,
+ policy = fit.get("policy", "off"),
+ gpu_ids = fit.get("gpu_ids"),
+ need_mib = fit.get("need_mib"),
+ cancel = cancel,
+ )
+ except (HTTPException, ChatLoadInFlightRefusal, RuntimeError) as exc:
+ if cancel is not None and cancel.is_set():
+ raise
+ raise FallbackLoadRefusedError(_fallback_refusal_http(exc)) from exc
+ for ref in (
+ request.model_path,
+ request.base_repo,
+ *(
+ r
+ for r in account_access.media_component_file_references(request)
+ if r and not Path(r).is_absolute()
+ ),
+ ):
+ if ref and _repo_is_in_the_hub_cache(ref) is not True:
+ _note_load_fetched_with_a_request_token(ref, request.hf_token)
+ return start()
+
+ return gate
+
+
+def _fallback_gate_kwarg(begin_load, gate) -> dict:
+ try:
+ import inspect
+ if "fallback_gate" in inspect.signature(begin_load).parameters:
+ return {"fallback_gate": gate}
+ except (TypeError, ValueError):
+ pass
+ return {}
+
+
async def _selected_gpu_ordinal(gpu_ids, *, allow_ranking: bool = True) -> Optional[int]:
"""The torch ordinal for a request's ``gpu_ids``, or None when there is nothing to honour.
@@ -52255,6 +52326,10 @@ async def load_diffusion_model_gated(
**_component_file_kwargs(request),
# Only when set: the native engines take no such argument.
**({"allow_oversized_load": True} if request.allow_oversized_load else {}),
+ **_fallback_gate_kwarg(
+ engine.begin_load,
+ _mlx_fallback_load_gate(request, gpu_ordinal, multi_model_mode),
+ ),
)
# A warm start that took the generation slot between the stop above and begin_load publishing the load would
# bring the old model's upsampler up beside this one: cancel it now that the load is visible.
@@ -52842,6 +52917,7 @@ async def _generate_diffusion_image_run(
ImageActivationShortfallError,
unified_memory_refusal_code,
)
+ from core.inference.mlx_diffusion_routing import FallbackLoadRefusedError
backend = get_active_diffusion_engine()
if account_access.managed_account():
@@ -52967,6 +53043,8 @@ async def _generate_diffusion_image_run(
)
except ValueError as exc:
raise HTTPException(status_code = 400, detail = str(exc))
+ except FallbackLoadRefusedError as exc:
+ raise exc.http from exc
except DiffusionModelReplacedError as exc:
if attempt > 0:
raise HTTPException(status_code = 409, detail = str(exc))
diff --git a/studio/backend/tests/test_diffusion_routes.py b/studio/backend/tests/test_diffusion_routes.py
index 0e3a101e0eb..67957236b48 100644
--- a/studio/backend/tests/test_diffusion_routes.py
+++ b/studio/backend/tests/test_diffusion_routes.py
@@ -759,6 +759,31 @@ def test_generate_unified_memory_load_refusal_is_structured_not_500(client, monk
assert "30 GB" in resp.json()["detail"]
+def test_generate_returns_the_load_refusal_of_a_refused_mlx_fallback(client, monkeypatch):
+ from fastapi import HTTPException
+ from core.inference.gpu_arbiter import MULTI_MODEL_REFUSAL_HEADERS
+ from core.inference.mlx_diffusion_routing import FallbackLoadRefusedError
+
+ backend = diffusion_module.get_diffusion_backend()
+ backend.loaded = True
+
+ def _refused(**kwargs):
+ raise FallbackLoadRefusedError(
+ HTTPException(
+ status_code = 409,
+ detail = "Unload the chat model first.",
+ headers = dict(MULTI_MODEL_REFUSAL_HEADERS),
+ )
+ )
+
+ monkeypatch.setattr(backend, "generate", _refused)
+ resp = client.post("/api/inference/images/generate", json = {"prompt": "p"})
+ assert resp.status_code == 409
+ assert resp.json()["detail"] == "Unload the chat model first."
+ for key, value in MULTI_MODEL_REFUSAL_HEADERS.items():
+ assert resp.headers.get(key) == value
+
+
def test_generate_user_cancellation_returns_409(client, monkeypatch):
backend = diffusion_module.get_diffusion_backend()
backend.loaded = True
diff --git a/studio/backend/tests/test_mlx_diffusion_routing.py b/studio/backend/tests/test_mlx_diffusion_routing.py
index 507c8f569f3..1faaaa4fd02 100644
--- a/studio/backend/tests/test_mlx_diffusion_routing.py
+++ b/studio/backend/tests/test_mlx_diffusion_routing.py
@@ -1156,3 +1156,212 @@ def test_no_fallback_no_shift_control(rig, monkeypatch, tmp_path):
)
monkeypatch.setattr(families, "family_pipeline_available", lambda _f: False)
assert rig.engine.status().get("shift_control") is None
+
+
+def _gated_rig(rig, gate):
+ rig.engine.begin_load(
+ "unsloth/Z-Image-Turbo-GGUF",
+ gguf_filename = "z-image-turbo-Q4_0.gguf",
+ local_files_only = True,
+ hf_token = None,
+ model_kind = "gguf",
+ fallback_gate = gate,
+ )
+ rig.log.clear()
+ return rig
+
+
+def test_the_fallback_gate_wraps_the_diffusers_load_and_never_reaches_an_engine(rig):
+ seen = []
+
+ def _gate(start, cancel = None):
+ seen.append("gate")
+ return start()
+
+ _gated_rig(rig, _gate)
+ assert "fallback_gate" not in (rig.mlx.load_kwargs or {})
+ assert _img2img(rig.engine)["engine"] == "diffusers"
+ assert seen == ["gate"]
+ assert "fallback_gate" not in (rig.diffusers.load_kwargs or {})
+ assert rig.log == [("mlx", "unload"), ("diffusers", "load"), ("diffusers", "generate")]
+
+
+def test_a_refusing_fallback_gate_leaves_mlx_loaded_and_keeps_the_refusal(rig):
+ from fastapi import HTTPException
+
+ refusal = HTTPException(status_code = 409, detail = "training is running")
+
+ def _gate(start, cancel = None):
+ raise routing.FallbackLoadRefusedError(refusal)
+
+ _gated_rig(rig, _gate)
+ with pytest.raises(routing.FallbackLoadRefusedError) as excinfo:
+ _img2img(rig.engine)
+ assert excinfo.value.http is refusal
+ assert rig.log == []
+ assert rig.engine.status()["engine_routing"]["resident"] == ["mlx"]
+ assert _txt2img(rig.engine)["engine"] == "mlx"
+
+
+def test_a_new_load_and_unload_drop_the_old_fallback_gate(rig):
+ _gated_rig(rig, lambda start, cancel = None: (_ for _ in ()).throw(AssertionError("stale gate")))
+ rig.engine.unload()
+ rig.engine.begin_load("unsloth/Z-Image-Turbo-GGUF", model_kind = "gguf", hf_token = None)
+ rig.log.clear()
+ assert _img2img(rig.engine)["engine"] == "diffusers"
+
+
+def route_gate(monkeypatch):
+ import routes.inference as inference
+ from core.inference import gpu_arbiter as arb
+ from core.inference import gpu_residency
+ from core.training import diffusion_training_service as dts
+
+ class _Trainer:
+ active = False
+
+ def is_active(self):
+ return self.active
+
+ def is_training_active(self):
+ return self.active
+
+ def gpu_load_admission(self):
+ from contextlib import contextmanager
+
+ @contextmanager
+ def _cm():
+ if self.active:
+ raise dts.TrainingActiveError("Diffusion training is running")
+ yield
+
+ return _cm()
+
+ trainer = _Trainer()
+ import core.training as training
+
+ monkeypatch.setattr(training, "get_training_backend", lambda: trainer)
+ monkeypatch.setattr(dts, "get_diffusion_training_service", lambda: trainer)
+ monkeypatch.setattr(inference.account_access, "require_live_account", lambda: None)
+ monkeypatch.setattr(inference, "_repo_is_in_the_hub_cache", lambda ref: False)
+ noted: list = []
+ monkeypatch.setattr(
+ inference,
+ "_note_load_fetched_with_a_request_token",
+ lambda ref, token: noted.append((ref, token)),
+ )
+ fit = {"kwargs": {}}
+ monkeypatch.setattr(gpu_residency, "media_fit_kwargs", lambda *a, **k: dict(fit["kwargs"]))
+ residents = {arb.DIFFUSION: None}
+ monkeypatch.setattr(arb, "_residents", residents)
+ monkeypatch.setattr(arb, "_sync_from_view", lambda: None)
+ request = SimpleNamespace(
+ model_path = "unsloth/Z-Image-Turbo-GGUF",
+ base_repo = "Tongyi-MAI/Z-Image-Turbo",
+ hf_token = "hf_request_token", # secret-scrub: allow
+ text_encoder_file = None,
+ vae_file = None,
+ text_encoder_files = None,
+ )
+ monkeypatch.setattr(inference.account_access, "media_component_file_references", lambda req: ())
+ gate = inference._mlx_fallback_load_gate(request, None, "off")
+ return SimpleNamespace(
+ gate = gate, trainer = trainer, noted = noted, fit = fit, residents = residents, arb = arb
+ )
+
+
+def test_the_route_gate_runs_a_normal_fallback_and_records_the_token(rig, route_gate):
+ _gated_rig(rig, route_gate.gate)
+ assert _img2img(rig.engine)["engine"] == "diffusers"
+ assert rig.log == [("mlx", "unload"), ("diffusers", "load"), ("diffusers", "generate")]
+ assert route_gate.noted == [
+ ("unsloth/Z-Image-Turbo-GGUF", "hf_request_token"),
+ ("Tongyi-MAI/Z-Image-Turbo", "hf_request_token"),
+ ]
+
+
+def test_the_fallback_is_refused_while_training_runs(rig, route_gate):
+ route_gate.trainer.active = True
+ _gated_rig(rig, route_gate.gate)
+ with pytest.raises(routing.FallbackLoadRefusedError) as excinfo:
+ _img2img(rig.engine)
+ assert excinfo.value.http.status_code == 409
+ assert "training is running" in excinfo.value.http.detail
+ assert rig.log == []
+ assert route_gate.noted == []
+ assert rig.engine.status()["engine_routing"]["resident"] == ["mlx"]
+
+
+def test_the_fallback_is_refused_when_the_trainer_wins_the_admission(rig, route_gate, monkeypatch):
+ import routes.inference as inference
+
+ monkeypatch.setattr(inference, "_guard_diffusion_load_against_training", lambda: None)
+ route_gate.trainer.active = True
+ _gated_rig(rig, route_gate.gate)
+ with pytest.raises(routing.FallbackLoadRefusedError) as excinfo:
+ _img2img(rig.engine)
+ assert excinfo.value.http.status_code == 409
+ assert "Diffusion training is running" in excinfo.value.http.detail
+ assert rig.log == []
+
+
+def test_the_fallback_is_refused_when_it_would_have_to_evict(rig, route_gate):
+ route_gate.residents[route_gate.arb.CHAT] = None
+ _gated_rig(rig, route_gate.gate)
+ with pytest.raises(routing.FallbackLoadRefusedError) as excinfo:
+ _img2img(rig.engine)
+ assert excinfo.value.http.status_code == 409
+ assert rig.log == []
+ assert rig.engine.status()["engine_routing"]["resident"] == ["mlx"]
+
+
+def test_the_fallback_is_refused_when_it_does_not_fit_under_always(rig, route_gate, monkeypatch):
+ from core.inference import gpu_residency
+
+ arb = route_gate.arb
+ route_gate.residents[arb.CHAT] = None
+ route_gate.fit["kwargs"] = {"policy": "always"}
+ monkeypatch.setattr(arb, "_view", lambda: {arb.CHAT: None, arb.DIFFUSION: None})
+ monkeypatch.setattr(
+ arb,
+ "resident_slots",
+ lambda name: [{"kind": "chat", "model": "unsloth/Qwen3-4B"}] if name == arb.CHAT else [],
+ )
+ monkeypatch.setattr(gpu_residency, "chat_load_in_flight", lambda: False)
+ _gated_rig(rig, route_gate.gate)
+ with pytest.raises(routing.FallbackLoadRefusedError) as excinfo:
+ _img2img(rig.engine)
+ http = excinfo.value.http
+ assert http.status_code == 409
+ assert http.headers == dict(arb.MULTI_MODEL_REFUSAL_HEADERS)
+ assert rig.log == []
+ assert rig.engine.status()["engine_routing"]["resident"] == ["mlx"]
+
+
+def test_only_an_engine_that_takes_a_fallback_gate_is_handed_one():
+ import routes.inference as inference
+
+ gate = object()
+ assert inference._fallback_gate_kwarg(routing.RoutedMlxEngine().begin_load, gate) == {
+ "fallback_gate": gate
+ }
+ assert inference._fallback_gate_kwarg(lambda repo_id, **kw: None, gate) == {}
+
+
+def test_the_fallback_fit_check_stops_waiting_for_the_arbiter_once_cancelled():
+ # An evictor holding the arbiter lock drains this generation: the wait must end on its cancel, not at the drain timeout.
+ import threading
+ import time
+
+ from core.inference import gpu_arbiter as arb
+ from core.inference.diffusion_families import DIFFUSION_CANCELLED_MSG
+ from core.inference.gpu_residency import refuse_unless_fits
+
+ cancel = threading.Event()
+ with arb._lock:
+ threading.Timer(0.2, cancel.set).start()
+ started = time.monotonic()
+ with pytest.raises(RuntimeError, match = DIFFUSION_CANCELLED_MSG):
+ refuse_unless_fits(arb.DIFFUSION, cancel = cancel)
+ assert time.monotonic() - started < 5