Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Studio: route Apple Silicon image requests to the MLX engine by default, diffusers MPS for the rest (#14883)
Daniel Han1492952a0924
diff --git a/studio/backend/core/inference/diffusion_engine_router.py b/studio/backend/core/inference/diffusion_engine_router.pyindex b4ec171586f..53092e865a7 100644--- a/studio/backend/core/inference/diffusion_engine_router.py+++ b/studio/backend/core/inference/diffusion_engine_router.py@@ -20,15 +20,17 @@ Env knobs:UNSLOTH_DIFFUSION_SD_CPP_MPS=0|1 allow native on Apple MPS (default off)UNSLOTH_DIFFUSION_SD_CPP_INSTALL=auto|0|1 allow lazy binary install (in sd_cpp_backend)UNSLOTH_DIFFUSION_SD_CPP_DEVICE=nvidia[:N] run native on a card torch cannot see- UNSLOTH_DIFFUSION_MLX=0|1|auto opt in to the Apple Silicon MLX engine (default 0; auto- behaves like 0 until a real-Mac A/B against diffusers MPS- and sd.cpp Metal settles the default)--The MLX engine (``mlx_diffusion_backend``) is considered only when UNSLOTH_DIFFUSION_MLX=1, on macOS 14+ on-Apple Silicon, for a GGUF of a family that declares ``mlx_model_config`` in a quant the converter handles-(Q4_0 / Q4_1 / Q5_0 / Q5_1 / Q8_0, the Q4_K / Q5_K / Q6_K mixes, BF16 / F16), with ``mlx`` and ``mflux`` installed.-Every refusal is recorded (``mlx_fallback_reason`` in the status) and falls through to the choice this module makes-without it.+ UNSLOTH_DIFFUSION_MLX=auto|0|1 the Apple Silicon MLX engine: auto (default) routes each request,+ 1 forces MLX alone, 0 turns it off (diffusers MPS as before)++The MLX engine (``mlx_diffusion_backend``) is considered on macOS 14+ on Apple Silicon, for a GGUF of a family that+declares ``mlx_model_config`` in a quant the converter handles (Q4_0 / Q4_1 / Q5_0 / Q5_1 / Q8_0, the Q4_K / Q5_K /+Q6_K mixes, BF16 / F16), with ``mlx`` and ``mflux`` installed. With ``auto`` the load goes to the routed engine+(``mlx_diffusion_routing``): plain text-to-image runs on MLX, and a request that needs a feature MLX lacks is served+by diffusers on MPS, loaded on demand. A load that itself needs such a feature (LoRA, separate component files, an+explicit precision) stays on diffusers. With ``1`` the MLX engine runs alone and refuses those requests. Every refusal+is recorded (``mlx_fallback_reason`` in the status) and falls through to the choice this module makes without it; on+a host that is not an Apple Silicon Mac ``auto`` records nothing."""from __future__ import annotations@@ -372,9 +374,23 @@ _engine_pick: Optional[str] = None_MLX_MIN_MACOS = (14, 0)+MLX_OFF = "off"+MLX_AUTO = "auto"+MLX_FORCE = "force"+++def mlx_mode() -> str:+ """``UNSLOTH_DIFFUSION_MLX``: unset / ``auto`` routes per request, ``1`` forces MLX, else off."""+ raw = os.environ.get("UNSLOTH_DIFFUSION_MLX", "auto").strip().lower()+ if raw in ("", "auto"):+ return MLX_AUTO+ if raw in _ENABLE_TOKENS:+ return MLX_FORCE+ return MLX_OFF++def _mlx_requested() -> bool:- """``auto`` means off for now."""- return os.environ.get("UNSLOTH_DIFFUSION_MLX", "0").strip().lower() in _ENABLE_TOKENS+ return mlx_mode() != MLX_OFFdef _mlx_host_refusal() -> Optional[str]:@@ -456,17 +472,26 @@ def mlx_selection(backend: Optional[str] = None,engine: Optional[str] = None,with_loras: bool = False,+ load_blocker: Optional[str] = None,) -> tuple[bool, Optional[str]]:"""``(use_mlx, refusal)``. Shared by selection and ``predict_engine`` so the download plan and the load- cannot disagree about MLX. ``engine`` is the load's own pick (``/images/load``'s ``engine`` field);- ``with_loras``: MLX cannot apply LoRAs, so such a load keeps its non-MLX engine."""- if not _mlx_requested():+ cannot disagree about MLX. ``engine`` is the load's own pick (``/images/load``'s ``engine`` field).+ ``with_loras`` says the load applies LoRA adapters, which the MLX engine cannot, so the load keeps the engine it+ would have had without MLX (in every mode) instead of reaching the MLX LoRA refusal.+ ``load_blocker`` (``mlx_load_blocker``) names a load option MLX cannot honour: in ``auto`` it keeps the load on+ diffusers; a forced MLX engine refuses that load in the route instead, as before."""+ mode = mlx_mode()+ if mode == MLX_OFF:+ return False, None+ if mode == MLX_AUTO and _mlx_host_refusal():return False, Noneforced = os.environ.get("UNSLOTH_DIFFUSION_ENGINE", "auto").strip().lower()if forced in (ENGINE_DIFFUSERS, ENGINE_SD_CPP):return False, f"UNSLOTH_DIFFUSION_ENGINE={forced} overrides UNSLOTH_DIFFUSION_MLX"if engine in (ENGINE_DIFFUSERS, ENGINE_SD_CPP):return False, f"the load asked for the {engine} engine"+ if mode == MLX_AUTO and _engine_config()[2]:+ return False, "UNSLOTH_DIFFUSION_SD_CPP_MPS=1 asks for the native engine on the Mac GPU"if model_kind and model_kind != "gguf":return False, f"the MLX engine loads GGUF picks only (got {model_kind})"if with_loras:@@ -489,9 +514,27 @@ def mlx_selection(runtime = _mlx_runtime_refusal()if runtime:return False, runtime+ if mode == MLX_AUTO and load_blocker:+ return False, f"{load_blocker} (diffusers serves this load)"return True, None+def mlx_load_blocker(+ *,+ loras: Any = None,+ component_files: Any = None,+ transformer_quant: Optional[str] = None,+ text_encoder_quant: Optional[str] = None,+) -> Optional[str]:+ from core.inference.mlx_diffusion_routing import load_blocker+ return load_blocker(+ loras = loras,+ component_files = component_files,+ transformer_quant = transformer_quant,+ text_encoder_quant = text_encoder_quant,+ )++def _refuse_lora_fallback(fam: DiffusionFamily,choice: str,@@ -501,13 +544,9 @@ def _refuse_lora_fallback(gguf_filename: Optional[str],engine: Optional[str],) -> None:- """Raise before unloading when MLX is skipped for LoRAs and the fallback engine cannot apply them."""- if (- not with_loras- or not mlx_selection(- fam, model_kind = model_kind, gguf_filename = gguf_filename, engine = engine- )[0]- ):+ if not with_loras or mlx_mode() != MLX_FORCE:+ return+ if not mlx_selection(fam, model_kind = model_kind, gguf_filename = gguf_filename, engine = engine)[0]:returnfrom .diffusion_lora import supports_lora@@ -527,7 +566,10 @@ def _note_mlx_refusal(reason: Optional[str]) -> None:with _lock:_mlx_fallback_reason = reasonif reason:- logger.warning("UNSLOTH_DIFFUSION_MLX=1 but the MLX engine is not used: %s", reason)+ if mlx_mode() == MLX_FORCE:+ logger.warning("UNSLOTH_DIFFUSION_MLX=1 but the MLX engine is not used: %s", reason)+ else:+ logger.info("MLX engine not used for this load: %s", reason)# Values of ``/images/load``'s ``engine`` field. "auto" (or absent) keeps the host's own choice.@@ -567,6 +609,9 @@ def engine_for(name: str) -> Any:from core.inference.sd_cpp_backend import get_sd_cpp_backendreturn get_sd_cpp_backend()if name == ENGINE_MLX:+ if mlx_mode() == MLX_AUTO:+ from core.inference.mlx_diffusion_routing import get_routed_mlx_engine+ return get_routed_mlx_engine()from core.inference.mlx_diffusion_backend import get_mlx_diffusion_backendreturn get_mlx_diffusion_backend()from core.inference.diffusion import get_diffusion_backend@@ -601,6 +646,11 @@ def cancel_generation_for_account(account_id: str) -> bool:# cancel_generate rechecks the owner under its lock.if engine.cancel_generate(expected_account = account_id):cancelled = True+ routing = sys.modules.get("core.inference.mlx_diffusion_routing")+ routed = getattr(routing, "_routed_mlx_engine", None) if routing is not None else None+ if routed is not None and routed._active_generate_account == account_id:+ if routed.cancel_generate(expected_account = account_id):+ cancelled = Truereturn cancelled@@ -765,6 +815,7 @@ def select_and_activate_engine(gguf_filename: Optional[str] = None,engine: Optional[str] = None,with_loras: bool = False,+ mlx_blocker: Optional[str] = None,) -> Any:"""Pick + activate the engine for loading ``fam`` on this host; return the engine.@@ -776,8 +827,9 @@ def select_and_activate_engine(a usable GPU, MPS is not enabled, the family has no native asset, or the binary is unavailable-- always BEFORE the slow load, so a fallback never strands a half-native load.- With UNSLOTH_DIFFUSION_MLX=1 the MLX engine is tried first (``mlx_selection``, which needs- ``gguf_filename`` to judge the quant); a refusal is recorded and the choice below runs unchanged.+ On an Apple Silicon Mac the MLX engine is tried first unless UNSLOTH_DIFFUSION_MLX=0 (``mlx_selection``, which+ needs ``gguf_filename`` to judge the quant, and ``mlx_blocker`` for a load option MLX cannot honour); a refusal is+ recorded and the choice below runs unchanged."""requested = _requested_engine(engine)refuse_engine_pick(fam, engine = engine, model_kind = model_kind)@@ -787,6 +839,7 @@ def select_and_activate_engine(gguf_filename = gguf_filename,engine = requested,with_loras = with_loras,+ load_blocker = mlx_blocker,)_note_mlx_refusal(mlx_refusal)if use_mlx:@@ -1049,6 +1102,7 @@ def predict_engine(gguf_filename: Optional[str] = None,engine: Optional[str] = None,with_loras: bool = False,+ mlx_blocker: Optional[str] = None,) -> str:"""The engine a load of ``fam`` would select on this host, WITHOUT any side effect. ``engine`` is the load's ownpick, as in ``select_and_activate_engine``; a pick selection would refuse raises the same ValueError here.@@ -1074,6 +1128,7 @@ def predict_engine(gguf_filename = gguf_filename,engine = requested,with_loras = with_loras,+ load_blocker = mlx_blocker,)[0]:return ENGINE_MLXif model_kind and model_kind != "gguf":@@ -1262,7 +1317,11 @@ def _engine_resolved(active: str) -> dict[str, Any]:elif active == ENGINE_SD_CPP:reason = "native sd.cpp engine chosen for this host"elif active == ENGINE_MLX:- reason = "MLX engine (UNSLOTH_DIFFUSION_MLX=1)"+ reason = (+ "MLX engine (UNSLOTH_DIFFUSION_MLX=1)"+ if mlx_mode() == MLX_FORCE+ else "MLX engine on Apple Silicon; diffusers serves what MLX cannot"+ )else:reason = _fallback_reason or "diffusers selected"return {diff --git a/studio/backend/core/inference/gpu_residency.py b/studio/backend/core/inference/gpu_residency.pyindex e6f483423df..265df81bd85 100644--- a/studio/backend/core/inference/gpu_residency.py+++ b/studio/backend/core/inference/gpu_residency.py@@ -220,7 +220,11 @@ def _image_need(request: Any, gpu_ordinal: Optional[int]) -> Optional[tuple[int,resolve_model_kind,)from core.inference.diffusion_auto_policy import resident_bytes_from_declared- from core.inference.diffusion_engine_router import has_active_loras, predict_engine+ from core.inference.diffusion_engine_router import (+ has_active_loras,+ mlx_load_blocker,+ predict_engine,+ )from core.inference.diffusion_families import (detect_family_for_pick,local_pipeline_components_are_complete,@@ -250,6 +254,11 @@ def _image_need(request: Any, gpu_ordinal: Optional[int]) -> Optional[tuple[int,gpu_ordinal = gpu_ordinal,gguf_filename = name,with_loras = has_active_loras(getattr(request, "loras", None)),+ # An explicit precision keeps a default-routed Apple Silicon load on diffusers, as the load does.+ mlx_blocker = mlx_load_blocker(+ transformer_quant = getattr(request, "transformer_quant", None),+ text_encoder_quant = getattr(request, "text_encoder_quant", None),+ ),)!= ENGINE_DIFFUSERS):diff --git a/studio/backend/core/inference/mlx_diffusion_backend.py b/studio/backend/core/inference/mlx_diffusion_backend.pyindex d398c061998..97a25465a78 100644--- a/studio/backend/core/inference/mlx_diffusion_backend.py+++ b/studio/backend/core/inference/mlx_diffusion_backend.py@@ -1,7 +1,7 @@# SPDX-License-Identifier: AGPL-3.0-only# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0-"""Opt-in MLX (mflux) image engine for Apple Silicon (``UNSLOTH_DIFFUSION_MLX=1``) on Studio's GGUF.+"""MLX (mflux) image engine for Apple Silicon on Studio's GGUF.Same duck-typed surface as the other image engines; selected only by ``diffusion_engine_router``."""@@ -56,6 +56,8 @@ BASE_ALLOW_PATTERNS = ("tokenizer/*","vae/*.safetensors","vae/*.json",+ "scheduler/*.json",+ "model_index.json",)_LINKED_SUBDIRS = ("text_encoder", "tokenizer", "vae")_TE_GROUP_SIZE = 64@@ -550,6 +552,7 @@ class _MlxState:dense_bits: intconvert_dir: strtimings: dict = field(default_factory = dict)+ gguf_path: Optional[str] = None@dataclass@@ -1120,6 +1123,7 @@ class MlxDiffusionBackend:dense_bits = bits,convert_dir = str(out_dir),timings = timings,+ gguf_path = str(gguf_path),)with self._lock:if self._load_token != _load_token:@@ -1278,8 +1282,8 @@ class MlxDiffusionBackend:or (upscale is not None and upscale > 1)):raise ValueError(- "The MLX engine runs text-to-image only; unset UNSLOTH_DIFFUSION_MLX for "- "img2img / inpaint / edit / reference / upscale."+ "The MLX engine runs text-to-image only; unset UNSLOTH_DIFFUSION_MLX (or set it to "+ "auto) for img2img / inpaint / edit / reference / upscale.")if prompts is not None or seeds is not None:raise ValueError(diff --git a/studio/backend/core/inference/mlx_diffusion_routing.py b/studio/backend/core/inference/mlx_diffusion_routing.pynew file mode 100644index 00000000000..8eb6440312b--- /dev/null+++ b/studio/backend/core/inference/mlx_diffusion_routing.py@@ -0,0 +1,884 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Apple Silicon routing: MLX for plain text-to-image, diffusers MPS for the rest (MLX unloads if both do not fit)."""++from __future__ import annotations++import inspect+import os+import threading+import time+from dataclasses import dataclass+from pathlib import Path+from types import SimpleNamespace+from typing import Any, Callable, Optional++from core.inference.generation_ticket import bind_generation_cancel+from loggers import get_logger+from utils.account_context import current_account_id++logger = get_logger(__name__)++ENGINE_MLX = "mlx"+ENGINE_DIFFUSERS = "diffusers"++COEXIST_ENV = "UNSLOTH_DIFFUSION_MLX_COEXIST"+_FALLBACK_DRAIN_S = 120.0+_ENABLE_TOKENS = frozenset({"1", "on", "true", "yes"})+_DISABLE_TOKENS = frozenset({"0", "off", "false", "no"})+_UNSET_TOKENS = frozenset({"", "auto", "default"})+++@dataclass(frozen = True)+class MlxCapabilities:+ workflows: tuple[str, ...] = ("txt2img",)+ loras: bool = False+ controlnet: bool = False+++_DEFAULT_CAPABILITIES = MlxCapabilities()+MLX_CAPABILITIES: dict[str, MlxCapabilities] = {"z-image": _DEFAULT_CAPABILITIES}+++def mlx_capabilities(family: Optional[str]) -> MlxCapabilities:+ return MLX_CAPABILITIES.get((family or "").lower(), _DEFAULT_CAPABILITIES)+++def _explicit(value: Any) -> bool:+ return value is not None and str(value).strip().lower() not in _UNSET_TOKENS+++def _positive(value: Any) -> bool:+ try:+ return value is not None and float(value) > 0.0+ except (TypeError, ValueError):+ return False+++def load_blocker(+ *,+ loras: Any = None,+ component_files: Any = None,+ transformer_quant: Optional[str] = None,+ text_encoder_quant: Optional[str] = None,+) -> Optional[str]:+ from core.inference.diffusion_engine_router import has_active_loras++ if has_active_loras(loras):+ return "LoRA adapters selected at load time need the diffusers engine"+ if component_files:+ return "separate text-encoder / VAE files need the diffusers engine"+ if _explicit(transformer_quant):+ return f"an explicit transformer precision ({transformer_quant}) needs the diffusers engine"+ if _explicit(text_encoder_quant):+ return (+ f"an explicit text-encoder precision ({text_encoder_quant}) needs the diffusers engine"+ )+ return None+++_IGNORED_ON_MLX = frozenset({"live_preview", "mask_blur", "inpaint_only_masked", "inpaint_padding"})+_CHECKED = frozenset(+ {+ "hires",+ "upscale_model",+ "workflow",+ "init_image",+ "mask_image",+ "reference_images",+ "reference_resolution",+ "localized_edit",+ "upscale",+ "prompts",+ "seeds",+ "loras",+ "controlnet",+ "sampler",+ "schedule_type",+ "sd_controls",+ "shift",+ "base_shift",+ "max_shift",+ }+)+++def _controls_requested(controls: Any) -> bool:+ requested = getattr(controls, "requested", None)+ try:+ return bool(requested()) if callable(requested) else False+ except Exception: # noqa: BLE001+ return True+++def request_blocker(+ kwargs: dict[str, Any],+ *,+ family: Optional[str] = None,+ mlx_params: Optional[frozenset[str]] = None,+ mlx_guidance: Optional[bool] = None,+) -> Optional[str]:+ caps = mlx_capabilities(family)+ get = kwargs.get+ if mlx_guidance is False and _positive(get("guidance")):+ # A guidance-distilled MLX variant (Z-Image-Turbo) drops CFG and the negative prompt; diffusers runs them.+ return "classifier-free guidance (and its negative prompt)"+ workflow = get("workflow")+ if workflow not in (None, "txt2img") and workflow not in caps.workflows:+ return f"the {workflow} workflow"+ if get("hires") is not None:+ return "Hires fix"+ if get("upscale_model"):+ return "a model upscaler"+ if get("mask_image") is not None:+ return "inpainting"+ if get("init_image") is not None:+ return "an input image (img2img)"+ if get("reference_images"):+ return "reference images"+ if get("reference_resolution") is not None:+ return "a reference resolution"+ if get("localized_edit") is not None:+ return "a localized edit"+ upscale = get("upscale")+ if upscale is not None and upscale > 1:+ return "upscaling"+ if get("prompts") is not None or get("seeds") is not None:+ return "per-image prompt or seed lists"+ if get("loras") and not caps.loras:+ return "LoRA adapters"+ controlnet = get("controlnet")+ if controlnet is not None and controlnet[3] not in (None, 0, 0.0) and not caps.controlnet:+ return "ControlNet"+ if get("sampler") not in (None, "default") or get("schedule_type") not in (None, "automatic"):+ return "a sampler choice"+ if get("sd_controls") is not None and _controls_requested(get("sd_controls")):+ return "prompt weighting, CLIP skip, CFG rescale or a variation seed"+ if any(get(name) is not None for name in ("shift", "base_shift", "max_shift")):+ return "a shift override"+ if mlx_params is not None:+ for name, value in kwargs.items():+ if name in mlx_params or name in _IGNORED_ON_MLX or name in _CHECKED:+ continue+ if value not in (None, False, [], ()):+ return f"the {name} option"+ return None+++@dataclass(frozen = True)+class Route:+ engine: str+ reason: str+ load_diffusers: bool = False+ unload_mlx: bool = False+++def decide_route(+ *,+ blocker: Optional[str],+ mlx_resident: bool,+ diffusers_resident: bool,+ fallback_available: bool,+ coexist: bool,+) -> Route:+ if blocker is None:+ if mlx_resident:+ return Route(ENGINE_MLX, "text-to-image runs on MLX")+ if diffusers_resident:+ return Route(+ ENGINE_DIFFUSERS,+ "MLX was unloaded to make room for diffusers; load the model again to return to MLX",+ )+ return Route(ENGINE_MLX, "no model resident")+ if diffusers_resident:+ return Route(ENGINE_DIFFUSERS, f"{blocker} runs on diffusers")+ if not fallback_available or not mlx_resident:+ return Route(ENGINE_MLX, f"{blocker} has no diffusers fallback here")+ return Route(+ ENGINE_DIFFUSERS,+ f"{blocker} runs on diffusers",+ load_diffusers = True,+ unload_mlx = not coexist,+ )+++def engines_coexist(mlx_bytes: int, diffusers_bytes: int, budget_bytes: int) -> bool:+ raw = os.environ.get(COEXIST_ENV, "auto").strip().lower()+ if raw in _ENABLE_TOKENS:+ return True+ if raw in _DISABLE_TOKENS:+ return False+ if mlx_bytes <= 0 or diffusers_bytes <= 0 or budget_bytes <= 0:+ return False+ return mlx_bytes + diffusers_bytes <= budget_bytes+++def diffusers_resident_bytes(gguf_path: Optional[str], components_dir: Optional[str]) -> int:+ if not gguf_path or not components_dir:+ return 0+ try:+ from core.inference.mlx_diffusion_backend import _safetensors_numel+ root = Path(components_dir)+ return (+ os.path.getsize(gguf_path)+ + 2 * _safetensors_numel(root / "text_encoder")+ + 2 * _safetensors_numel(root / "vae")+ )+ except Exception as exc: # noqa: BLE001+ logger.info("mlx_routing.diffusers_size_unknown: %s", exc)+ return 0+++def _default_mlx() -> Any:+ from core.inference.mlx_diffusion_backend import get_mlx_diffusion_backend+ return get_mlx_diffusion_backend()+++def _default_diffusers() -> Any:+ from core.inference.diffusion import get_diffusion_backend+ return get_diffusion_backend()+++def _default_budget() -> int:+ from core.inference.mlx_diffusion_backend import working_set_bytes+ return working_set_bytes()+++def _diffusers_capabilities(family: Any) -> dict[str, Any]:+ from core.inference import diffusion as diffusers_module+ from core.inference.diffusion_conditioning import conditioning_capabilities++ workflows = diffusers_module._family_workflows(family)+ return {+ "workflows": workflows,+ "conditioning": conditioning_capabilities(family, workflows),+ **diffusers_module._hires_status(family),+ # A request with guidance routes to diffusers when MLX drops CFG, so the Images page offers its controls.+ "supports_guidance": bool(getattr(family, "uses_guidance", False)),+ "supports_negative_prompt": bool(getattr(family, "uses_negative_prompt", False)),+ "negative_prompt_min_guidance": diffusers_module._negative_prompt_guidance_threshold(+ family+ ),+ }+++_SCHEDULER_CONFIG = "scheduler/scheduler_config.json"+++def _cached_base_file(base: str, filename: str) -> Optional[Path]:+ local = Path(base).expanduser()+ if local.is_dir():+ candidate = local / filename+ return candidate if candidate.is_file() else None+ from huggingface_hub import constants, try_to_load_from_cache++ from core.inference.diffusion_families import (+ mirror_repo,+ pinned_revision_kwargs,+ prefer_ungated_mirror,+ )+ from utils.hf_cache_settings import active_hf_hub_cache++ repos = (prefer_ungated_mirror(base), base, mirror_repo(base))+ for repo in dict.fromkeys(r for r in repos if r):+ revision = pinned_revision_kwargs(repo).get("revision")+ for cache_dir in dict.fromkeys((active_hf_hub_cache(), constants.HF_HUB_CACHE)):+ hit = try_to_load_from_cache(repo, filename, cache_dir = cache_dir, revision = revision)+ if isinstance(hit, str):+ return Path(hit)+ return None+++def fallback_shift_control(family: Any, status: dict[str, Any]) -> Optional[dict]:+ import json++ from core.inference.diffusion_content import content_variant_hint+ from core.inference.diffusion_families import comfy_flow_shift_for, comfy_shift_node_for+ from core.inference.diffusion_flow_shift import (+ SAMPLE_SIGMAS_KEY,+ apply_comfy_flow_shift,+ shift_control,+ valid_sample_sigmas,+ )++ repo_id, gguf_filename = status.get("repo_id"), status.get("gguf_filename")+ display_repo_id, base = status.get("display_repo_id"), status.get("base_repo")+ node = comfy_shift_node_for(family, gguf_filename, repo_id, display_repo_id, base)+ if node is None or not base:+ return None+ index_path = _cached_base_file(base, "model_index.json")+ if index_path is not None:+ index = json.loads(index_path.read_text(encoding = "utf-8"))+ if isinstance(index, dict) and valid_sample_sigmas(index.get(SAMPLE_SIGMAS_KEY)):+ return None+ config_path = _cached_base_file(base, _SCHEDULER_CONFIG)+ if config_path is None:+ return None+ config = json.loads(config_path.read_text(encoding = "utf-8"))+ import diffusers++ scheduler_cls = getattr(diffusers, str(config.get("_class_name") or ""), None)+ if scheduler_cls is None:+ return None+ pipe = SimpleNamespace(scheduler = scheduler_cls.from_config(config))+ apply_comfy_flow_shift(+ pipe,+ comfy_flow_shift_for(+ family,+ gguf_filename,+ content_variant_hint(repo_id, gguf_filename),+ repo_id,+ display_repo_id,+ base,+ ),+ )+ return shift_control(node, pipe.scheduler)+++_GUIDANCE_KEYS = ("supports_guidance", "supports_negative_prompt", "negative_prompt_min_guidance")+++def _parameters(fn: Any) -> dict[str, inspect.Parameter]:+ try:+ return dict(inspect.signature(fn).parameters)+ except (TypeError, ValueError):+ return {}+++def _identity_of(engine: Any) -> Any:+ from core.inference.diffusion_families import load_identity++ try:+ status = engine.status()+ except Exception: # noqa: BLE001+ return None+ if not status.get("loaded"):+ return None+ return load_identity(status.get("repo_id"), status.get("base_repo"), status.get("family"))+++class _RoutedGenerate:+ def __init__(self, owner: "RoutedMlxEngine") -> None:+ self.__self__ = owner++ @property+ def __signature__(self) -> inspect.Signature:+ owner = self.__self__+ params: dict[str, inspect.Parameter] = {}+ try:+ params.update(_parameters(owner._diffusers().generate))+ except Exception: # noqa: BLE001+ pass+ for name, param in _parameters(owner._mlx().generate).items():+ params.setdefault(name, param)+ ordered = [p for p in params.values() if p.kind is not inspect.Parameter.VAR_KEYWORD]+ return inspect.Signature([p.replace(kind = inspect.Parameter.KEYWORD_ONLY) for p in ordered])++ def __call__(self, **kwargs: Any) -> dict[str, Any]:+ return self.__self__._generate(**kwargs)+++class RoutedMlxEngine:+ runs_off_torch_device = False+ parses_prompt_attention = False++ def __init__(+ self,+ mlx_factory: Optional[Callable[[], Any]] = None,+ diffusers_factory: Optional[Callable[[], Any]] = None,+ budget_fn: Optional[Callable[[], int]] = None,+ capabilities_fn: Optional[Callable[[Any], dict[str, Any]]] = None,+ poll_s: float = 0.25,+ ) -> None:+ self._mlx_factory = mlx_factory or _default_mlx+ self._diffusers_factory = diffusers_factory or _default_diffusers+ self._budget_fn = budget_fn or _default_budget+ self._capabilities_fn = capabilities_fn or _diffusers_capabilities+ self._poll_s = poll_s+ self._route_lock = threading.Lock()+ self._lock = threading.Lock()+ self._load_kwargs: Optional[dict[str, Any]] = None+ self._epoch = 0+ # Replacement loads between their first epoch bump and registering their options: no fallback registers.+ self._replacing = 0+ self._diffusers_ours = False+ self._mlx_dropped = False+ self._origin_identity: Any = None+ self._coexist: Optional[bool] = None+ self._serving: Optional[str] = None+ self._last: Optional[dict[str, Any]] = None+ self._fallback_cancel: Optional[threading.Event] = None+ self._fallback_done: Optional[threading.Event] = None+ self._active_generate_account: Optional[str] = None+ self.generate = _RoutedGenerate(self)++ def _mlx(self) -> Any:+ return self._mlx_factory()++ def _diffusers(self) -> Any:+ return self._diffusers_factory()++ def _diffusers_resident(self) -> bool:+ return self._diffusers_ours and getattr(self._diffusers(), "_state", None) is not None++ def _mlx_resident(self) -> bool:+ return getattr(self._mlx(), "_state", None) is not None++ def _primary(self) -> Any:+ return self._diffusers() if self._diffusers_resident() else self._mlx()++ @property+ def _state(self) -> Any:+ return getattr(self._primary(), "_state", None)++ @property+ def is_loaded(self) -> bool:+ return self._state is not None++ def __getattr__(self, name: str) -> Any:+ if name.startswith("__") or name in (+ "_mlx_factory",+ "_diffusers_factory",+ "_lock",+ "_diffusers_ours",+ ):+ raise AttributeError(name)+ return getattr(self._primary(), name)++ def _family(self) -> Any:+ state = getattr(self._mlx(), "_state", None)+ if state is not None:+ return getattr(state, "family", None)+ state = getattr(self._diffusers(), "_state", None) if self._diffusers_ours else None+ return getattr(state, "family", None)++ def _fallback_available(self, family: Any) -> bool:+ if self._load_kwargs is None or family is None:+ return False+ try:+ from core.inference.diffusion_families import family_pipeline_available+ return bool(family_pipeline_available(family))+ except Exception: # noqa: BLE001+ return False++ def _engines_fit_together(self) -> bool:+ state = getattr(self._mlx(), "_state", None)+ if state is None:+ return False+ plan = (getattr(state, "timings", None) or {}).get("quant_plan") or {}+ mlx_bytes = int(plan.get("planned_bytes") or 0)+ diffusers_bytes = diffusers_resident_bytes(+ getattr(state, "gguf_path", None), getattr(state, "convert_dir", None)+ )+ try:+ budget = int(self._budget_fn() or 0)+ except Exception: # noqa: BLE001+ budget = 0+ fits = engines_coexist(mlx_bytes, diffusers_bytes, budget)+ logger.info(+ "mlx_routing.coexist: mlx=%.2f GiB diffusers=%.2f GiB budget=%.2f GiB -> %s",+ mlx_bytes / 1024**3,+ diffusers_bytes / 1024**3,+ budget / 1024**3,+ fits,+ )+ return fits++ def _drain_fallback(self, *, replacing: bool = False) -> bool:+ with self._lock:+ self._epoch += 1+ if replacing:+ self._replacing += 1+ cancel = self._fallback_cancel+ done = self._fallback_done+ if cancel is not None:+ cancel.set()+ if done is not None and not done.wait(_FALLBACK_DRAIN_S):+ logger.warning("mlx_routing.fallback_drain_timeout: %.0fs", _FALLBACK_DRAIN_S)+ with self._lock:+ return self._diffusers_ours++ def begin_load(self, repo_id: str, **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:+ if ours:+ self._diffusers().unload()+ with self._lock:+ self._diffusers_ours = False+ self._mlx_dropped = False+ self._origin_identity = None+ self._coexist = None+ self._last = None+ self._mlx().begin_load(repo_id, **kwargs)+ with self._lock:+ self._load_kwargs = {"repo_id": repo_id, **kwargs}+ finally:+ with self._lock:+ # A second bump: a route decided inside the fence holds a stale epoch once it lifts.+ self._epoch += 1+ self._replacing -= 1+ return self.status()++ def _diffusers_load_kwargs(self) -> dict[str, Any]:+ kwargs = dict(self._load_kwargs or {})+ accepted = _parameters(self._diffusers().begin_load)+ if not any(p.kind is inspect.Parameter.VAR_KEYWORD for p in accepted.values()):+ kwargs = {k: v for k, v in kwargs.items() if k in accepted}+ return kwargs++ def _load_fallback(self, *, unload_mlx: bool, epoch: int) -> Any:+ from core.inference.diffusion_families import DIFFUSION_CANCELLED_MSG+ from core.inference.diffusion_memory import (+ UNIFIED_OVERSIZE_REFUSAL_CODE,+ UnifiedMemoryShortfallError,+ )++ mlx, diffusers = self._mlx(), self._diffusers()+ cancel, done = threading.Event(), threading.Event()+ # Epoch check and registration are atomic: a new load drains this fallback, or this request sees the new epoch.+ with self._lock:+ if self._epoch != epoch or self._replacing:+ raise RuntimeError(DIFFUSION_CANCELLED_MSG)+ self._fallback_cancel = cancel+ self._fallback_done = done+ self._active_generate_account = current_account_id()+ bind_generation_cancel(cancel)+ dropped = False+ started = time.perf_counter()+ try:+ kwargs = self._diffusers_load_kwargs()+ 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+ 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+ while True:+ if cancel.is_set() or self._epoch != epoch:+ diffusers.unload()+ raise RuntimeError(DIFFUSION_CANCELLED_MSG)+ progress = diffusers.load_progress() or {}+ phase = progress.get("phase")+ if phase == "ready" and getattr(diffusers, "_state", None) is not None:+ break+ if phase == "error":+ message = (+ "Could not load the diffusers engine this request needs: "+ f"{progress.get('error') or 'unknown error'}"+ )+ if progress.get("error_code") == UNIFIED_OVERSIZE_REFUSAL_CODE:+ raise UnifiedMemoryShortfallError(message)+ raise RuntimeError(message)+ if phase is None:+ diffusers.unload()+ raise RuntimeError(DIFFUSION_CANCELLED_MSG)+ time.sleep(self._poll_s)+ identity = _identity_of(diffusers)+ if cancel.is_set() or self._epoch != epoch:+ diffusers.unload()+ raise RuntimeError(DIFFUSION_CANCELLED_MSG)+ logger.info(+ "mlx_routing.fallback_loaded: diffusers in %.1fs (mlx unloaded first: %s)",+ time.perf_counter() - started,+ dropped,+ )+ return identity+ except BaseException:+ with self._lock:+ self._diffusers_ours = False+ restore = dropped and self._epoch == epoch and self._load_kwargs is not None+ if restore:+ self._mlx_dropped = False+ if restore:+ try:+ restore_kwargs = dict(self._load_kwargs or {})+ mlx.begin_load(restore_kwargs.pop("repo_id"), **restore_kwargs)+ except Exception as exc: # noqa: BLE001+ logger.warning("mlx_routing.restore_failed: %s", exc)+ raise+ finally:+ with self._lock:+ if self._fallback_cancel is cancel:+ self._fallback_cancel = None+ self._fallback_done = None+ self._active_generate_account = None+ done.set()++ def _mlx_guidance(self) -> Optional[bool]:+ try:+ value = self._mlx().status().get("supports_guidance")+ except Exception: # noqa: BLE001+ return None+ return None if value is None else bool(value)++ def _identity_snapshot(self) -> dict[str, Any]:+ out: dict[str, Any] = {}+ if self._mlx_resident():+ out[ENGINE_MLX] = _identity_of(self._mlx())+ if self._diffusers_resident():+ out[ENGINE_DIFFUSERS] = _identity_of(self._diffusers())+ return {k: v for k, v in out.items() if v is not None}++ def _accepted_identities(self, snapshot: Optional[dict[str, Any]] = None) -> list[Any]:+ ids = list((self._identity_snapshot() if snapshot is None else snapshot).values())+ if self._origin_identity is not None and ids:+ ids.append(self._origin_identity)+ return ids++ def _generate(self, **kwargs: Any) -> dict[str, Any]:+ from core.inference.diffusion_families import (+ DIFFUSION_NOT_LOADED_MSG,+ DiffusionModelReplacedError,+ )+ expected = kwargs.pop("expected_load", None)+ with self._route_lock:+ with self._lock:+ epoch = self._epoch+ mlx, diffusers = self._mlx(), self._diffusers()+ mlx_params = frozenset(_parameters(mlx.generate))+ family = self._family()+ mlx_resident = self._mlx_resident()+ blocker = request_blocker(+ kwargs,+ family = getattr(family, "name", None),+ mlx_params = mlx_params,+ mlx_guidance = self._mlx_guidance() if mlx_resident else None,+ )+ diffusers_resident = self._diffusers_resident()+ fallback_available = self._fallback_available(family)+ coexist = False+ if blocker and mlx_resident and not diffusers_resident and fallback_available:+ coexist = self._engines_fit_together()+ self._coexist = coexist+ route = decide_route(+ blocker = blocker,+ mlx_resident = mlx_resident,+ diffusers_resident = diffusers_resident,+ fallback_available = fallback_available,+ coexist = coexist,+ )+ if blocker and route.engine == ENGINE_MLX and not mlx_resident:+ raise RuntimeError(DIFFUSION_NOT_LOADED_MSG)+ snapshot: dict[str, Any] = {}+ if expected is not None:+ snapshot = self._identity_snapshot()+ accepted = self._accepted_identities(snapshot)+ if accepted and expected not in accepted:+ raise DiffusionModelReplacedError(expected, accepted[0])+ if route.load_diffusers and (mlx.load_progress() or {}).get("phase") != "ready":+ raise RuntimeError(+ "A diffusion load is in progress; retry once it finishes or load the model again."+ )+ if blocker and route.engine == ENGINE_MLX and mlx_resident:+ mlx_call = {k: v for k, v in kwargs.items() if k in mlx_params}+ if request_blocker(mlx_call, family = getattr(family, "name", None)) is None:+ raise ValueError(+ f"{blocker[0].upper()}{blocker[1:]} is not supported on the MLX engine, and "+ "this install has no diffusers pipeline for the model to fall back to."+ )+ own = snapshot.get(route.engine, expected) if expected is not None else None+ if route.load_diffusers:+ logger.info("mlx_routing.fallback: %s", route.reason)+ fallback_identity = self._load_fallback(unload_mlx = route.unload_mlx, epoch = epoch)+ if expected is not None:+ own = fallback_identity or expected+ engine = diffusers if route.engine == ENGINE_DIFFUSERS else mlx+ if route.engine == ENGINE_DIFFUSERS:+ call = kwargs+ else:+ call = {k: v for k, v in kwargs.items() if k in mlx_params}+ with self._lock:+ self._serving = route.engine+ try:+ result = engine.generate(expected_load = own, **call)+ finally:+ with self._lock:+ self._serving = None+ out = dict(result)+ out["engine"] = route.engine+ with self._lock:+ self._last = {"served_by": route.engine, "reason": route.reason}+ return out++ def generate_progress(self) -> dict[str, Any]:+ if self._fallback_cancel is not None:+ return {+ "active": True,+ "step": 0,+ "total_steps": 0,+ "fraction": 0.0,+ "eta_seconds": None,+ "phase": None,+ }+ if self._serving == ENGINE_DIFFUSERS:+ return self._diffusers().generate_progress()+ if self._serving == ENGINE_MLX:+ return self._mlx().generate_progress()+ return self._primary().generate_progress()++ def cancel_generate(self, expected_account: Optional[str] = None) -> bool:+ with self._lock:+ cancel = self._fallback_cancel+ owner = self._active_generate_account+ if cancel is not None:+ if expected_account is not None and owner not in (None, expected_account):+ return False+ cancel.set()+ return True+ if self._serving == ENGINE_DIFFUSERS:+ return self._diffusers().cancel_generate(expected_account = expected_account)+ return self._mlx().cancel_generate(expected_account = expected_account)++ def unload(self, *, expected_account: Optional[str] = None) -> dict[str, Any]:+ # Drain the fallback first and stay fenced until teardown ends, so none reloads MLX or registers meanwhile.+ if expected_account is not None:+ with self._lock:+ foreign = (+ self._fallback_cancel is not None+ and self._active_generate_account+ not in (+ None,+ expected_account,+ )+ )+ if foreign:+ # Refused before the drain: draining cancels the other account's in-flight fallback.+ from core.inference.gpu_arbiter import DIFFUSION, GpuBusyForAnotherAccountError+ raise GpuBusyForAnotherAccountError(DIFFUSION, 1)+ ours = self._drain_fallback(replacing = True)+ try:+ if expected_account is None:+ self._mlx().unload()+ else:+ self._mlx().unload(expected_account = expected_account)+ if ours:+ if expected_account is None:+ self._diffusers().unload()+ else:+ self._diffusers().unload(expected_account = expected_account)+ with self._lock:+ self._diffusers_ours = False+ self._mlx_dropped = False+ self._origin_identity = None+ self._coexist = None+ self._load_kwargs = None+ finally:+ with self._lock:+ self._epoch += 1+ self._replacing -= 1+ return self.status()++ def load_progress(self) -> dict[str, Any]:+ if self._fallback_cancel is not None or self._diffusers_resident():+ return self._diffusers().load_progress()+ return self._mlx().load_progress()++ def _repo_ids(self, method: str) -> tuple[str, ...]:+ engines = [self._mlx()]+ if self._diffusers_ours:+ engines.append(self._diffusers())+ out: list[str] = []+ for engine in engines:+ fn = getattr(engine, method, None)+ if callable(fn):+ out.extend(fn())+ return tuple(dict.fromkeys(out))++ def loading_repo_ids(self) -> tuple[str, ...]:+ return self._repo_ids("loading_repo_ids")++ def draining_repo_ids(self) -> tuple[str, ...]:+ return self._repo_ids("draining_repo_ids")++ def loaded_repo_ids(self) -> tuple[str, ...]:+ return self._repo_ids("loaded_repo_ids")++ def download_plan(self, repo_id: str, **kwargs: Any) -> dict[str, Any]:+ return self._mlx().download_plan(repo_id, **kwargs)++ def preflight_base_access(self, *args: Any, **kwargs: Any) -> Any:+ return self._mlx().preflight_base_access(*args, **kwargs)++ def _fallback_capabilities(self, family: Any) -> dict[str, Any]:+ if not self._fallback_available(family):+ return {}+ try:+ return dict(self._capabilities_fn(family))+ except Exception as exc: # noqa: BLE001+ logger.info("mlx_routing.capabilities_unavailable: %s", exc)+ return {}++ def _fallback_shift_control(self, family: Any, status: dict[str, Any]) -> Optional[dict]:+ if not self._fallback_available(family):+ return None+ try:+ return fallback_shift_control(family, status)+ except Exception as exc: # noqa: BLE001+ logger.info("mlx_routing.shift_control_unavailable: %s", exc)+ return None++ def routing_status(self) -> dict[str, Any]:+ resident = [+ name+ for name, here in (+ (ENGINE_MLX, self._mlx_resident()),+ (ENGINE_DIFFUSERS, self._diffusers_resident()),+ )+ if here+ ]+ with self._lock:+ last = dict(self._last) if self._last else None+ dropped = self._mlx_dropped+ coexist = self._coexist+ return {+ "mode": "auto",+ "default_engine": ENGINE_MLX,+ "resident": resident,+ "txt2img_engine": ENGINE_DIFFUSERS+ if dropped and not self._mlx_resident()+ else ENGINE_MLX,+ "engines_fit_together": coexist,+ "last_served_by": last["served_by"] if last else None,+ "last_reason": last["reason"] if last else None,+ }++ def status(self) -> dict[str, Any]:+ if self._diffusers_resident():+ out = dict(self._diffusers().status())+ else:+ out = dict(self._mlx().status())+ if out.get("loaded"):+ family = self._family()+ caps = self._fallback_capabilities(family)+ if out.get("supports_guidance"):+ for key in _GUIDANCE_KEYS:+ caps.pop(key, None)+ out.update(caps)+ if out.get("shift_control") is None:+ shift = self._fallback_shift_control(family, out)+ if shift is not None:+ out["shift_control"] = shift+ out["engine_routing"] = self.routing_status()+ return out+++_routed_mlx_engine: Optional[RoutedMlxEngine] = None+_singleton_lock = threading.Lock()+++def get_routed_mlx_engine() -> RoutedMlxEngine:+ global _routed_mlx_engine+ with _singleton_lock:+ if _routed_mlx_engine is None:+ _routed_mlx_engine = RoutedMlxEngine()+ return _routed_mlx_enginediff --git a/studio/backend/models/inference.py b/studio/backend/models/inference.pyindex df1172a1a01..efd4fac7356 100644--- a/studio/backend/models/inference.py+++ b/studio/backend/models/inference.py@@ -6008,8 +6008,14 @@ class DiffusionStatusResponse(BaseModel):)mlx_fallback_reason: Optional[str] = Field(None,- description = "Why UNSLOTH_DIFFUSION_MLX=1 did not get the MLX engine on the last load (null when "- "MLX was not requested or is in use)",+ description = "Why an Apple Silicon load did not get the MLX engine (null when MLX is off, the host is "+ "not an Apple Silicon Mac, or MLX is in use)",+ )+ engine_routing: Optional[dict[str, Any]] = Field(+ None,+ description = "Per-request routing of the default Apple Silicon MLX engine: mode, default_engine, resident "+ "engines, txt2img_engine (where plain text-to-image runs next), engines_fit_together, last_served_by and "+ "last_reason. Null for every other engine.",)engine_forced: Optional[str] = Field(None,diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.pyindex 4eef1eeaff8..db794cbdbe8 100644--- a/studio/backend/routes/inference.py+++ b/studio/backend/routes/inference.py@@ -51535,6 +51535,16 @@ def _refuse_native_component_files(request: DiffusionLoadRequest) -> None:)+def _mlx_load_blocker(request: DiffusionLoadRequest) -> Optional[str]:+ from core.inference.diffusion_engine_router import mlx_load_blocker+ return mlx_load_blocker(+ loras = request.loras,+ component_files = _component_file_kwargs(request),+ transformer_quant = request.transformer_quant,+ text_encoder_quant = request.text_encoder_quant,+ )++def _has_active_loras(loras: Any) -> bool:from core.inference.diffusion_engine_router import has_active_lorasreturn has_active_loras(loras)@@ -51652,6 +51662,7 @@ async def diffusion_download_plan(gguf_filename = request.gguf_filename,engine = request.engine,with_loras = _has_active_loras(request.loras),+ mlx_blocker = _mlx_load_blocker(request),)if fam is not Noneelse None@@ -51661,7 +51672,6 @@ async def diffusion_download_plan(from core.inference.sd_cpp_backend import get_sd_cpp_backendplanner = get_sd_cpp_backend()elif predicted == ENGINE_MLX:- # Opt-in MLX engine (UNSLOTH_DIFFUSION_MLX=1): same single-GGUF contract as native._refuse_native_component_files(request)_refuse_mlx_loras(request)from core.inference.mlx_diffusion_backend import get_mlx_diffusion_backend@@ -51978,6 +51988,7 @@ async def load_diffusion_model_gated(gguf_filename = request.gguf_filename,engine = request.engine,with_loras = _has_active_loras(request.loras),+ mlx_blocker = _mlx_load_blocker(request),)if fam is not Noneelse None@@ -52123,6 +52134,8 @@ async def load_diffusion_model_gated(# The load's own engine pick (auto when absent); refused there rather than swapped.engine = request.engine,with_loras = _has_active_loras(request.loras),+ # A load option the MLX engine cannot honour keeps an auto-routed Apple Silicon load on diffusers.+ mlx_blocker = _mlx_load_blocker(request),),)# predict_engine is selection's read-only twin: it never installs, so a host whose sd-cli@@ -52788,6 +52801,7 @@ async def _generate_diffusion_image_run(IMAGE_REFUSAL_HEADER,IMAGE_REFUSAL_MEMORY_ESTIMATE,ImageActivationShortfallError,+ unified_memory_refusal_code,)backend = get_active_diffusion_engine()@@ -52925,6 +52939,13 @@ async def _generate_diffusion_image_run(msg = str(exc)if msg in (DIFFUSION_NOT_LOADED_MSG, DIFFUSION_CANCELLED_MSG):raise HTTPException(status_code = 409, detail = msg)+ refusal = unified_memory_refusal_code(exc)+ if refusal is not None:+ raise HTTPException(+ status_code = 400,+ detail = msg,+ headers = {IMAGE_REFUSAL_HEADER: refusal},+ )logger.error("diffusion.generate_failed: %s", exc, exc_info = True)raise HTTPException(status_code = 500, detail = _generate_failure_detail(msg))except Exception as exc:@@ -52987,6 +53008,7 @@ async def _generate_diffusion_image_run(# The batch shares one seed, so reproducing a batch_index>0 image needs the original batch_size."batch_size": 1 if list_driven else request.batch_size,"model": result.get("repo_id"),+ **({"engine": result["engine"]} if result.get("engine") else {}),# The BUILD the image came off, not just the repo id: a GGUF repo holds many quants, a dense load may be torchao-# quantised, and a bake is not the same build as the adapter-less one. Absent on records written before this existed."model_kind": result.get("model_kind"),@@ -54751,6 +54773,7 @@ async def _generate_openai_images(want_b64 = body.response_format == "b64_json"# Persist each image with its full recipe, like /images/generate, so url links resolve and images show in the gallery.recipe = {+ **({"engine": result["engine"]} if result.get("engine") else {}),"prompt": body.prompt,"negative_prompt": result.get("negative_prompt"),"width": width,diff --git a/studio/backend/tests/test_diffusion_mlx_engine_router.py b/studio/backend/tests/test_diffusion_mlx_engine_router.pyindex 00a7926ec79..861298319b1 100644--- a/studio/backend/tests/test_diffusion_mlx_engine_router.py+++ b/studio/backend/tests/test_diffusion_mlx_engine_router.py@@ -1,7 +1,7 @@# SPDX-License-Identifier: AGPL-3.0-only# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0-"""Router matrix for the opt-in MLX image engine: defaults unchanged, refusals fall back, predict == select."""+"""Router matrix for the Apple Silicon MLX image engine."""from __future__ import annotations@@ -162,14 +162,111 @@ def test_opt_in_on_the_mps_less_cpu_backend_still_picks_mlx(monkeypatch):assert _predict() == _select() == ENGINE_MLX-# ── default unchanged: unset / 0 / auto never consult MLX ────────────────────[email protected]("value", [None, "", "auto", "AUTO"])+def test_default_and_auto_pick_mlx_on_apple_silicon(monkeypatch, value):+ _apple(monkeypatch)+ if value is not None:+ monkeypatch.setenv("UNSLOTH_DIFFUSION_MLX", value)+ assert _predict() == ENGINE_MLX+ assert _select() == ENGINE_MLX+ status = r.annotate_status({"loaded": False})+ assert status["engine"] == ENGINE_MLX+ assert status["mlx_fallback_reason"] is None++[email protected]("value", [None, "auto"])+ "host",+ [+ {"system": "linux", "machine": "x86_64"},+ {"system": "win32", "machine": "AMD64"},+ {"system": "darwin", "machine": "x86_64"},+ {"system": "darwin", "machine": "arm64", "macos": "13.6"},+ ],+)+def test_auto_on_other_hosts_is_todays_engine_and_records_nothing(monkeypatch, value, host):+ _host(monkeypatch, **host)+ _device(monkeypatch, "cpu")++ def _no_probe(*_a, **_k):+ raise AssertionError("auto must not probe the MLX runtime off Apple Silicon")++ monkeypatch.setattr(r, "_mlx_runtime_refusal", _no_probe)+ if value is not None:+ monkeypatch.setenv("UNSLOTH_DIFFUSION_MLX", value)+ assert _predict() == _select() == ENGINE_DIFFUSERS+ assert r.annotate_status({})["mlx_fallback_reason"] is None+++ "blocker_kwargs, needle",+ [+ ({"loras": [("some/lora", 1.0)]}, "LoRA"),+ ({"component_files": {"vae_file": "vae.safetensors"}}, "text-encoder / VAE"),+ ({"transformer_quant": "int8"}, "transformer precision (int8)"),+ ({"text_encoder_quant": "fp8"}, "text-encoder precision (fp8)"),+ ],+)+def test_auto_keeps_a_load_mlx_cannot_honour_on_diffusers(monkeypatch, blocker_kwargs, needle):+ _apple(monkeypatch)+ blocker = r.mlx_load_blocker(**blocker_kwargs)+ assert needle in blocker+ fam = detect_family("z-image")+ assert (+ r.predict_engine(fam, model_kind = "gguf", gguf_filename = _Q4, mlx_blocker = blocker)+ == ENGINE_DIFFUSERS+ )+ r.select_and_activate_engine(fam, model_kind = "gguf", gguf_filename = _Q4, mlx_blocker = blocker)+ assert r.active_engine_name() == ENGINE_DIFFUSERS+ assert needle in (r.annotate_status({})["mlx_fallback_reason"] or "")+ monkeypatch.setenv("UNSLOTH_DIFFUSION_MLX", "1")+ assert (+ r.predict_engine(fam, model_kind = "gguf", gguf_filename = _Q4, mlx_blocker = blocker)+ == ENGINE_MLX+ )[email protected]("value", [None, "0", "off", "auto", "AUTO", "garbage"])-def test_default_and_auto_keep_todays_engine(monkeypatch, value):[email protected]("value", [None, "auto", "1"])+def test_native_lora_pick_on_a_mac_is_never_an_mlx_refusal(monkeypatch, value):_apple(monkeypatch)if value is not None:monkeypatch.setenv("UNSLOTH_DIFFUSION_MLX", value)+ monkeypatch.setattr(r, "ensure_sd_cpp_binary", lambda **_: "/usr/bin/sd-cli")+ monkeypatch.setattr(r, "SdCppEngine", lambda **_: SimpleNamespace(version = lambda: "v0"))+ blocker = r.mlx_load_blocker(loras = [("some/lora", 1.0)])+ fam = detect_family("z-image")+ use_mlx, reason = r.mlx_selection(+ fam, model_kind = "gguf", gguf_filename = _Q4, engine = ENGINE_SD_CPP, load_blocker = blocker+ )+ assert use_mlx is False+ assert "sd_cpp" in reason+ assert (+ r.predict_engine(+ fam,+ model_kind = "gguf",+ gguf_filename = _Q4,+ engine = ENGINE_SD_CPP,+ mlx_blocker = blocker,+ )+ == ENGINE_SD_CPP+ )+++def test_delegating_precisions_do_not_block_mlx():+ for quant in (None, "", "auto", "AUTO"):+ assert r.mlx_load_blocker(transformer_quant = quant, text_encoder_quant = quant) is None+++def test_pinned_original_precisions_block_mlx():+ for quant in ("none", "off"):+ assert r.mlx_load_blocker(transformer_quant = quant) is not None+ assert r.mlx_load_blocker(text_encoder_quant = quant) is not None++[email protected]("value", ["0", "off", "false", "no", "garbage"])+def test_kill_switch_keeps_todays_engine(monkeypatch, value):+ _apple(monkeypatch)+ monkeypatch.setenv("UNSLOTH_DIFFUSION_MLX", value)def _no_probe(*_a, **_k):raise AssertionError("MLX must not be probed when it was not asked for")@@ -184,9 +281,12 @@ def test_default_and_auto_keep_todays_engine(monkeypatch, value):assert status["fallback_reason"] == "GPU backend 'mps' uses diffusers"-def test_default_keeps_sd_cpp_where_sd_cpp_is_chosen_today(monkeypatch):[email protected]("runtime", [False, True])+def test_default_keeps_sd_cpp_where_sd_cpp_is_chosen_today(monkeypatch, runtime):_host(monkeypatch)_device(monkeypatch, "mps")+ if runtime:+ _runtime(monkeypatch)monkeypatch.setenv("UNSLOTH_DIFFUSION_SD_CPP_MPS", "1")monkeypatch.setattr(r, "ensure_sd_cpp_binary", lambda **_: "/usr/bin/sd-cli")monkeypatch.setattr(r, "SdCppEngine", lambda **_: SimpleNamespace(version = lambda: "v0"))@@ -351,21 +451,49 @@ def test_predict_matches_selection(monkeypatch, env, backend, gguf, fam):r._active_engine_name = ENGINE_DIFFUSERSassert _select(fam, gguf) == predictedconvertible = gguf in (_Q4, "z-image-turbo-Q4_K_M.gguf")- expect_mlx = env == "1" and backend != "cuda" and convertible and fam == "z-image"+ expect_mlx = (+ env in (None, "auto", "1") and backend != "cuda" and convertible and fam == "z-image"+ )assert (predicted == ENGINE_MLX) is expect_mlx# ── engine plumbing ──────────────────────────────────────────────────────────-def test_engine_for_mlx_is_the_mlx_singleton():+def test_engine_for_forced_mlx_is_the_mlx_singleton(monkeypatch):from core.inference import mlx_diffusion_backend as mb+ monkeypatch.setenv("UNSLOTH_DIFFUSION_MLX", "1")engine = r.engine_for(ENGINE_MLX)assert isinstance(engine, mb.MlxDiffusionBackend)assert engine is mb.get_mlx_diffusion_backend()[email protected]("value", [None, "auto"])+def test_engine_for_auto_mlx_is_the_routed_singleton(monkeypatch, value):+ from core.inference import mlx_diffusion_routing as routing++ if value is not None:+ monkeypatch.setenv("UNSLOTH_DIFFUSION_MLX", value)+ engine = r.engine_for(ENGINE_MLX)+ assert isinstance(engine, routing.RoutedMlxEngine)+ assert engine is routing.get_routed_mlx_engine()+++def test_cancel_scans_the_routed_engine_while_it_loads_its_fallback(monkeypatch):+ from core.inference import mlx_diffusion_routing as routing++ calls = []+ fake = SimpleNamespace(+ _active_generate_account = "acct",+ cancel_generate = lambda expected_account = None: calls.append(expected_account) or True,+ )+ monkeypatch.setattr(routing, "_routed_mlx_engine", fake)+ assert r.cancel_generation_for_account("acct") is True+ assert calls == ["acct"]+ assert r.cancel_generation_for_account("someone-else") is False++def test_cancel_and_retire_scan_the_mlx_singleton(monkeypatch):from core.inference import mlx_diffusion_backend as mb@@ -393,6 +521,7 @@ def test_switching_away_from_mlx_unloads_it(monkeypatch):r._active_engine_name = ENGINE_MLX_host(monkeypatch)_device(monkeypatch, "mps")+ monkeypatch.setenv("UNSLOTH_DIFFUSION_MLX", "0")assert _select() == ENGINE_DIFFUSERSassert unloaded == [True]@@ -405,6 +534,8 @@ def test_family_buildable_here_counts_mlx_only_with_a_convertible_gguf(monkeypatassert r.family_buildable_here(fam, model_kind = "gguf", gguf_filename = _Q4) is Trueassert r.family_buildable_here(fam, model_kind = "gguf") is Falsemonkeypatch.delenv("UNSLOTH_DIFFUSION_MLX")+ assert r.family_buildable_here(fam, model_kind = "gguf", gguf_filename = _Q4) is True+ monkeypatch.setenv("UNSLOTH_DIFFUSION_MLX", "0")assert r.family_buildable_here(fam, model_kind = "gguf", gguf_filename = _Q4) is False@@ -440,41 +571,25 @@ def test_auto_switch_planner_judges_mlx_with_the_picks_gguf(monkeypatch):assert media_locality.planners_for(DIFFUSION, pick) == [ENGINE_MLX]-# ── a LoRA load never lands on MLX, which refuses adapters ───────────────────--- "gguf",- [- "z-image-turbo-Q4_K_M.gguf",- "z-image-turbo-Q5_K_M.gguf",- "z-image-turbo-Q6_K.gguf",- "z-image-turbo-Q5_0.gguf",- "z-image-turbo-Q5_1.gguf",- _Q4,- ],-)-def test_a_lora_load_keeps_sd_cpp_under_the_mlx_opt_in(monkeypatch, gguf):- # An MPS Mac running native sd.cpp today with a LoRA: the opt-in must not divert it into MLX's refusal.[email protected]("value", [None, "auto"])[email protected]("gguf", [_Q4, "z-image-turbo-Q4_K_M.gguf", "z-image-turbo-Q5_1.gguf"])+def test_a_lora_load_declines_mlx_under_default_routing(monkeypatch, value, gguf):_apple(monkeypatch)- monkeypatch.setenv("UNSLOTH_DIFFUSION_MLX", "1")- monkeypatch.setenv("UNSLOTH_DIFFUSION_SD_CPP_MPS", "1")- monkeypatch.setattr(r, "ensure_sd_cpp_binary", lambda **_: "/usr/bin/sd-cli")- monkeypatch.setattr(r, "SdCppEngine", lambda **_: SimpleNamespace(version = lambda: "v0"))+ if value is not None:+ monkeypatch.setenv("UNSLOTH_DIFFUSION_MLX", value)fam = detect_family("z-image")assert _predict(gguf = gguf) == _select(gguf = gguf) == ENGINE_MLXkw = dict(model_kind = "gguf", gguf_filename = gguf, with_loras = True)- assert r.predict_engine(fam, **kw) == ENGINE_SD_CPP+ assert r.predict_engine(fam, **kw) == ENGINE_DIFFUSERSr.select_and_activate_engine(fam, **kw)- assert r.active_engine_name() == ENGINE_SD_CPP+ assert r.active_engine_name() == ENGINE_DIFFUSERSassert "LoRA" in (r.annotate_status({})["mlx_fallback_reason"] or "")@pytest.mark.parametrize("sd_cpp_off", [False, True])-def test_a_lora_load_with_no_lora_capable_fallback_is_refused_before_the_switch(+def test_a_forced_mlx_lora_load_with_no_lora_capable_fallback_is_refused_before_the_switch(monkeypatch, sd_cpp_off):- # No native engine: diffusers cannot apply GGUF LoRAs, so refuse before unloading._apple(monkeypatch)monkeypatch.setenv("UNSLOTH_DIFFUSION_MLX", "1")if sd_cpp_off:@@ -489,44 +604,108 @@ def test_a_lora_load_with_no_lora_capable_fallback_is_refused_before_the_switch(assert r.active_engine_name() == ENGINE_MLX-def test_a_lora_load_without_the_mlx_opt_in_still_falls_back_to_diffusers(monkeypatch):+def test_a_forced_mlx_lora_load_keeps_a_lora_capable_sd_cpp(monkeypatch):_apple(monkeypatch)+ monkeypatch.setenv("UNSLOTH_DIFFUSION_MLX", "1")+ monkeypatch.setenv("UNSLOTH_DIFFUSION_SD_CPP_MPS", "1")+ monkeypatch.setattr(r, "ensure_sd_cpp_binary", lambda **_: "/usr/bin/sd-cli")+ monkeypatch.setattr(r, "SdCppEngine", lambda **_: SimpleNamespace(version = lambda: "v0"))fam = detect_family("z-image")- kw = dict(model_kind = "gguf", gguf_filename = "z-image-turbo-Q4_K_M.gguf", with_loras = True)+ kw = dict(model_kind = "gguf", gguf_filename = _Q4, with_loras = True)+ assert r.predict_engine(fam, **kw) == ENGINE_SD_CPP+ r.select_and_activate_engine(fam, **kw)+ assert r.active_engine_name() == ENGINE_SD_CPP++[email protected]("value", [None, "auto", "1"])+def test_a_lora_load_off_apple_silicon_is_unchanged(monkeypatch, value):+ _host(monkeypatch, system = "linux", machine = "x86_64")+ _device(monkeypatch, "cpu")+ if value is not None:+ monkeypatch.setenv("UNSLOTH_DIFFUSION_MLX", value)+ fam = detect_family("z-image")+ kw = dict(model_kind = "gguf", gguf_filename = _Q4, with_loras = True)assert r.predict_engine(fam, **kw) == ENGINE_DIFFUSERSr.select_and_activate_engine(fam, **kw)assert r.active_engine_name() == ENGINE_DIFFUSERS-def test_every_load_route_passes_its_loras_to_engine_selection():+def test_a_lora_load_keeps_sd_cpp_under_default_routing_with_the_native_mps_knob(monkeypatch):+ _apple(monkeypatch)+ monkeypatch.setenv("UNSLOTH_DIFFUSION_SD_CPP_MPS", "1")+ monkeypatch.setattr(r, "ensure_sd_cpp_binary", lambda **_: "/usr/bin/sd-cli")+ monkeypatch.setattr(r, "SdCppEngine", lambda **_: SimpleNamespace(version = lambda: "v0"))+ fam = detect_family("z-image")+ kw = dict(model_kind = "gguf", gguf_filename = _Q4, with_loras = True)+ assert r.predict_engine(fam, **kw) == ENGINE_SD_CPP+ r.select_and_activate_engine(fam, **kw)+ assert r.active_engine_name() == ENGINE_SD_CPP+++def test_every_load_route_and_the_residency_estimate_pass_loras_to_engine_selection():import astfrom pathlib import Path- source = (Path(__file__).resolve().parents[1] / "routes" / "inference.py").read_text(- encoding = "utf-8"- )- calls = [- c- for c in ast.walk(ast.parse(source))- if isinstance(c, ast.Call)- and (- getattr(c.func, "id", None) == "predict_engine"- or (- getattr(c.func, "id", None) == "partial"- or getattr(c.func, "attr", None) == "partial"+ root = Path(__file__).resolve().parents[1]+ for rel, minimum in (("routes/inference.py", 3), ("core/inference/gpu_residency.py", 1)):+ source = (root / rel).read_text(encoding = "utf-8")+ calls = [+ c+ for c in ast.walk(ast.parse(source))+ if isinstance(c, ast.Call)+ and (+ getattr(c.func, "id", None) == "predict_engine"+ or (+ getattr(c.func, "id", None) == "partial"+ or getattr(c.func, "attr", None) == "partial"+ )+ and c.args+ and getattr(c.args[0], "id", None) == "select_and_activate_engine")- and c.args- and getattr(c.args[0], "id", None) == "select_and_activate_engine"- )- ]- assert len(calls) >= 3- for call in calls:- kw = {k.arg: k.value for k in call.keywords}- assert "with_loras" in kw, ast.unparse(call)[:120]- # A zero-weight entry is dropped before loading, so it must not count as a LoRA load.- assert getattr(kw["with_loras"].func, "id", None) == "_has_active_loras", ast.unparse(call)[- :120]+ assert len(calls) >= minimum, rel+ for call in calls:+ kw = {k.arg: k.value for k in call.keywords}+ assert {"with_loras", "mlx_blocker"} <= set(kw), f"{rel}: {ast.unparse(call)[:120]}"+ assert getattr(kw["with_loras"].func, "id", None) in (+ "_has_active_loras",+ "has_active_loras",+ ), f"{rel}: {ast.unparse(call)[:120]}"+++ "gguf",+ [+ "z-image-turbo-Q4_K_M.gguf",+ "z-image-turbo-Q5_K_M.gguf",+ "z-image-turbo-Q6_K.gguf",+ "z-image-turbo-Q5_0.gguf",+ "z-image-turbo-Q5_1.gguf",+ _Q4,+ ],+)+def test_a_lora_load_keeps_sd_cpp_under_the_mlx_opt_in(monkeypatch, gguf):+ _apple(monkeypatch)+ monkeypatch.setenv("UNSLOTH_DIFFUSION_MLX", "1")+ monkeypatch.setenv("UNSLOTH_DIFFUSION_SD_CPP_MPS", "1")+ monkeypatch.setattr(r, "ensure_sd_cpp_binary", lambda **_: "/usr/bin/sd-cli")+ monkeypatch.setattr(r, "SdCppEngine", lambda **_: SimpleNamespace(version = lambda: "v0"))+ fam = detect_family("z-image")+ assert _predict(gguf = gguf) == _select(gguf = gguf) == ENGINE_MLX+ kw = dict(model_kind = "gguf", gguf_filename = gguf, with_loras = True)+ assert r.predict_engine(fam, **kw) == ENGINE_SD_CPP+ r.select_and_activate_engine(fam, **kw)+ assert r.active_engine_name() == ENGINE_SD_CPP+ assert "LoRA" in (r.annotate_status({})["mlx_fallback_reason"] or "")+++def test_a_lora_load_without_the_mlx_opt_in_still_falls_back_to_diffusers(monkeypatch):+ _apple(monkeypatch)+ fam = detect_family("z-image")+ kw = dict(model_kind = "gguf", gguf_filename = "z-image-turbo-Q4_K_M.gguf", with_loras = True)+ assert r.predict_engine(fam, **kw) == ENGINE_DIFFUSERS+ r.select_and_activate_engine(fam, **kw)+ assert r.active_engine_name() == ENGINE_DIFFUSERS@pytest.mark.parametrize(@@ -553,3 +732,4 @@ def test_a_zero_weight_lora_load_still_lands_on_mlx(monkeypatch):fam = detect_family("z-image")kw = dict(model_kind = "gguf", gguf_filename = gguf, with_loras = r.has_active_loras([("a", 0.0)]))assert r.predict_engine(fam, **kw) == ENGINE_MLX+ assert r.mlx_load_blocker(loras = [("a", 0.0)]) is Nonediff --git a/studio/backend/tests/test_diffusion_routes.py b/studio/backend/tests/test_diffusion_routes.pyindex 2e73ec99470..390e67a5cc8 100644--- a/studio/backend/tests/test_diffusion_routes.py+++ b/studio/backend/tests/test_diffusion_routes.py@@ -739,6 +739,26 @@ def test_generate_memory_refusal_is_a_tagged_400_and_allow_oversized_reaches_theassert IMAGE_REFUSAL_HEADER not in other.headers+def test_generate_unified_memory_load_refusal_is_structured_not_500(client, monkeypatch):+ from core.inference.diffusion_memory import (+ IMAGE_REFUSAL_HEADER,+ UNIFIED_OVERSIZE_REFUSAL_CODE,+ UnifiedMemoryShortfallError,+ )++ backend = diffusion_module.get_diffusion_backend()+ backend.loaded = True++ def _refused(**kwargs):+ raise UnifiedMemoryShortfallError("Could not load the diffusers engine: needs about 30 GB")++ monkeypatch.setattr(backend, "generate", _refused)+ resp = client.post("/api/inference/images/generate", json = {"prompt": "p"})+ assert resp.status_code == 400+ assert resp.headers.get(IMAGE_REFUSAL_HEADER) == UNIFIED_OVERSIZE_REFUSAL_CODE+ assert "30 GB" in resp.json()["detail"]++def test_generate_user_cancellation_returns_409(client, monkeypatch):backend = diffusion_module.get_diffusion_backend()backend.loaded = Truediff --git a/studio/backend/tests/test_mlx_diffusion_backend.py b/studio/backend/tests/test_mlx_diffusion_backend.pyindex 6fb5f2fcae2..5297a99428a 100644--- a/studio/backend/tests/test_mlx_diffusion_backend.py+++ b/studio/backend/tests/test_mlx_diffusion_backend.py@@ -1868,3 +1868,11 @@ def test_release_buffer_cache_never_replaces_the_callers_exception():finally:mb.release_buffer_cache(mx)assert events == ["synchronize", "clear_cache"]+++def test_the_mlx_base_fetch_keeps_the_fallback_scheduler_config():+ import fnmatch++ from core.inference.mlx_diffusion_backend import BASE_ALLOW_PATTERNS+ for name in ("scheduler/scheduler_config.json", "model_index.json"):+ assert any(fnmatch.fnmatch(name, pattern) for pattern in BASE_ALLOW_PATTERNS), namediff --git a/studio/backend/tests/test_mlx_diffusion_routing.py b/studio/backend/tests/test_mlx_diffusion_routing.pynew file mode 100644index 00000000000..5c9fc41be9d--- /dev/null+++ b/studio/backend/tests/test_mlx_diffusion_routing.py@@ -0,0 +1,1090 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Per-request MLX / diffusers routing on Apple Silicon, with fake engines (no mlx, torch or GPU needed)."""++from __future__ import annotations++import inspect+import threading+import time+from types import SimpleNamespace+from typing import Any, Optional++import pytest++from core.inference import diffusion_families as families+from core.inference import mlx_diffusion_routing as routing+from core.inference.diffusion_families import (+ DIFFUSION_CANCELLED_MSG,+ DIFFUSION_NOT_LOADED_MSG,+ DiffusionModelReplacedError,+ load_identity,+)++GIB = 1024**3+_FAM = SimpleNamespace(name = "z-image")+++class _Engine:+ def __init__(self, name: str, log: list, *, base: str) -> None:+ self.name = name+ self.log = log+ self.base = base+ self._state: Any = None+ self._load_error: Optional[str] = None+ self._loading = False+ self.load_kwargs: Optional[dict] = None+ self.fail_next_load: Optional[str] = None+ self.hang_load = False+ self.cancelled = threading.Event()++ def begin_load(self, repo_id: str, **kwargs: Any) -> dict:+ self.log.append((self.name, "load"))+ self.load_kwargs = {"repo_id": repo_id, **kwargs}+ self._load_error = None+ if self.fail_next_load:+ self._load_error, self.fail_next_load = self.fail_next_load, None+ return self.status()+ if self.hang_load:+ self._loading = True+ return self.status()+ self._state = SimpleNamespace(+ family = _FAM,+ repo_id = repo_id,+ timings = {"quant_plan": {"planned_bytes": 6 * GIB}},+ gguf_path = None,+ convert_dir = None,+ )+ return self.status()++ def load_progress(self) -> dict:+ if self._load_error:+ return {"phase": "error", "error": self._load_error}+ if self._loading:+ return {"phase": "downloading"}+ return {"phase": "ready" if self._state is not None else None}++ def unload(self, *, expected_account: Optional[str] = None) -> dict:+ self.log.append((self.name, "unload"))+ self._state = None+ self._loading = False+ return self.status()++ def status(self) -> dict:+ if self._state is None:+ return {"loaded": False, "engine": self.name, "workflows": []}+ return {+ "loaded": True,+ "engine": self.name,+ "repo_id": self._state.repo_id,+ "base_repo": self.base,+ "family": "z-image",+ "workflows": ["txt2img"] if self.name == "mlx" else ["txt2img", "img2img"],+ }++ def generate_progress(self) -> dict:+ return {"active": False, "engine": self.name}++ def cancel_generate(self, expected_account: Optional[str] = None) -> bool:+ self.cancelled.set()+ return True++ def loaded_repo_ids(self) -> tuple:+ return (self._state.repo_id,) if self._state is not None else ()++ def _run(self, expected_load, kwargs) -> dict:+ if self._state is None:+ raise RuntimeError(DIFFUSION_NOT_LOADED_MSG)+ if expected_load is not None and expected_load != load_identity(+ self._state.repo_id, self.base, "z-image"+ ):+ raise DiffusionModelReplacedError(expected_load, expected_load)+ self.log.append((self.name, "generate"))+ return {"images": [f"{self.name}-image"], "seed": kwargs.get("seed"), "kwargs": kwargs}+++class _Mlx(_Engine):+ def generate(+ self,+ *,+ prompt: str,+ width: Optional[int] = 1024,+ height: Optional[int] = 1024,+ seed: Optional[int] = None,+ init_image: Optional[str] = None,+ workflow: Optional[str] = None,+ loras: Any = None,+ controlnet: Any = None,+ prompts: Any = None,+ seeds: Any = None,+ upscale: Optional[float] = None,+ expected_load: Any = None,+ hires: Any = None,+ ) -> dict:+ if init_image is not None or workflow not in (None, "txt2img"):+ raise ValueError("The MLX engine runs text-to-image only")+ return self._run(+ expected_load, {"prompt": prompt, "width": width, "height": height, "seed": seed}+ )+++class _Diffusers(_Engine):+ def generate(+ self,+ *,+ prompt: str,+ width: Optional[int] = 1024,+ height: Optional[int] = 1024,+ seed: Optional[int] = None,+ init_image: Optional[str] = None,+ mask_image: Optional[str] = None,+ strength: Optional[float] = None,+ workflow: Optional[str] = None,+ loras: Any = None,+ controlnet: Any = None,+ prompts: Any = None,+ seeds: Any = None,+ upscale: Optional[float] = None,+ expected_load: Any = None,+ hires: Any = None,+ live_preview: Optional[bool] = None,+ sampler: Optional[str] = None,+ schedule_type: Optional[str] = None,+ sd_controls: Any = None,+ shift: Optional[float] = None,+ base_shift: Optional[float] = None,+ max_shift: Optional[float] = None,+ upscale_model: Optional[str] = None,+ tile_vae: bool = False,+ guidance: float = 0.0,+ negative_prompt: Optional[str] = None,+ ) -> dict:+ return self._run(+ expected_load,+ {"prompt": prompt, "init_image": init_image, "seed": seed, "sampler": sampler},+ )+++def rig(monkeypatch):+ monkeypatch.delenv(routing.COEXIST_ENV, raising = False)+ monkeypatch.setattr(families, "family_pipeline_available", lambda _f: True)+ log: list = []+ mlx = _Mlx("mlx", log, base = "Tongyi-MAI/Z-Image-Turbo")+ diffusers = _Diffusers("diffusers", log, base = "unsloth/Z-Image-Turbo")+ fit = {"coexist": False}+ engine = routing.RoutedMlxEngine(+ mlx_factory = lambda: mlx,+ diffusers_factory = lambda: diffusers,+ budget_fn = lambda: 5 * GIB,+ capabilities_fn = lambda fam: {+ "workflows": ["txt2img", "img2img", "upscale", "inpaint", "outpaint"],+ "hires": {"available": True},+ },+ poll_s = 0.01,+ )+ monkeypatch.setattr(engine, "_engines_fit_together", lambda: fit["coexist"])+ 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",+ )+ log.clear()+ return SimpleNamespace(engine = engine, mlx = mlx, diffusers = diffusers, log = log, fit = fit)+++def _txt2img(engine, **extra):+ return engine.generate(prompt = "a fox", width = 512, height = 512, seed = 42, **extra)+++def _img2img(engine, **extra):+ return engine.generate(+ prompt = "a fox",+ width = 512,+ height = 512,+ seed = 42,+ init_image = "data:image/png;base64,AAAA",+ strength = 0.6,+ workflow = "img2img",+ **extra,+ )+++def test_plain_txt2img_runs_on_mlx_and_never_loads_diffusers(rig):+ result = _txt2img(rig.engine, sampler = "default", schedule_type = "automatic", live_preview = True)+ assert result["engine"] == "mlx"+ assert result["images"] == ["mlx-image"]+ assert rig.log == [("mlx", "generate")]+ assert set(result["kwargs"]) == {"prompt", "width", "height", "seed"}+ routing_status = rig.engine.status()["engine_routing"]+ assert routing_status["resident"] == ["mlx"]+ assert routing_status["last_served_by"] == "mlx"+ assert routing_status["txt2img_engine"] == "mlx"+++def test_img2img_after_txt2img_unloads_mlx_first_then_serves_from_diffusers(rig):+ assert _txt2img(rig.engine)["engine"] == "mlx"+ result = _img2img(rig.engine)+ assert result["engine"] == "diffusers"+ assert result["kwargs"]["init_image"] == "data:image/png;base64,AAAA"+ assert rig.log == [+ ("mlx", "generate"),+ ("mlx", "unload"),+ ("diffusers", "load"),+ ("diffusers", "generate"),+ ]+ assert rig.diffusers.load_kwargs == {+ "repo_id": "unsloth/Z-Image-Turbo-GGUF",+ "gguf_filename": "z-image-turbo-Q4_0.gguf",+ "local_files_only": True,+ "hf_token": None,+ "model_kind": "gguf",+ }+ status = rig.engine.status()+ assert status["engine"] == "diffusers"+ assert status["engine_routing"]["resident"] == ["diffusers"]+ assert status["engine_routing"]["last_served_by"] == "diffusers"+ assert "img2img" in status["engine_routing"]["last_reason"]+ assert status["engine_routing"]["engines_fit_together"] is False+++def test_after_a_fallback_that_did_not_fit_txt2img_stays_on_diffusers(rig):+ _img2img(rig.engine)+ rig.log.clear()+ result = _txt2img(rig.engine)+ assert result["engine"] == "diffusers"+ assert rig.log == [("diffusers", "generate")]+ routing_status = rig.engine.status()["engine_routing"]+ assert routing_status["txt2img_engine"] == "diffusers"+ assert "load the model again" in routing_status["last_reason"]+++def test_when_both_fit_both_stay_resident_and_txt2img_returns_to_mlx(rig):+ rig.fit["coexist"] = True+ assert _img2img(rig.engine)["engine"] == "diffusers"+ assert ("mlx", "unload") not in rig.log+ assert _txt2img(rig.engine)["engine"] == "mlx"+ assert _img2img(rig.engine)["engine"] == "diffusers"+ assert rig.log.count(("diffusers", "load")) == 1+ assert rig.engine.status()["engine_routing"]["resident"] == ["mlx", "diffusers"]+++ "extra, needle",+ [+ ({"init_image": "x", "workflow": "img2img"}, "img2img"),+ ({"mask_image": "m", "init_image": "x"}, "inpainting"),+ ({"workflow": "edit"}, "edit"),+ ({"hires": object()}, "Hires"),+ ({"upscale_model": "4x"}, "upscaler"),+ ({"upscale": 2.0}, "upscaling"),+ ({"prompts": ["a", "b"]}, "lists"),+ ({"seeds": [1, 2]}, "lists"),+ ({"loras": [("l", 1.0)]}, "LoRA"),+ ({"controlnet": ("c", "img", "canny", 0.8, 0.0, 1.0)}, "ControlNet"),+ ({"sampler": "euler"}, "sampler"),+ ({"schedule_type": "karras"}, "sampler"),+ ({"sd_controls": SimpleNamespace(requested = lambda: True)}, "prompt weighting"),+ ({"shift": 3.0}, "shift"),+ ({"tile_vae": True}, "tile_vae"),+ ],+)+def test_every_feature_mlx_lacks_routes_to_diffusers(rig, extra, needle):+ blocker = routing.request_blocker(+ {"prompt": "p", **extra}, family = "z-image", mlx_params = frozenset({"prompt"})+ )+ assert blocker and needle in blocker+ assert rig.engine.generate(prompt = "p", **extra)["engine"] == "diffusers"+++ "extra",+ [+ {},+ {"workflow": "txt2img"},+ {"upscale": 1.0},+ {"controlnet": ("c", "img", "canny", 0.0, 0.0, 1.0)},+ {"sampler": "default", "schedule_type": "automatic"},+ {"sd_controls": SimpleNamespace(requested = lambda: False)},+ {"live_preview": True, "mask_blur": 4},+ {"tile_vae": False},+ ],+)+def test_neutral_values_stay_on_mlx(rig, extra):+ assert (+ routing.request_blocker({"prompt": "p", **extra}, mlx_params = frozenset({"prompt"})) is None+ )+ assert rig.engine.generate(prompt = "p", **extra)["engine"] == "mlx"+++ "blocker, mlx_resident, diffusers_resident, fallback, coexist, expected",+ [+ (None, True, False, True, False, ("mlx", False, False)),+ (None, True, True, True, True, ("mlx", False, False)),+ (None, False, True, True, False, ("diffusers", False, False)),+ (None, False, False, True, False, ("mlx", False, False)),+ ("img2img", True, False, True, False, ("diffusers", True, True)),+ ("img2img", True, False, True, True, ("diffusers", True, False)),+ ("img2img", True, True, True, True, ("diffusers", False, False)),+ ("img2img", False, True, True, False, ("diffusers", False, False)),+ ("img2img", True, False, False, False, ("mlx", False, False)),+ ("img2img", False, False, True, False, ("mlx", False, False)),+ ],+)+def test_decide_route_table(blocker, mlx_resident, diffusers_resident, fallback, coexist, expected):+ route = routing.decide_route(+ blocker = blocker,+ mlx_resident = mlx_resident,+ diffusers_resident = diffusers_resident,+ fallback_available = fallback,+ coexist = coexist,+ )+ assert (route.engine, route.load_diffusers, route.unload_mlx) == expected+++def test_a_family_diffusers_cannot_build_keeps_the_mlx_refusal(rig, monkeypatch):+ monkeypatch.setattr(families, "family_pipeline_available", lambda _f: False)+ with pytest.raises(ValueError, match = "text-to-image only"):+ _img2img(rig.engine)+ assert ("diffusers", "load") not in rig.log+ assert rig.engine.status()["workflows"] == ["txt2img"]+++def test_status_advertises_the_fallback_workflows_while_mlx_is_resident(rig):+ status = rig.engine.status()+ assert status["engine"] == "mlx"+ assert "img2img" in status["workflows"]+ assert status["hires"] == {"available": True}+++ "mlx_gib, diffusers_gib, budget_gib, expected",+ [+ (6, 4, 10.7, True),+ (7.5, 12, 10.7, False),+ (2, 3, 5.01, True),+ (0, 3, 5.01, False),+ (3, 0, 5.01, False),+ (3, 3, 0, False),+ ],+)+def test_engines_coexist_only_when_both_fit(+ monkeypatch, mlx_gib, diffusers_gib, budget_gib, expected+):+ monkeypatch.delenv(routing.COEXIST_ENV, raising = False)+ assert (+ routing.engines_coexist(int(mlx_gib * GIB), int(diffusers_gib * GIB), int(budget_gib * GIB))+ is expected+ )++[email protected]("value, expected", [("1", True), ("0", False)])+def test_coexist_env_overrides(monkeypatch, value, expected):+ monkeypatch.setenv(routing.COEXIST_ENV, value)+ assert routing.engines_coexist(100 * GIB, 100 * GIB, GIB) is expected+ assert routing.engines_coexist(1, 1, 100 * GIB) is expected+++def test_diffusers_size_is_the_gguf_plus_bf16_text_encoder_and_vae(tmp_path):+ import json+ import struct++ def _st(folder, shape):+ folder.mkdir()+ header = json.dumps(+ {"w": {"dtype": "BF16", "shape": shape, "data_offsets": [0, 0]}}+ ).encode()+ (folder / "model.safetensors").write_bytes(struct.pack("<Q", len(header)) + header)++ gguf = tmp_path / "m.gguf"+ gguf.write_bytes(b"\0" * 1000)+ _st(tmp_path / "text_encoder", [10, 10])+ _st(tmp_path / "vae", [5])+ assert routing.diffusers_resident_bytes(str(gguf), str(tmp_path)) == 1000 + 200 + 10+ assert routing.diffusers_resident_bytes(None, str(tmp_path)) == 0+ assert routing.diffusers_resident_bytes(str(tmp_path / "missing.gguf"), str(tmp_path)) == 0+++def test_the_real_fit_check_reads_the_mlx_plan_and_the_budget(tmp_path, monkeypatch):+ log: list = []+ mlx = _Mlx("mlx", log, base = "b")+ mlx.begin_load("r")+ mlx._state.gguf_path = "g"+ mlx._state.convert_dir = "d"+ monkeypatch.setattr(routing, "diffusers_resident_bytes", lambda g, d: 4 * GIB)+ monkeypatch.delenv(routing.COEXIST_ENV, raising = False)+ small = routing.RoutedMlxEngine(mlx_factory = lambda: mlx, budget_fn = lambda: 9 * GIB)+ big = routing.RoutedMlxEngine(mlx_factory = lambda: mlx, budget_fn = lambda: 11 * GIB)+ assert small._engines_fit_together() is False+ assert big._engines_fit_together() is True+++def test_a_failed_fallback_reports_the_error_and_restores_mlx(rig):+ rig.diffusers.fail_next_load = "does not fit"+ with pytest.raises(RuntimeError, match = "does not fit"):+ _img2img(rig.engine)+ assert rig.log == [("mlx", "unload"), ("diffusers", "load"), ("mlx", "load")]+ assert rig.engine.status()["engine_routing"]["resident"] == ["mlx"]+ assert _txt2img(rig.engine)["engine"] == "mlx"+++def test_cancel_during_the_fallback_load_stops_it(rig):+ rig.diffusers.hang_load = True+ errors = []++ def _run():+ try:+ _img2img(rig.engine)+ except RuntimeError as exc:+ errors.append(str(exc))++ worker = threading.Thread(target = _run)+ worker.start()+ deadline = time.time() + 5+ while rig.engine._fallback_cancel is None and time.time() < deadline:+ time.sleep(0.01)+ progress = rig.engine.generate_progress()+ assert progress["active"] is True and progress["step"] == 0+ assert rig.engine.cancel_generate() is True+ worker.join(5)+ assert errors == [DIFFUSION_CANCELLED_MSG]+ assert ("diffusers", "unload") in rig.log+++def test_a_stopped_generation_ticket_stops_the_fallback_load(rig):+ from core.inference.generation_ticket import GenerationTicket, generation_ticket++ rig.diffusers.hang_load = True+ ticket = GenerationTicket()+ errors = []++ def _run():+ with generation_ticket(ticket):+ try:+ _img2img(rig.engine)+ except RuntimeError as exc:+ errors.append(str(exc))++ worker = threading.Thread(target = _run, daemon = True)+ worker.start()+ deadline = time.time() + 5+ while rig.engine._fallback_cancel is None and time.time() < deadline:+ time.sleep(0.01)+ ticket.stop()+ worker.join(5)+ assert not worker.is_alive()+ assert errors == [DIFFUSION_CANCELLED_MSG]+ assert ("diffusers", "unload") in rig.log+++def test_cancel_during_the_fallback_load_checks_the_owner(rig):+ rig.engine._fallback_cancel = threading.Event()+ rig.engine._active_generate_account = "owner"+ assert rig.engine.cancel_generate(expected_account = "intruder") is False+ assert rig.engine.cancel_generate(expected_account = "owner") is True+++def test_a_replaced_model_is_refused(rig):+ stale = load_identity("someone/else", "x", "z-image")+ with pytest.raises(DiffusionModelReplacedError):+ _txt2img(rig.engine, expected_load = stale)+++def test_the_original_identity_is_accepted_after_the_fallback(rig):+ mlx_identity = load_identity(+ "unsloth/Z-Image-Turbo-GGUF", "Tongyi-MAI/Z-Image-Turbo", "z-image"+ )+ assert _txt2img(rig.engine, expected_load = mlx_identity)["engine"] == "mlx"+ assert _img2img(rig.engine, expected_load = mlx_identity)["engine"] == "diffusers"+ assert _txt2img(rig.engine, expected_load = mlx_identity)["engine"] == "diffusers"+++def test_a_new_load_drops_the_old_fallback_and_returns_to_mlx(rig):+ _img2img(rig.engine)+ rig.log.clear()+ rig.engine.begin_load("unsloth/Z-Image-Turbo-GGUF", gguf_filename = "z-image-turbo-Q8_0.gguf")+ assert rig.log == [("diffusers", "unload"), ("mlx", "load")]+ assert _txt2img(rig.engine)["engine"] == "mlx"+ assert rig.engine.status()["engine_routing"]["resident"] == ["mlx"]+++def test_unload_frees_both_engines(rig):+ rig.fit["coexist"] = True+ _img2img(rig.engine)+ rig.log.clear()+ status = rig.engine.unload()+ assert rig.log == [("mlx", "unload"), ("diffusers", "unload")]+ assert status["loaded"] is False+ with pytest.raises(RuntimeError, match = DIFFUSION_NOT_LOADED_MSG):+ _img2img(rig.engine)+ assert ("diffusers", "load") not in rig.log+++def test_a_scoped_unload_never_cancels_another_accounts_fallback(rig):+ from core.inference.gpu_arbiter import GpuBusyForAnotherAccountError++ cancel = threading.Event()+ rig.engine._fallback_cancel = cancel+ rig.engine._active_generate_account = "owner"+ epoch = rig.engine._epoch+ with pytest.raises(GpuBusyForAnotherAccountError):+ rig.engine.unload(expected_account = "intruder")+ assert not cancel.is_set() and rig.engine._epoch == epoch+ assert ("mlx", "unload") not in rig.log++[email protected]("field", ["transformer_quant", "text_encoder_quant"])[email protected]("value", ["none", "off", "NONE"])+def test_a_pinned_original_precision_keeps_the_load_on_diffusers(field, value):+ blocker = routing.load_blocker(**{field: value})+ assert blocker and value in blocker+++def test_unload_forwards_the_account_scope_to_the_fallback(rig):+ rig.fit["coexist"] = True+ _img2img(rig.engine)+ seen = []+ real = rig.diffusers.unload++ unscoped = object()++ def _scoped_unload(*, expected_account = unscoped):+ seen.append(expected_account)+ return real() if expected_account is unscoped else real(expected_account = expected_account)++ rig.diffusers.unload = _scoped_unload+ rig.engine.unload(expected_account = "owner")+ assert seen == ["owner"]+++def test_a_plain_diffusers_load_is_never_unloaded_as_a_fallback(rig):+ rig.diffusers.begin_load("someone/else")+ rig.log.clear()+ rig.engine.unload()+ assert ("diffusers", "unload") not in rig.log+++def test_repo_ids_cover_both_engines(rig):+ rig.fit["coexist"] = True+ _img2img(rig.engine)+ assert rig.engine.loaded_repo_ids() == ("unsloth/Z-Image-Turbo-GGUF",)+++def test_generate_signature_is_the_union_of_both_engines(rig):+ params = inspect.signature(rig.engine.generate).parameters+ for name in (+ "sampler",+ "sd_controls",+ "shift",+ "hires",+ "upscale_model",+ "live_preview",+ "prompt",+ ):+ assert name in params+ assert all(p.kind is inspect.Parameter.KEYWORD_ONLY for p in params.values())+ assert rig.engine.generate.__self__ is rig.engine+ assert rig.engine.parses_prompt_attention is False+++def test_load_blocker_matrix():+ assert routing.load_blocker() is None+ assert routing.load_blocker(transformer_quant = "auto", text_encoder_quant = "default") is None+ assert "LoRA" in routing.load_blocker(loras = [("a", 1.0)])+ assert "VAE" in routing.load_blocker(component_files = {"vae_file": "v"})+ assert "int8" in routing.load_blocker(transformer_quant = "int8")+ assert "fp8" in routing.load_blocker(text_encoder_quant = "fp8")+++def test_unload_during_the_fallback_begin_load_waits_for_its_teardown(rig):+ entered, release = threading.Event(), threading.Event()+ real_begin_load = rig.diffusers.begin_load++ def _slow_begin_load(repo_id, **kwargs):+ entered.set()+ release.wait(5)+ return real_begin_load(repo_id, **kwargs)++ rig.diffusers.begin_load = _slow_begin_load+ outcome: list = []++ def _run():+ try:+ outcome.append(_img2img(rig.engine)["engine"])+ except RuntimeError as exc:+ outcome.append(str(exc))++ worker = threading.Thread(target = _run)+ worker.start()+ assert entered.wait(5)+ unloaded: list = []+ unloader = threading.Thread(target = lambda: unloaded.append(rig.engine.unload()))+ unloader.start()+ time.sleep(0.05)+ assert unloaded == []+ release.set()+ unloader.join(5)+ worker.join(5)+ assert unloaded and unloaded[0]["loaded"] is False+ assert outcome == [DIFFUSION_CANCELLED_MSG]+ assert rig.diffusers._state is None+ assert ("diffusers", "generate") not in rig.log+++def test_a_cancel_is_honoured_even_when_the_fallback_turns_ready(rig):+ rig.diffusers.hang_load = True+ outcome: list = []++ def _run():+ try:+ outcome.append(_img2img(rig.engine)["engine"])+ except RuntimeError as exc:+ outcome.append(str(exc))++ worker = threading.Thread(target = _run)+ worker.start()+ deadline = time.time() + 5+ while rig.engine._fallback_cancel is None and time.time() < deadline:+ time.sleep(0.005)+ rig.engine._fallback_cancel.set()+ rig.diffusers._loading = False+ rig.diffusers._state = SimpleNamespace(+ family = _FAM,+ repo_id = "unsloth/Z-Image-Turbo-GGUF",+ timings = {},+ gguf_path = None,+ convert_dir = None,+ )+ worker.join(5)+ assert outcome == [DIFFUSION_CANCELLED_MSG]+ assert ("diffusers", "generate") not in rig.log+++def test_no_fallback_while_a_replacement_mlx_load_is_pending(rig):+ a_identity = load_identity("unsloth/Z-Image-Turbo-GGUF", "Tongyi-MAI/Z-Image-Turbo", "z-image")+ rig.mlx.hang_load = True+ real_begin_load = rig.mlx.begin_load++ def _keep_resident(repo_id, **kwargs):+ resident = rig.mlx._state+ out = real_begin_load(repo_id, **kwargs)+ rig.mlx._state = resident+ return out++ rig.mlx.begin_load = _keep_resident+ rig.engine.begin_load("someone/Other-GGUF", gguf_filename = "other-Q8_0.gguf")+ rig.log.clear()+ with pytest.raises(RuntimeError, match = "load is in progress"):+ _img2img(rig.engine, expected_load = a_identity)+ assert ("diffusers", "load") not in rig.log+ assert ("mlx", "unload") not in rig.log+++def test_an_option_mlx_never_receives_is_refused_without_a_fallback(rig, monkeypatch):+ monkeypatch.setattr(families, "family_pipeline_available", lambda _f: False)+ with pytest.raises(ValueError, match = "sampler choice is not supported on the MLX engine"):+ _txt2img(rig.engine, sampler = "euler")+ with pytest.raises(ValueError, match = "shift override"):+ _txt2img(rig.engine, shift = 3.0)+ assert ("mlx", "generate") not in rig.log+ assert _txt2img(rig.engine, sampler = "default")["engine"] == "mlx"+++def test_a_load_replacing_the_model_after_the_identity_check_is_refused(rig):+ a_identity = load_identity("unsloth/Z-Image-Turbo-GGUF", "Tongyi-MAI/Z-Image-Turbo", "z-image")+ entered, release = threading.Event(), threading.Event()+ real_accepted = rig.engine._accepted_identities++ def _paused(*args, **kwargs):+ out = real_accepted(*args, **kwargs)+ entered.set()+ assert release.wait(5)+ return out++ rig.engine._accepted_identities = _paused+ outcome: list = []++ def _run():+ try:+ outcome.append(_txt2img(rig.engine, expected_load = a_identity)["engine"])+ except Exception as exc: # noqa: BLE001+ outcome.append(exc)++ worker = threading.Thread(target = _run)+ worker.start()+ assert entered.wait(5)+ rig.engine.begin_load("someone/Other-GGUF", gguf_filename = "other-Q8_0.gguf")+ release.set()+ worker.join(5)+ assert not worker.is_alive()+ assert len(outcome) == 1 and isinstance(outcome[0], DiffusionModelReplacedError), outcome+ assert ("mlx", "generate") not in rig.log+++def test_a_superseded_fallback_never_unloads_the_new_load(rig):+ entered, release = threading.Event(), threading.Event()+ real_fallback = rig.engine._load_fallback++ def _paused(**kwargs):+ entered.set()+ assert release.wait(5)+ return real_fallback(**kwargs)++ rig.engine._load_fallback = _paused+ outcome: list = []++ def _run():+ try:+ outcome.append(_img2img(rig.engine)["engine"])+ except RuntimeError as exc:+ outcome.append(str(exc))++ worker = threading.Thread(target = _run)+ worker.start()+ assert entered.wait(5)+ rig.engine.begin_load("someone/Other-GGUF", gguf_filename = "other-Q8_0.gguf")+ rig.log.clear()+ release.set()+ worker.join(5)+ assert not worker.is_alive()+ assert outcome == [DIFFUSION_CANCELLED_MSG]+ assert rig.log == []+ assert rig.mlx._state is not None and rig.mlx._state.repo_id == "someone/Other-GGUF"+ assert rig.engine.is_loaded+++def _pause_mlx_begin_load(rig):+ entered, release = threading.Event(), threading.Event()+ real_begin_load = rig.mlx.begin_load++ def _paused(repo_id, **kwargs):+ entered.set()+ assert release.wait(5)+ return real_begin_load(repo_id, **kwargs)++ rig.mlx.begin_load = _paused+ return entered, release+++def _in_thread(fn):+ outcome: list = []++ def _run():+ try:+ outcome.append(fn())+ except Exception as exc: # noqa: BLE001+ outcome.append(exc)++ worker = threading.Thread(target = _run)+ worker.start()+ return worker, outcome+++def test_no_fallback_registers_while_a_replacement_is_being_set_up(rig):+ # Epoch bumped, options not yet registered: a fallback now would load stale options.+ entered, release = _pause_mlx_begin_load(rig)+ replacer, replaced = _in_thread(+ lambda: rig.engine.begin_load("someone/Other-GGUF", gguf_filename = "other-Q8_0.gguf")+ )+ assert entered.wait(5)+ with pytest.raises(RuntimeError, match = DIFFUSION_CANCELLED_MSG):+ _img2img(rig.engine)+ assert ("diffusers", "load") not in rig.log+ release.set()+ replacer.join(5)+ assert not replacer.is_alive() and not isinstance(replaced[0], Exception), replaced+ assert rig.mlx._state.repo_id == "someone/Other-GGUF"+ assert rig.diffusers._state is None+ assert rig.engine._load_kwargs["repo_id"] == "someone/Other-GGUF"+++def test_a_route_decided_during_replacement_setup_never_registers_after_it(rig):+ entered, release = _pause_mlx_begin_load(rig)+ routed, go = threading.Event(), threading.Event()+ real_fallback = rig.engine._load_fallback++ def _paused_fallback(**kwargs):+ routed.set()+ assert go.wait(5)+ return real_fallback(**kwargs)++ rig.engine._load_fallback = _paused_fallback+ replacer, _ = _in_thread(+ lambda: rig.engine.begin_load("someone/Other-GGUF", gguf_filename = "other-Q8_0.gguf")+ )+ assert entered.wait(5)+ requester, outcome = _in_thread(lambda: _img2img(rig.engine)["engine"])+ assert routed.wait(5)+ release.set()+ replacer.join(5)+ assert not replacer.is_alive()+ rig.log.clear()+ go.set()+ requester.join(5)+ assert not requester.is_alive()+ assert len(outcome) == 1 and isinstance(outcome[0], RuntimeError), outcome+ assert str(outcome[0]) == DIFFUSION_CANCELLED_MSG+ assert rig.log == []+ assert rig.mlx._state.repo_id == "someone/Other-GGUF"+ assert rig.diffusers._state is None+++def _guidance_distilled_mlx(rig, monkeypatch, *, supports_guidance):+ real_status, real_run = rig.mlx.status, rig.mlx._run++ def _status():+ out = real_status()+ if out.get("loaded"):+ out["supports_guidance"] = supports_guidance+ return out++ def _generate(+ *,+ prompt: str,+ negative_prompt: Optional[str] = None,+ width: Optional[int] = 1024,+ height: Optional[int] = 1024,+ seed: Optional[int] = None,+ guidance: float = 0.0,+ expected_load: Any = None,+ ) -> dict:+ return real_run(expected_load, {"prompt": prompt, "guidance": guidance, "seed": seed})++ monkeypatch.setattr(rig.mlx, "status", _status)+ monkeypatch.setattr(rig.mlx, "generate", _generate)+++def test_explicit_guidance_the_mlx_variant_drops_runs_on_diffusers(rig, monkeypatch):+ _guidance_distilled_mlx(rig, monkeypatch, supports_guidance = False)+ assert _txt2img(rig.engine, guidance = 0.0, negative_prompt = "blurry")["engine"] == "mlx"+ assert _txt2img(rig.engine)["engine"] == "mlx"+ assert ("diffusers", "load") not in rig.log+ result = _txt2img(rig.engine, guidance = 4.0, negative_prompt = "blurry")+ assert result["engine"] == "diffusers"+ assert ("diffusers", "load") in rig.log+++def test_explicit_guidance_stays_on_an_mlx_variant_that_applies_it(rig, monkeypatch):+ _guidance_distilled_mlx(rig, monkeypatch, supports_guidance = True)+ assert _txt2img(rig.engine, guidance = 4.0, negative_prompt = "blurry")["engine"] == "mlx"+ assert ("diffusers", "load") not in rig.log+++def test_explicit_guidance_without_a_fallback_is_refused_not_dropped(rig, monkeypatch):+ _guidance_distilled_mlx(rig, monkeypatch, supports_guidance = False)+ monkeypatch.setattr(families, "family_pipeline_available", lambda _f: False)+ with pytest.raises(ValueError, match = "guidance .* is not supported on the MLX engine"):+ _txt2img(rig.engine, guidance = 4.0)+ assert ("mlx", "generate") not in rig.log+ assert _txt2img(rig.engine, guidance = 0.0)["engine"] == "mlx"+++def test_status_offers_the_fallback_guidance_controls_over_a_turbo_mlx_variant(rig, monkeypatch):+ # A guided request routes to diffusers, so the routed status advertises what diffusers serves.+ _guidance_distilled_mlx(rig, monkeypatch, supports_guidance = False)+ z_image = next(f for f in families._FAMILIES if f.name == "z-image")+ monkeypatch.setattr(rig.engine, "_family", lambda: z_image)+ monkeypatch.setattr(rig.engine, "_capabilities_fn", routing._diffusers_capabilities)+ status = rig.engine.status()+ assert status["engine"] == "mlx"+ assert status["supports_guidance"] is True+ assert status["supports_negative_prompt"] is True+ assert status["negative_prompt_min_guidance"] == 0.0+ assert rig.engine._mlx_guidance() is False+ assert _txt2img(rig.engine, guidance = 4.0, negative_prompt = "blurry")["engine"] == "diffusers"+++def test_an_mlx_variant_that_applies_guidance_keeps_its_own_thresholds(rig, monkeypatch):+ _guidance_distilled_mlx(rig, monkeypatch, supports_guidance = True)+ real_status = rig.mlx.status++ def _status():+ out = real_status()+ out.update(supports_negative_prompt = True, negative_prompt_min_guidance = 1.0)+ return out++ monkeypatch.setattr(rig.mlx, "status", _status)+ monkeypatch.setattr(+ rig.engine,+ "_capabilities_fn",+ lambda fam: {"workflows": ["txt2img", "img2img"], "negative_prompt_min_guidance": 0.0},+ )+ assert rig.engine.status()["negative_prompt_min_guidance"] == 1.0+++def test_an_unload_racing_a_failing_fallback_never_leaves_mlx_resident(rig):+ rig.diffusers.hang_load = True+ worker, outcome = _in_thread(lambda: _img2img(rig.engine))+ deadline = time.time() + 5+ while not rig.diffusers._loading and time.time() < deadline:+ time.sleep(0.01)+ assert rig.diffusers._loading and rig.mlx._state is None+ real_unload = rig.mlx.unload++ def _unload_then_fail_the_fallback(**kwargs):+ result = real_unload(**kwargs)+ rig.diffusers._load_error = "out of memory"+ worker.join(5)+ return result++ rig.mlx.unload = _unload_then_fail_the_fallback+ status = rig.engine.unload()+ worker.join(5)+ assert not worker.is_alive() and isinstance(outcome[0], RuntimeError), outcome+ assert status["loaded"] is False+ assert rig.mlx._state is None+ assert rig.diffusers._state is None+++def test_a_unified_memory_refusal_of_the_fallback_keeps_its_error_code(rig):+ from core.inference.diffusion_memory import (+ UNIFIED_OVERSIZE_REFUSAL_CODE,+ unified_memory_refusal_code,+ )++ real_progress = rig.diffusers.load_progress++ def _progress():+ out = real_progress()+ if out.get("phase") == "error":+ out["error_code"] = UNIFIED_OVERSIZE_REFUSAL_CODE+ return out++ rig.diffusers.load_progress = _progress+ rig.diffusers.fail_next_load = "needs about 30 GB of unified memory"+ with pytest.raises(RuntimeError, match = "unified memory") as excinfo:+ _img2img(rig.engine)+ assert unified_memory_refusal_code(excinfo.value) == UNIFIED_OVERSIZE_REFUSAL_CODE+ assert rig.engine.status()["engine_routing"]["resident"] == ["mlx"]+++_Z_TURBO_SCHEDULER = {+ "_class_name": "FlowMatchEulerDiscreteScheduler",+ "_diffusers_version": "0.36.0.dev0",+ "num_train_timesteps": 1000,+ "use_dynamic_shifting": False,+ "shift": 3.0,+}+_Z_BASE_SCHEDULER = {**_Z_TURBO_SCHEDULER, "shift": 6.0}+++def _cache_base(monkeypatch, tmp_path, repo: str, files: dict) -> None:+ import json++ from huggingface_hub import constants++ import utils.hf_cache_settings as cache_settings++ root = tmp_path / "hub"+ folder = root / f"models--{repo.replace('/', '--')}"+ snapshot = folder / "snapshots" / ("0" * 40)+ for name, content in files.items():+ path = snapshot / name+ path.parent.mkdir(parents = True, exist_ok = True)+ path.write_text(json.dumps(content), encoding = "utf-8")+ (folder / "refs").mkdir(parents = True, exist_ok = True)+ (folder / "refs" / "main").write_text("0" * 40, encoding = "utf-8")+ monkeypatch.setattr(cache_settings, "active_hf_hub_cache", lambda: str(root))+ monkeypatch.setattr(constants, "HF_HUB_CACHE", str(root))+++def _expected_shift_control(config: dict) -> Optional[dict]:+ from diffusers import FlowMatchEulerDiscreteScheduler++ from core.inference.diffusion_flow_shift import apply_comfy_flow_shift, shift_control++ pipe = SimpleNamespace(scheduler = FlowMatchEulerDiscreteScheduler.from_config(config))+ apply_comfy_flow_shift(pipe, 3.0)+ return shift_control("sd3", pipe.scheduler)+++def _z_image_rig(rig, monkeypatch):+ z_image = next(f for f in families._FAMILIES if f.name == "z-image")+ monkeypatch.setattr(rig.engine, "_family", lambda: z_image)+ return z_image++[email protected]("config", [_Z_TURBO_SCHEDULER, _Z_BASE_SCHEDULER], ids = ["turbo", "base"])+def test_status_offers_the_fallback_shift_control_from_the_cached_scheduler(+ rig, monkeypatch, tmp_path, config+):+ pytest.importorskip("diffusers")+ _z_image_rig(rig, monkeypatch)+ _cache_base(+ monkeypatch,+ tmp_path,+ "Tongyi-MAI/Z-Image-Turbo",+ {+ "scheduler/scheduler_config.json": config,+ "model_index.json": {"_class_name": "ZImagePipeline"},+ },+ )+ status = rig.engine.status()+ assert status["engine"] == "mlx"+ expected = _expected_shift_control(config)+ assert expected == {"node": "sd3", "shift": 3.0}+ assert status["shift_control"] == expected+ assert _txt2img(rig.engine, shift = 3.0)["engine"] == "diffusers"+++def test_fallback_shift_control_reads_a_local_base_dir(rig, monkeypatch, tmp_path):+ pytest.importorskip("diffusers")+ import json++ z_image = _z_image_rig(rig, monkeypatch)+ (tmp_path / "scheduler").mkdir()+ (tmp_path / "scheduler" / "scheduler_config.json").write_text(json.dumps(_Z_BASE_SCHEDULER))+ status = {"repo_id": "unsloth/Z-Image-GGUF", "base_repo": str(tmp_path)}+ assert routing.fallback_shift_control(z_image, status) == _expected_shift_control(+ _Z_BASE_SCHEDULER+ )+++def test_status_hides_shift_when_the_scheduler_config_is_not_cached(rig, monkeypatch, tmp_path):+ _z_image_rig(rig, monkeypatch)+ _cache_base(monkeypatch, tmp_path, "Tongyi-MAI/Z-Image-Turbo", {"model_index.json": {}})+ assert rig.engine.status().get("shift_control") is None+++def test_status_hides_shift_when_the_base_ships_a_sampling_grid(rig, monkeypatch, tmp_path):+ _z_image_rig(rig, monkeypatch)+ _cache_base(+ monkeypatch,+ tmp_path,+ "Tongyi-MAI/Z-Image-Turbo",+ {+ "scheduler/scheduler_config.json": _Z_TURBO_SCHEDULER,+ "model_index.json": {"sample_sigmas": [1.0, 0.75, 0.5, 0.25]},+ },+ )+ assert rig.engine.status().get("shift_control") is None+++def test_an_mlx_reported_shift_control_is_kept(rig, monkeypatch, tmp_path):+ _z_image_rig(rig, monkeypatch)+ _cache_base(+ monkeypatch,+ tmp_path,+ "Tongyi-MAI/Z-Image-Turbo",+ {"scheduler/scheduler_config.json": _Z_TURBO_SCHEDULER},+ )+ real_status = rig.mlx.status+ own = {"node": "sd3", "shift": 5.0}+ monkeypatch.setattr(rig.mlx, "status", lambda: {**real_status(), "shift_control": own})+ assert rig.engine.status()["shift_control"] == own+++def test_no_fallback_no_shift_control(rig, monkeypatch, tmp_path):+ _z_image_rig(rig, monkeypatch)+ _cache_base(+ monkeypatch,+ tmp_path,+ "Tongyi-MAI/Z-Image-Turbo",+ {"scheduler/scheduler_config.json": _Z_TURBO_SCHEDULER},+ )+ monkeypatch.setattr(families, "family_pipeline_available", lambda _f: False)+ assert rig.engine.status().get("shift_control") is None