Skip to content

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

Assert the image family's pipeline class in the training preflight, before the GPU teardown (#8236)

Daniel Hanbcfc62657b62
diff --git a/pyproject.toml b/pyproject.toml
index 4188fa9da67..7587d0b8acb 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -144,7 +144,7 @@ huggingfacenotorch = [
# workflow raises without it), the cache_context child-registry behavior, and the
# Flux2 / Z-Image pipelines. An unversioned entry let an upgrade keep an older
# diffusers, so advertised models failed to load until the user upgraded by hand.
- # diffusers dropped 3.9 in 0.38, and we still support it (requires-python >= 3.9),
+ # diffusers dropped 3.9 in 0.37, and we still support it (requires-python >= 3.9),
# so the floor is conditional: pinning it outright leaves pip no candidate at all
# on 3.9 and the whole extra becomes unresolvable.
"diffusers>=0.39.0 ; python_version >= '3.10'",
diff --git a/studio/backend/core/inference/diffusion_families.py b/studio/backend/core/inference/diffusion_families.py
index fb983cc7147..4ab5604887e 100644
--- a/studio/backend/core/inference/diffusion_families.py
+++ b/studio/backend/core/inference/diffusion_families.py
@@ -770,18 +770,133 @@ def family_prequant_repo(
return None
-def assert_pipeline_class_available(pipeline_class: str, family_name: str) -> None:
+# The release where diffusers' own requires-python went ">= 3.10.0", which makes 0.36.0 the newest
+# a supported Python 3.9 host can resolve.
+_DIFFUSERS_DROPPED_PY39 = "0.37.0"
+
+# First diffusers release exporting each pipeline class, read off ``src/diffusers/__init__.py`` at
+# the upstream tags and cross-checked against each release's requires-python on PyPI. An unlisted
+# class gets a version-free "a newer diffusers" instead of a number, since the ones left out are
+# older than any release in play. This exists so the remedy is true: telling a
+# 3.9 host that Z-Image needs Python >= 3.10 sends it to upgrade the interpreter when
+# ``pip install -U diffusers`` (0.36.0 there) would have been enough.
+_PIPELINE_MIN_DIFFUSERS: dict[str, str] = {
+ "Flux2Pipeline": "0.36.0",
+ "ZImagePipeline": "0.36.0",
+ "ZImageImg2ImgPipeline": "0.36.0",
+ "HunyuanImagePipeline": "0.36.0",
+ "HunyuanVideo15Pipeline": "0.36.0",
+ "QwenImageControlNetPipeline": "0.36.0",
+ "QwenImageEditPlusPipeline": "0.36.0",
+ "Flux2KleinPipeline": "0.37.0",
+ "ZImageInpaintPipeline": "0.37.0",
+ "LTX2Pipeline": "0.37.0",
+ "Flux2KleinInpaintPipeline": "0.38.0",
+ "Ideogram4Pipeline": "0.39.0",
+ "Krea2Pipeline": "0.39.0",
+ # Older than the 0.35 baseline, but listed anyway: the packaging leaves an UNCONSTRAINED
+ # diffusers installable below 3.10, so an already-present ancient one satisfies the pin, and
+ # quoting the 0.39 floor at a family that has existed since 0.30 is the same wrong remedy.
+ "QwenImagePipeline": "0.35.0",
+ "QwenImageImg2ImgPipeline": "0.35.0",
+ "QwenImageInpaintPipeline": "0.35.0",
+ "FluxPipeline": "0.30.0",
+ "FluxImg2ImgPipeline": "0.30.0",
+ "FluxInpaintPipeline": "0.30.0",
+}
+
+
+def _version_tuple(v: str) -> tuple[int, ...]:
+ """``"0.37.0" -> (0, 37, 0)`` for ordering. Numeric so 0.9 sorts below 0.10, which a string
+ compare gets backwards; a non-numeric part stops the parse rather than raising."""
+ out: list[int] = []
+ for part in str(v).split("."):
+ if not part.isdigit():
+ break
+ out.append(int(part))
+ return tuple(out)
+
+
+def pipeline_class_requirement(pipeline_class: str) -> tuple[Optional[str], bool]:
+ """``(minimum diffusers version, whether that minimum also needs Python >= 3.10)``.
+
+ ``None`` for a class with no entry. That is deliberately not the packaging floor: an unlisted
+ class is one old enough that no release in play lacks it (StableDiffusionXLPipeline goes back
+ past 0.29), so naming 0.39 would send a supported Python 3.9 host to upgrade its interpreter
+ for a class every diffusers it can install already has. Without an entry the refusal says
+ "a newer diffusers" and stops there, which is true whatever the class."""
+ minimum = _PIPELINE_MIN_DIFFUSERS.get(pipeline_class)
+ if minimum is None:
+ return None, False
+ return minimum, _version_tuple(minimum) >= _version_tuple(_DIFFUSERS_DROPPED_PY39)
+
+
+def _too_old_message(pipeline_class: str, family_name: str, installed: str) -> str:
+ """The refusal text: what is missing, what is installed, and a remedy this interpreter can
+ actually carry out."""
+ minimum, needs_py310 = pipeline_class_requirement(pipeline_class)
+ if minimum is None:
+ return (
+ f"'{family_name}' needs a newer diffusers ({pipeline_class}); this environment has "
+ f"diffusers {installed}. Upgrade with: pip install -U diffusers."
+ )
+ remedy = f"Upgrade with: pip install -U 'diffusers>={minimum}'."
+ if needs_py310:
+ remedy += (
+ f" diffusers dropped Python 3.9 in {_DIFFUSERS_DROPPED_PY39}, so that release needs "
+ f"Python >= 3.10 too."
+ )
+ return (
+ f"'{family_name}' needs diffusers >= {minimum} ({pipeline_class}); this environment has "
+ f"diffusers {installed}. {remedy}"
+ )
+
+
+def _dummy_required_backends(cls: object) -> tuple[str, ...]:
+ """The backends diffusers says ``cls`` REQUIRES, when ``cls`` is one of its placeholders.
+
+ Required, not missing: ``_backends`` is the class's full requirement list, so a placeholder
+ standing in because transformers is absent still lists torch beside it. Naming them all as
+ missing, and prescribing a reinstall, is how you tell someone with a working ROCm or CUDA
+ build of torch to replace it.
+
+ With a required backend absent (torch, transformers, ...), diffusers still EXPORTS every
+ pipeline name, as a ``DummyObject``-metaclassed stand-in from ``diffusers.utils.dummy_*``
+ whose ``from_pretrained`` raises ``ImportError`` on the first call. ``hasattr`` therefore
+ answers True for a class that cannot be used, which is exactly the "importable" answer the
+ strict gate must not accept. Empty tuple for a real class."""
+ if not str(getattr(cls, "__module__", "")).startswith("diffusers.utils.dummy"):
+ return ()
+ backends = getattr(cls, "_backends", None) or ()
+ return tuple(str(b) for b in backends)
+
+
+def assert_pipeline_class_available(
+ pipeline_class: str,
+ family_name: str,
+ *,
+ strict: bool = False,
+) -> None:
"""Raise ``ValueError`` before any download when the installed diffusers has no
``pipeline_class``.
- The newer families (Flux2Klein, Z-Image, Krea 2, LTX-2, HunyuanImage) only exist from diffusers
- 0.39, and the packaging leaves an older diffusers installable on Python 3.9 -- diffusers dropped
- 3.9 in 0.38 and this project still supports it, so the 0.39 floor has to be conditional or the
- whole extra becomes unresolvable. Without this check the getattr chain died with a bare
+ The newer families (Flux2Klein, Z-Image, Krea 2, LTX-2, HunyuanImage) only exist from a
+ diffusers newer than the 0.35 baseline, and the packaging leaves an older one installable on
+ Python 3.9 -- diffusers dropped 3.9 in 0.37 and this project still supports it, so the 0.39
+ floor has to be conditional or the whole extra becomes unresolvable. Which release a family
+ needs differs per class, so the refusal reads it from ``_PIPELINE_MIN_DIFFUSERS`` rather than
+ quoting the floor at everyone. Without this check the getattr chain died with a bare
AttributeError deep in the load, after the checkpoint had already been fetched, which is an
expensive way to learn the environment is too old. Krea 2 already guarded itself this way; this
is the same check for every family, run from validation.
+ ``strict`` decides what an *unimportable* diffusers means. Inference (the default) stays
+ silent: it only answers "is the installed diffusers new enough", and the native sd.cpp engine
+ serves GGUF picks on a CPU or Apple host that has no diffusers at all. Training passes
+ ``strict = True``, because its child is an ``mp.get_context("spawn")`` process in the SAME
+ interpreter -- an import that fails here fails there too, only after the route has reserved the
+ training slot and freed the resident GPU models.
+
``ValueError``, like every other unloadable-pick refusal ``validate_load_request`` raises, so
the routes map it to 400 with the message intact. A ``RuntimeError`` instead reached
``/images/load``'s 409 (the code that otherwise means "a load is already in progress") and
@@ -790,26 +905,46 @@ def assert_pipeline_class_available(pipeline_class: str, family_name: str) -> No
try:
import diffusers
present = hasattr(diffusers, pipeline_class)
- except Exception: # noqa: BLE001 -- see below: this check must never raise anything but its own ValueError
- # Not this check's business: it answers "is the installed diffusers new enough for this family", and with
- # nothing importable there is no version to judge. Refusing would also break the native sd.cpp engine, which
- # serves GGUF picks on a CPU or Apple host without diffusers. A pick that really needs it fails later, in
- # the loader. The one thing that must not happen is a raise: ModuleNotFoundError is not the ValueError the
- # routes map to 400, so it escapes /images/download-plan as a bare 500 with the message lost.
+ dummy_backends = _dummy_required_backends(getattr(diffusers, pipeline_class, None))
+ except Exception as exc: # noqa: BLE001 -- see below: this check must never raise anything but its own ValueError
+ # Not this check's business under the default: it answers "is the installed diffusers new enough for this
+ # family", and with nothing importable there is no version to judge. Refusing would also break the native
+ # sd.cpp engine, which serves GGUF picks on a CPU or Apple host without diffusers. A pick that really needs
+ # it fails later, in the loader. The one thing that must not happen is a raise of the wrong type:
+ # ModuleNotFoundError is not the ValueError the routes map to 400, so it escapes /images/download-plan as a
+ # bare 500 with the message lost.
#
# The attribute probe is inside the try for the same reason. diffusers' top level is a lazy module, so
# ``hasattr`` is what actually imports the pipeline's submodule, and when that submodule's own dependencies
# are unsatisfiable it raises RuntimeError ("Failed to import diffusers.pipelines...") -- which hasattr does
# NOT swallow, since it only absorbs AttributeError. A partially usable diffusers install therefore escaped
# this guard exactly the way a missing one used to.
+ if strict:
+ raise ValueError(
+ f"'{family_name}' needs diffusers ({pipeline_class}), which this environment "
+ f"cannot import: {exc}. Install or repair it with: pip install -U diffusers."
+ ) from None
return
+ if present and dummy_backends:
+ # A placeholder, not the pipeline. Under the default this is left alone like every other
+ # unusable install; strict refuses, because the trainer child imports the same placeholder
+ # and its from_pretrained raises only after the GPU residents are gone.
+ if not strict:
+ return
+ raise ValueError(
+ f"'{family_name}' needs diffusers ({pipeline_class}), but this diffusers exports it as "
+ f"a placeholder, which it does when a backend it requires is unavailable. That class "
+ f"requires: {', '.join(dummy_backends)}. Check which of those this environment is "
+ f"missing and install it."
+ )
+
if present:
return
raise ValueError(
- f"'{family_name}' needs diffusers >= 0.39.0 ({pipeline_class}); this environment has "
- f"diffusers {getattr(diffusers, '__version__', 'unknown')}. Upgrade with: "
- f"pip install -U diffusers (which needs Python >= 3.10; diffusers dropped 3.9 in 0.38)."
+ _too_old_message(
+ pipeline_class, family_name, str(getattr(diffusers, "__version__", "unknown"))
+ )
)
@@ -818,7 +953,7 @@ def family_pipeline_available(fam: Optional[DiffusionFamily]) -> bool:
The boolean twin of ``assert_pipeline_class_available``, for the listing routes: the newer
families exist only from diffusers 0.39, and the packaging leaves an older diffusers
- installable on Python 3.9 (diffusers dropped 3.9 in 0.38, so the 0.39 floor has to be
+ installable on Python 3.9 (diffusers dropped 3.9 in 0.37, so the 0.39 floor has to be
conditional or the extra becomes unresolvable). Advertising Z-Image or Krea 2 in the picker
on such an environment offers a pick that can only fail, and no `pip install -U diffusers`
can fix it without also upgrading Python. Fails OPEN (True) when diffusers cannot be
diff --git a/studio/backend/core/training/diffusion_train_common.py b/studio/backend/core/training/diffusion_train_common.py
index bd481ea50a3..6335818213e 100644
--- a/studio/backend/core/training/diffusion_train_common.py
+++ b/studio/backend/core/training/diffusion_train_common.py
@@ -87,6 +87,61 @@ def _trainable_hint() -> str:
)
+def _assert_family_pipeline_available(fam: Any) -> None:
+ """Refuse a family whose pipeline class the installed diffusers does not carry.
+
+ ``pyproject`` deliberately leaves the diffusers floor conditional -- diffusers dropped Python
+ 3.9 in 0.37 and this project still supports 3.9 (``requires-python >= 3.9``), so the pin reads
+ ``diffusers>=0.39.0 ; python_version >= '3.10'`` and an unconstrained ``diffusers`` below that.
+ A supported install can therefore legitimately predate a family's pipeline class:
+ ``Krea2Pipeline`` arrived in 0.39.0 and ``Flux2KleinPipeline`` in 0.37.0, while the newest
+ diffusers a 3.9 host can resolve is 0.36.0, and an already-present older one satisfies the
+ unconstrained pin outright (``ZImagePipeline`` and ``Flux2Pipeline`` only arrived in 0.36.0).
+
+ The inference paths already assert this before a load (``diffusion.py`` and ``video.py``); the
+ training preflight did not, so the family resolved as trainable, ``/diffusion/start`` reserved
+ the training slot and freed the resident GPU workloads, and only the spawned child discovered
+ the pipeline was missing when it ran its own ``from diffusers import <Pipeline>``. Losing a
+ loaded model and THEN failing is the worst ordering available, so assert here, while
+ ``resolve_trainable_family`` still runs ahead of every teardown.
+
+ Not strict: an unimportable diffusers is left to ``training_pipeline_import_error`` below.
+ ``resolve_trainable_family`` runs from ``normalized()``, which is pure config validation and is
+ called in plenty of places that never train, so making it depend on a working diffusers import
+ would refuse configs over an unrelated environment problem.
+
+ Family-agnostic on purpose: it reads ``fam.pipeline_class`` off whatever spec it is handed, so
+ the image registry and the separate video registry share one gate rather than one each."""
+ from core.inference.diffusion_families import assert_pipeline_class_available
+ assert_pipeline_class_available(fam.pipeline_class, fam.name)
+
+
+def training_pipeline_import_error(resolved_family: str) -> Optional[str]:
+ """The reason this host cannot import ``resolved_family``'s pipeline class, or None.
+
+ The strict half of the gate above, and it belongs to the ROUTE rather than to config
+ validation. ``assert_pipeline_class_available`` deliberately absorbs an unimportable diffusers
+ for inference -- the native sd.cpp engine serves GGUF picks on a CPU or Apple host that has
+ none. Training has no such fallback: its child is an ``mp.get_context("spawn")`` process in the
+ SAME interpreter, so a diffusers that cannot be imported here cannot be imported there either.
+ Staying silent bought nothing but the ordering this whole preflight exists to prevent: the slot
+ reserved, the resident GPU models freed, and only then the child failing on its own
+ ``from diffusers import <Pipeline>``.
+
+ Returns the message instead of raising, matching ``training_precision_preflight_error``, so the
+ route maps it to its own 400."""
+ from core.inference.diffusion_families import assert_pipeline_class_available, detect_family
+
+ fam = detect_family("", override = str(resolved_family or "").strip().lower())
+ if fam is None:
+ return None
+ try:
+ assert_pipeline_class_available(fam.pipeline_class, fam.name, strict = True)
+ except ValueError as e:
+ return str(e)
+ return None
+
+
def resolve_trainable_family(base_model: str, model_family: Optional[str] = None) -> str:
"""Resolve the trainer family for a base model, or raise ValueError with a clear reason.
@@ -98,8 +153,13 @@ def resolve_trainable_family(base_model: str, model_family: Optional[str] = None
family (e.g. a DiT family before its trainer ships) is rejected;
- a name that resolves to no registry family but matches a known non-trainable
architecture (SD3 / PixArt / ...) is rejected;
+ - a resolved family whose pipeline class the installed diffusers lacks is rejected
+ (``_assert_family_pipeline_available``), so an environment too old for the pick fails
+ here rather than in the child, after the GPU residents are gone;
- an unclassifiable custom name/path falls through to the SDXL trainer (backwards
compatible: a genuinely wrong pick still fails cleanly later in from_pretrained).
+ No pipeline assert on that path: there is no family spec to read a class off, and the
+ family it lands on is SDXL, whose pipeline predates every diffusers in play.
"""
name = str(base_model or "").strip().lower()
# GGUF weights (a ``.gguf`` file or ``*-GGUF`` repo) are inference-only: training needs the full diffusers pipeline.
@@ -119,6 +179,7 @@ def resolve_trainable_family(base_model: str, model_family: Optional[str] = None
raise ValueError(f"Unknown model_family {model_family!r}. Known families: {known}.")
if not fam.trainable:
raise ValueError(f"'{fam.name}' models can't be trained yet. {_trainable_hint()}")
+ _assert_family_pipeline_available(fam)
return fam.name
fam = detect_family_for_pick(base_model)
@@ -128,6 +189,7 @@ def resolve_trainable_family(base_model: str, model_family: Optional[str] = None
f"'{base_model}' looks like a {fam.name} model, which isn't trainable yet. "
f"{_trainable_hint()}"
)
+ _assert_family_pipeline_available(fam)
return fam.name
condensed = re.sub(r"[^a-z0-9]+", "-", name)
diff --git a/studio/backend/routes/training.py b/studio/backend/routes/training.py
index 32890fa127b..bad23ca8fb7 100644
--- a/studio/backend/routes/training.py
+++ b/studio/backend/routes/training.py
@@ -2777,6 +2777,15 @@ async def start_diffusion_training(
if _precision_reason:
raise HTTPException(status_code = 400, detail = _precision_reason)
+ # The trainer child imports the family's pipeline itself, in a spawn of THIS interpreter, so a
+ # diffusers that cannot be imported here cannot be imported there either. Refuse now, while the
+ # GPU residents are still loaded, rather than after the teardown below frees them.
+ from core.training.diffusion_train_common import training_pipeline_import_error
+
+ _pipeline_reason = training_pipeline_import_error(normalized_cfg.resolved_family)
+ if _pipeline_reason:
+ raise HTTPException(status_code = 400, detail = _pipeline_reason)
+
# Preflight a resume request in the same place and for the same reason: a checkpoint from a
# different family / base / LoRA shape / precision must 400 BEFORE the resident GPU model is
# evicted, not fail in the child once the user's Images pipeline is already gone. The dataset
diff --git a/studio/backend/tests/conftest.py b/studio/backend/tests/conftest.py
index 7970098f53e..d9415374d83 100644
--- a/studio/backend/tests/conftest.py
+++ b/studio/backend/tests/conftest.py
@@ -747,3 +747,41 @@ def _reset_optional_module_memo():
_shim._reset_optional_module_cache()
yield
_shim._reset_optional_module_cache()
+
+
+def healthy_diffusers(monkeypatch):
+ """A diffusers that answers any pipeline class, for tests about a route rather than a cast.
+
+ The training route asserts the family's pipeline class strictly before it frees the resident
+ GPU models, so a runner whose diffusers cannot import (a transformers/huggingface-hub pin skew
+ is the common one: the lazy top level then raises RuntimeError instead of answering hasattr)
+ would turn every routing and config test into a 400 about diffusers. This is a PROXY, not a
+ replacement: everything the real module can still serve is delegated, including ``__path__`` so
+ ``from diffusers.optimization import ...`` keeps working, and only a pipeline class it cannot
+ produce is answered here. Tests that DO exercise the gate replace ``sys.modules["diffusers"]``
+ themselves, which runs after this and wins."""
+ import types
+
+ try:
+ import diffusers as _real
+ except Exception: # noqa: BLE001 -- an absent diffusers is exactly what this stands in for
+ _real = None
+
+ class _AnyPipeline(types.ModuleType):
+ def __getattr__(self, name):
+ if _real is not None:
+ try:
+ return getattr(_real, name)
+ except Exception: # noqa: BLE001 -- the lazy submodule is what may be broken
+ pass
+ if name.endswith("Pipeline"):
+ return object
+ raise AttributeError(name)
+
+ proxy = _AnyPipeline("diffusers")
+ proxy.__version__ = str(getattr(_real, "__version__", "0.39.0"))
+ for attr in ("__path__", "__file__", "__spec__", "__loader__"):
+ if _real is not None and hasattr(_real, attr):
+ setattr(proxy, attr, getattr(_real, attr))
+ monkeypatch.setitem(sys.modules, "diffusers", proxy)
diff --git a/studio/backend/tests/test_cached_gguf_routes.py b/studio/backend/tests/test_cached_gguf_routes.py
index 2d756b4ecb6..64fa82bf564 100644
--- a/studio/backend/tests/test_cached_gguf_routes.py
+++ b/studio/backend/tests/test_cached_gguf_routes.py
@@ -3232,13 +3232,14 @@ def test_hub_local_rows_are_tagged_with_their_task():
def test_pipeline_class_guard_fires_before_any_download():
- # The 0.39-only families used to die with a bare AttributeError deep in the load, after the checkpoint was fetched, on
+ # The newer families used to die with a bare AttributeError deep in the load, after the checkpoint was fetched, on
# the older diffusers packaging still allows on Python 3.9. Validation refuses first, naming the version and the fix.
+ # 0.35.2 is the last release before ZImagePipeline existed, and it is still installable on 3.9.
import pytest
from core.inference.diffusion_families import assert_pipeline_class_available
- stub = types.SimpleNamespace(__version__ = "0.37.0")
+ stub = types.SimpleNamespace(__version__ = "0.35.2")
real = sys.modules.get("diffusers")
sys.modules["diffusers"] = stub
try:
@@ -3252,8 +3253,25 @@ def test_pipeline_class_guard_fires_before_any_download():
del sys.modules["diffusers"]
msg = str(excinfo.value)
assert "z-image" in msg and "ZImagePipeline" in msg
- assert "0.39" in msg and "0.37.0" in msg
- assert "3.10" in msg # names the Python floor that carries a new enough diffusers
+ # The release that family actually needs (0.36.0), not the blanket packaging floor, and what is installed.
+ assert "0.36.0" in msg and "0.35.2" in msg
+ # And NOT a Python upgrade: 0.36.0 still declares requires-python >= 3.8, so `pip install -U
+ # diffusers` alone fixes this on a 3.9 host. Sending it to 3.10 would be the wrong remedy.
+ assert "3.10" not in msg
+
+ # Krea 2 is the other side: its class only exists from 0.39.0, which needs 3.10 -- so the
+ # Python floor belongs in THAT message.
+ sys.modules["diffusers"] = stub
+ try:
+ with pytest.raises(ValueError) as excinfo:
+ assert_pipeline_class_available("Krea2Pipeline", "krea-2")
+ finally:
+ if real is not None:
+ sys.modules["diffusers"] = real
+ else:
+ del sys.modules["diffusers"]
+ krea = str(excinfo.value)
+ assert "0.39.0" in krea and "3.10" in krea
def test_pipeline_class_guard_passes_every_shipped_family():
diff --git a/studio/backend/tests/test_diffusion_checkpoint_resume.py b/studio/backend/tests/test_diffusion_checkpoint_resume.py
index 7b3818d7306..09fa1c3c836 100644
--- a/studio/backend/tests/test_diffusion_checkpoint_resume.py
+++ b/studio/backend/tests/test_diffusion_checkpoint_resume.py
@@ -120,6 +120,12 @@ class _Run:
)
[email protected](autouse = True)
+def _healthy_diffusers(healthy_diffusers):
+ """The resume route runs the same preflight as start, which asserts the family's pipeline
+ class strictly; these tests are about resume, not about the runner's diffusers."""
+
+
@pytest.fixture
def run_dir(tmp_path, monkeypatch):
"""A run output directory inside the (per-test) Studio outputs root, since the resume
diff --git a/studio/backend/tests/test_diffusion_training.py b/studio/backend/tests/test_diffusion_training.py
index 1a226ad4c7d..d84f5fdedb2 100644
--- a/studio/backend/tests/test_diffusion_training.py
+++ b/studio/backend/tests/test_diffusion_training.py
@@ -67,6 +67,11 @@ class _FakeCtx:
return _FakeProc(target, kwargs, daemon)
[email protected](autouse = True)
+def _healthy_diffusers(healthy_diffusers):
+ """Every test here is about the route or the config, not about the runner's diffusers."""
+
+
@pytest.fixture(autouse = True)
def _isolated_runs_dir(monkeypatch, tmp_path):
"""Terminal service events persist a run record; point the runs dir at tmp so tests
@@ -1409,6 +1414,297 @@ def test_route_start_refuses_non_sdxl_base_without_freeing_gpu(client, monkeypat
assert client._fake.started_with is None
+# ── the pipeline-class gate in the training preflight ─────────────────────────
+# The image families' pipeline classes arrived in different diffusers releases, and the packaging
+# deliberately leaves an older diffusers installable: diffusers dropped Python 3.9 in 0.37 and this
+# project still supports 3.9, so the pin is ``diffusers>=0.39.0 ; python_version >= '3.10'`` plus an
+# unconstrained ``diffusers`` below that. The newest release a 3.9 host can resolve is 0.36.0, and
+# an already-present older one satisfies the unconstrained pin outright. Upstream first exports:
+# ZImagePipeline 0.36.0, Flux2Pipeline 0.36.0, Flux2KleinPipeline 0.37.0, Krea2Pipeline 0.39.0.
+_PIPELINE_TOO_NEW_FOR_0_36 = (
+ ("krea/Krea-2-Raw", "Krea2Pipeline"),
+ ("black-forest-labs/FLUX.2-klein-4B", "Flux2KleinPipeline"),
+)
+_PIPELINE_TOO_NEW_FOR_0_35 = _PIPELINE_TOO_NEW_FOR_0_36 + (
+ ("Tongyi-MAI/Z-Image-Turbo", "ZImagePipeline"),
+ ("black-forest-labs/FLUX.2-dev", "Flux2Pipeline"),
+)
+
+
+def _fake_diffusers(version, *classes):
+ """A stand-in ``diffusers`` carrying exactly ``classes``, so the guard sees the attribute
+ surface of that release rather than whatever is installed on the runner."""
+ import types
+
+ mod = types.ModuleType("diffusers")
+ mod.__version__ = version
+ for c in classes:
+ setattr(mod, c, object)
+ return mod
+
+
[email protected]("base_model,pipeline_class", _PIPELINE_TOO_NEW_FOR_0_35)
+def test_route_start_refuses_a_family_the_install_has_no_pipeline_for(
+ client, monkeypatch, base_model, pipeline_class
+):
+ # The hole this closes: the family resolved as trainable, /diffusion/start reserved the
+ # training slot and freed the resident GPU workloads, and only the spawned child failed, on its
+ # own ``from diffusers import <Pipeline>``. Losing a loaded model and THEN failing is the worst
+ # ordering available, so this asserts the ORDERING, not merely that an error was raised:
+ # nothing freed, and the slot never even reserved.
+ import sys
+
+ import routes.training as tr
+
+ freed = []
+ monkeypatch.setattr(tr, "_free_gpu_for_diffusion_training", lambda: freed.append(1))
+ # 0.35.2: the last release before any of these four classes existed.
+ monkeypatch.setitem(sys.modules, "diffusers", _fake_diffusers("0.35.2"))
+
+ r = client.post("/api/train/diffusion/start", json = {**_BODY, "base_model": base_model})
+ assert r.status_code == 400, r.text
+ detail = r.json()["detail"]
+ assert pipeline_class in detail # names the class that is missing
+ assert "0.35.2" in detail # and what is actually installed
+ assert freed == [] # nothing was torn down
+ assert client._fake.calls == [] # the slot was never even reserved
+ assert client._fake.started_with is None
+
+
[email protected]("base_model,pipeline_class", _PIPELINE_TOO_NEW_FOR_0_36)
+def test_route_start_refuses_a_too_new_pipeline_on_the_newest_py39_diffusers(
+ client, monkeypatch, base_model, pipeline_class
+):
+ # The realistic case rather than the worst one: 0.36.0 is the newest diffusers a supported
+ # Python 3.9 host can resolve, and it already carries ZImagePipeline and Flux2Pipeline. Krea 2
+ # and FLUX.2-klein still cannot run there, and no `pip install -U diffusers` fixes it without
+ # also upgrading Python.
+ import sys
+
+ import routes.training as tr
+
+ freed = []
+ monkeypatch.setattr(tr, "_free_gpu_for_diffusion_training", lambda: freed.append(1))
+ monkeypatch.setitem(
+ sys.modules,
+ "diffusers",
+ _fake_diffusers("0.36.0", "ZImagePipeline", "Flux2Pipeline", "StableDiffusionXLPipeline"),
+ )
+
+ r = client.post("/api/train/diffusion/start", json = {**_BODY, "base_model": base_model})
+ assert r.status_code == 400, r.text
+ assert pipeline_class in r.json()["detail"]
+ assert freed == []
+ assert client._fake.calls == []
+ assert client._fake.started_with is None
+
+
+def test_route_start_refuses_a_missing_pipeline_named_by_model_family_too(client, monkeypatch):
+ # resolve_trainable_family has two branches that produce a family, and the explicit
+ # model_family override is the one a name-based test cannot reach: it skips detection entirely.
+ import sys
+
+ import routes.training as tr
+
+ freed = []
+ monkeypatch.setattr(tr, "_free_gpu_for_diffusion_training", lambda: freed.append(1))
+ monkeypatch.setitem(sys.modules, "diffusers", _fake_diffusers("0.36.0"))
+
+ r = client.post(
+ "/api/train/diffusion/start",
+ json = {**_BODY, "base_model": "my-org/some-private-mirror", "model_family": "krea-2"},
+ )
+ assert r.status_code == 400, r.text
+ assert "Krea2Pipeline" in r.json()["detail"]
+ assert freed == []
+ assert client._fake.calls == []
+ assert client._fake.started_with is None
+
+
+def test_route_start_still_runs_when_the_install_does_have_the_pipeline(
+ client, monkeypatch, dit_train_host
+):
+ # The gate must not refuse a family the environment can actually run, or it would break every
+ # up-to-date install. Same request as above, one attribute different.
+ import sys
+ import urllib.request
+
+ monkeypatch.setattr(urllib.request, "urlopen", lambda req, timeout = None: object())
+ monkeypatch.setitem(sys.modules, "diffusers", _fake_diffusers("0.39.0", "Krea2Pipeline"))
+
+ r = client.post("/api/train/diffusion/start", json = {**_BODY, "base_model": "krea/Krea-2-Raw"})
+ assert r.status_code == 200, r.text
+ assert client._fake.started_with["base_model"] == "krea/Krea-2-Raw"
+
+
+def test_route_start_refuses_a_diffusers_whose_lazy_submodule_cannot_import(client, monkeypatch):
+ # diffusers' top level is lazy, so the guard's attribute probe is what actually imports the
+ # pipeline's submodule, and a partially usable install raises RuntimeError("Failed to import
+ # diffusers.pipelines...") there. Inference absorbs that (the native sd.cpp engine needs no
+ # diffusers), but the trainer child is a spawn of THIS interpreter and would hit the same
+ # broken import -- after the GPU residents were gone. So training refuses, as a 400 with the
+ # underlying reason intact rather than the bare 500 a RuntimeError would have produced.
+ import sys
+ import types
+
+ import routes.training as tr
+
+ class _LazyModule(types.ModuleType):
+ __version__ = "0.39.0"
+
+ def __getattr__(self, name):
+ raise RuntimeError(f"Failed to import diffusers.pipelines.{name.lower()}")
+
+ freed = []
+ monkeypatch.setattr(tr, "_free_gpu_for_diffusion_training", lambda: freed.append(1))
+ monkeypatch.setitem(sys.modules, "diffusers", _LazyModule("diffusers"))
+
+ r = client.post("/api/train/diffusion/start", json = {**_BODY, "base_model": "krea/Krea-2-Raw"})
+ assert r.status_code == 400, r.text
+ detail = r.json()["detail"]
+ assert "Krea2Pipeline" in detail
+ assert "Failed to import diffusers.pipelines" in detail # the real reason, not a guess
+ assert freed == []
+ assert client._fake.calls == []
+ assert client._fake.started_with is None
+
+
+def test_route_start_refuses_training_when_diffusers_is_absent(client, monkeypatch):
+ # There is no "the child will install it" here: the trainer runs in a spawned process in the
+ # SAME environment, so an absent diffusers is absent there too. Refusing before the teardown
+ # is the whole point of this preflight.
+ import builtins
+ import sys
+
+ import routes.training as tr
+
+ real_import = builtins.__import__
+
+ def _no_diffusers(name, *args, **kwargs):
+ if name == "diffusers" or name.startswith("diffusers."):
+ raise ModuleNotFoundError("No module named 'diffusers'")
+ return real_import(name, *args, **kwargs)
+
+ freed = []
+ monkeypatch.setattr(tr, "_free_gpu_for_diffusion_training", lambda: freed.append(1))
+ monkeypatch.delitem(sys.modules, "diffusers", raising = False)
+ monkeypatch.setattr(builtins, "__import__", _no_diffusers)
+
+ r = client.post("/api/train/diffusion/start", json = {**_BODY, "base_model": "krea/Krea-2-Raw"})
+ assert r.status_code == 400, r.text
+ assert "No module named 'diffusers'" in r.json()["detail"]
+ assert freed == []
+ assert client._fake.calls == []
+
+
+def test_inference_keeps_absorbing_an_unimportable_diffusers(monkeypatch):
+ # The other half of the strict split, asserted where it lives: the default stays silent, or a
+ # CPU/Apple host serving GGUF picks through the native sd.cpp engine could not load anything.
+ import builtins
+
+ from core.inference.diffusion_families import assert_pipeline_class_available
+
+ real_import = builtins.__import__
+
+ def _no_diffusers(name, *args, **kwargs):
+ if name == "diffusers" or name.startswith("diffusers."):
+ raise ModuleNotFoundError("No module named 'diffusers'")
+ return real_import(name, *args, **kwargs)
+
+ monkeypatch.setattr(builtins, "__import__", _no_diffusers)
+ assert assert_pipeline_class_available("Krea2Pipeline", "krea-2") is None
+
+
+ "pipeline_class,minimum,needs_py310",
+ [
+ ("ZImagePipeline", "0.36.0", False),
+ ("Flux2Pipeline", "0.36.0", False),
+ ("Flux2KleinPipeline", "0.37.0", True),
+ ("LTX2Pipeline", "0.37.0", True),
+ ("Krea2Pipeline", "0.39.0", True),
+ # Older than the 0.35 baseline but still listed: the packaging leaves an UNCONSTRAINED
+ # diffusers installable below Python 3.10, so an ancient one already present satisfies the
+ # pin, and quoting the 0.39 floor at a family that has shipped since 0.30 is the same wrong
+ # remedy this fixes.
+ ("QwenImagePipeline", "0.35.0", False),
+ ("FluxPipeline", "0.30.0", False),
+ ],
+)
+def test_the_refusal_names_the_release_that_family_actually_needs(
+ pipeline_class, minimum, needs_py310
+):
+ # Quoting the 0.39 floor at every family sent a Python 3.9 host to upgrade its interpreter for
+ # Z-Image, when `pip install -U diffusers` (0.36.0 there) was the whole fix. First-export
+ # releases are read off src/diffusers/__init__.py at the upstream tags; 0.37.0 is where
+ # diffusers' requires-python went ">= 3.10.0" on PyPI.
+ from core.inference.diffusion_families import (
+ _too_old_message,
+ pipeline_class_requirement,
+ )
+
+ assert pipeline_class_requirement(pipeline_class) == (minimum, needs_py310)
+ message = _too_old_message(pipeline_class, "some-family", "0.29.0")
+ assert f"diffusers >= {minimum}" in message
+ assert "0.29.0" in message # what is actually installed
+ assert ("Python >= 3.10" in message) is needs_py310
+
+
+def test_an_unlisted_pipeline_names_no_version_it_cannot_stand_behind():
+ # StableDiffusionXLPipeline has shipped since before 0.29, so there is no release in play that
+ # lacks it. Falling back to the 0.39 packaging floor would tell a supported Python 3.9 host to
+ # upgrade its interpreter for a class every diffusers it can install already has, so an
+ # unlisted class gets no version and no Python claim at all.
+ from core.inference.diffusion_families import (
+ _too_old_message,
+ pipeline_class_requirement,
+ )
+
+ assert pipeline_class_requirement("StableDiffusionXLPipeline") == (None, False)
+ message = _too_old_message("StableDiffusionXLPipeline", "sdxl", "0.29.0")
+ assert "a newer diffusers" in message and "0.29.0" in message
+ assert "0.39" not in message and "3.10" not in message
+
+
+def test_a_dummy_pipeline_export_is_not_treated_as_importable():
+ # With a required backend absent, diffusers still exports every pipeline NAME as a
+ # DummyObject-metaclassed placeholder whose from_pretrained raises ImportError on first call.
+ # hasattr answers True for it, so the strict gate has to look past the name or the trainer
+ # child hits that ImportError after the GPU residents are gone.
+ import sys
+ import types
+
+ import pytest
+
+ from core.inference.diffusion_families import assert_pipeline_class_available
+
+ dummy = types.new_class("Krea2Pipeline")
+ dummy.__module__ = "diffusers.utils.dummy_torch_and_transformers_objects"
+ dummy._backends = ["torch", "transformers"]
+
+ stub = types.ModuleType("diffusers")
+ stub.__version__ = "0.39.0"
+ stub.Krea2Pipeline = dummy
+ real = sys.modules.get("diffusers")
+ sys.modules["diffusers"] = stub
+ try:
+ # The default is unchanged: inference has always left an unusable install to the loader.
+ assert assert_pipeline_class_available("Krea2Pipeline", "krea-2") is None
+ with pytest.raises(ValueError) as excinfo:
+ assert_pipeline_class_available("Krea2Pipeline", "krea-2", strict = True)
+ finally:
+ if real is not None:
+ sys.modules["diffusers"] = real
+ else:
+ del sys.modules["diffusers"]
+ msg = str(excinfo.value)
+ assert "placeholder" in msg
+ assert "requires: torch, transformers" in msg # what the class needs, not a diagnosis
+ # _backends is diffusers' full requirement list, not a list of failed probes, so the message
+ # must not declare a working torch missing or prescribe reinstalling it.
+ assert "missing: torch" not in msg and "pip install -U torch" not in msg
+
+
def test_route_start_refuses_non_bf16_gpu_without_freeing_gpu(client, monkeypatch):
# A DiT precision the host cannot run must 400 BEFORE the GPU residents are freed. The route imports the helper locally, so patch its home module.
import routes.training as tr