Skip to content

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

Studio: install the released Diffusers 0.41.0 instead of the pinned main commit (#13045)

Daniel Han7730160ab282
diff --git a/.github/workflows/studio-vae-seam-guard.yml b/.github/workflows/studio-vae-seam-guard.yml
index eb038eecf7a..3751d5b572d 100644
--- a/.github/workflows/studio-vae-seam-guard.yml
+++ b/.github/workflows/studio-vae-seam-guard.yml
@@ -53,9 +53,11 @@ jobs:
pip install --index-url https://download.pytorch.org/whl/cpu --extra-index-url https://pypi.org/simple \
'torch>=2.4,<2.11'
pip install -r studio/backend/requirements/studio.txt
- # As Studio installs it: the release pin, then the main commit (Qwen-Image-2.1) on top.
+ # As Studio installs it: the release, then the main commit only while that line is uncommented.
pip install -r studio/backend/requirements/diffusers-pin.txt
- pip install -r studio/backend/requirements/diffusers-main.txt
+ if grep -Eq '^[[:space:]]*[^#[:space:]]' studio/backend/requirements/diffusers-main.txt; then
+ pip install -r studio/backend/requirements/diffusers-main.txt
+ fi
pip install pytest pytest-timeout
- name: Seam guard
diff --git a/pyproject.toml b/pyproject.toml
index e87b3801a3e..8048c430517 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -166,7 +166,7 @@ studio = [
"nest_asyncio==1.6.0",
"datasets==4.3.0",
"pyjwt==2.15.1",
- "huggingface-hub>=1.31.0,<2.0 ; python_version >= '3.10'",
+ "huggingface-hub>=1.32.0,<2.0 ; python_version >= '3.10'",
"huggingface-hub==0.36.2 ; python_version < '3.10'",
"hf-xet>=1.5.2,<2.0 ; python_version >= '3.10' and (platform_machine == 'x86_64' or platform_machine == 'amd64' or platform_machine == 'AMD64' or platform_machine == 'arm64' or platform_machine == 'aarch64' or platform_machine == 'ARM64')",
"urllib3>=2.8.0 ; python_version >= '3.10'",
diff --git a/studio/backend/core/inference/diffusion.py b/studio/backend/core/inference/diffusion.py
index 1012805c9a2..ff1bd115c5b 100644
--- a/studio/backend/core/inference/diffusion.py
+++ b/studio/backend/core/inference/diffusion.py
@@ -7172,10 +7172,12 @@ class DiffusionBackend:
)
comfy_compile = comfy_torchao_quantized(transformer)
else:
- if kind != "gguf" and not hasattr(
- transformer_cls, "from_single_file"
+ if kind != "gguf" and (
+ not hasattr(transformer_cls, "from_single_file")
+ # diffusers 0.41's from_single_file rounds Krea 2's fp32 norms to bf16.
+ or getattr(transformer_cls, "__name__", "")
+ == "Krea2Transformer2DModel"
):
- # Krea 2: diffusers gives the class no single-file loader at all.
transformer = load_original_layout_transformer(
transformer_cls, single_file_path, sf_kwargs, logger
)
diff --git a/studio/backend/core/inference/diffusion_comfy_quant.py b/studio/backend/core/inference/diffusion_comfy_quant.py
index 087991c4e4f..e51e430cecb 100644
--- a/studio/backend/core/inference/diffusion_comfy_quant.py
+++ b/studio/backend/core/inference/diffusion_comfy_quant.py
@@ -606,6 +606,12 @@ def _fp8_tensor(
def _mapping(transformer_cls: Any) -> tuple[Any, Any]:
from diffusers.loaders import single_file_model as sfm
+ from .diffusion_single_file_converters import CONVERTERS
+
+ # Ahead of diffusers' own: its Krea 2 converter (0.41) strips only model.diffusion_model.
+ own = CONVERTERS.get(getattr(transformer_cls, "__name__", ""))
+ if own is not None:
+ return own, sfm
name = sfm._get_single_file_loadable_mapping_class(transformer_cls)
entry = sfm.SINGLE_FILE_LOADABLE_CLASSES.get(name or "")
if not entry:
diff --git a/studio/backend/core/inference/diffusion_families.py b/studio/backend/core/inference/diffusion_families.py
index a23fe8675ce..c8e4e1f3291 100644
--- a/studio/backend/core/inference/diffusion_families.py
+++ b/studio/backend/core/inference/diffusion_families.py
@@ -1747,7 +1747,7 @@ def local_pipeline_components_are_complete(
# Studio installs the pinned main build for exactly these classes (studio/backend/requirements/
# diffusers-main.txt), so the remedy is to put that back, not to chase a release. Delete an entry
# here the moment its version ships, which is the same moment diffusers-pin.txt moves to it.
-_UNRELEASED_MIN_DIFFUSERS = frozenset({"0.41.0"})
+_UNRELEASED_MIN_DIFFUSERS: frozenset = frozenset()
_DIFFUSERS_MAIN_PIN = Path(__file__).resolve().parents[2] / "requirements" / "diffusers-main.txt"
diff --git a/studio/backend/core/inference/diffusion_single_file_converters.py b/studio/backend/core/inference/diffusion_single_file_converters.py
index 7c581c289c8..a91cdb6d059 100644
--- a/studio/backend/core/inference/diffusion_single_file_converters.py
+++ b/studio/backend/core/inference/diffusion_single_file_converters.py
@@ -378,7 +378,7 @@ def load_original_layout_transformer(
expected, optional = transformer_cls._get_signature_keys(transformer_cls)
config.update({k: v for k, v in kwargs.items() if k in expected or k in optional})
entry = sfm.SINGLE_FILE_LOADABLE_CLASSES.get(transformer_cls.__name__) or {}
- mapping_fn = entry.get("checkpoint_mapping_fn") or CONVERTERS.get(transformer_cls.__name__)
+ mapping_fn = CONVERTERS.get(transformer_cls.__name__) or entry.get("checkpoint_mapping_fn")
if mapping_fn is None:
raise ValueError(f"{transformer_cls.__name__} has no single-file converter")
with init_empty_weights():
diff --git a/studio/backend/requirements/diffusers-main.txt b/studio/backend/requirements/diffusers-main.txt
index f666b555ee3..e06a47fbeaf 100644
--- a/studio/backend/requirements/diffusers-main.txt
+++ b/studio/backend/requirements/diffusers-main.txt
@@ -1,9 +1,12 @@
-# INSTALLED BY DEFAULT, on top of diffusers-pin.txt. Set UNSLOTH_DIFFUSERS_MAIN=0 to opt out.
+# DISABLED while diffusers-pin.txt's release carries every family: the requirement line is commented
+# out and every step of the git route does nothing. To re-enable for an unreleased model, uncomment it
+# with the new commit + archive-sha256 and add the minimum to _UNRELEASED_MIN_DIFFUSERS
+# (diffusion_families.py). When active it installs by default; UNSLOTH_DIFFUSERS_MAIN=0 opts out.
#
# A pinned commit of Diffusers main, for models whose support has merged upstream but has not
-# reached a release yet. Today that is Qwen-Image-2.1: it merged on 2026-09-18, four weeks after
-# 0.40.0 was cut, so 0.41.0 is the first release that can carry it and there is nothing on PyPI
-# that works. Without this file the only way to run it is to break the release pin by hand.
+# reached a release yet. The last one was Qwen-Image-2.1: it merged on 2026-09-18, four weeks after
+# 0.40.0 was cut, and until 0.41.0 shipped (2026-10-06) nothing on PyPI could run it. Without this
+# file the only way to run such a model is to break the release pin by hand.
#
# Why this is a SEPARATE file rather than an edit to diffusers-pin.txt, even though both now run on
# every install. That file is the single source of truth for the release everything is built
@@ -36,6 +39,5 @@
# curl -sL https://github.com/huggingface/diffusers/archive/<commit>.zip | sha256sum
# archive-sha256: 7b0d00b5b44f5ca1745d477ae4a0c2da125d58b89cff8470c422d3181a797a09
#
-# Retiring this file: once 0.41.0 ships, bump diffusers-pin.txt to it and delete this. The family
-# entry already records 0.41.0 as QwenImage21Pipeline's minimum, so nothing else has to move.
-diffusers @ git+https://github.com/huggingface/diffusers.git@80c7ed262aeffbeb43ef13ae04baeb9b84515a69
+# Retiring a pin: bump diffusers-pin.txt to the release and comment the line out (done for 0.41.0).
+# diffusers @ git+https://github.com/huggingface/diffusers.git@80c7ed262aeffbeb43ef13ae04baeb9b84515a69
diff --git a/studio/backend/requirements/diffusers-pin.txt b/studio/backend/requirements/diffusers-pin.txt
index 42c2f4fc05e..6cb2ce97fd4 100644
--- a/studio/backend/requirements/diffusers-pin.txt
+++ b/studio/backend/requirements/diffusers-pin.txt
@@ -2,16 +2,15 @@
# no other requirements file may name diffusers, and a test in
# tests/studio/install/test_diffusers_pin.py enforces that.
#
-# Diffusers 0.40.0 is the first release containing the MiniMax-H3 and MiniMax Music 3
-# modular pipelines. Keep the exact release pin so installs are reproducible without a
-# source build from GitHub.
+# 0.41.0 is the first release with Qwen-Image-2.1 (0.40.0: MiniMax-H3 / Music 3). Exact pin, so
+# installs are reproducible without a source build from GitHub.
#
# Why it is installed from its own file, in its own step: base.txt is applied near the
# start of the dependency pass. This step runs late, after every other requirements file,
# so nothing can re-resolve diffusers back to a release behind it.
#
-# python < 3.10 has no candidate: diffusers dropped 3.9 in 0.38, so pinning 0.40.0
+# python < 3.10 has no candidate: diffusers dropped 3.9 in 0.38, so pinning 0.41.0
# outright would leave the resolver nothing at all on a 3.9 host. Those hosts get the
# newest release they can take and the H3 guard refuses the model with a clear message.
-diffusers==0.40.0 ; python_version >= "3.10"
+diffusers==0.41.0 ; python_version >= "3.10"
diffusers==0.36.0 ; python_version < "3.10"
diff --git a/studio/backend/requirements/no-torch-runtime.txt b/studio/backend/requirements/no-torch-runtime.txt
index 0bdd11fc7cb..b3de86b0479 100644
--- a/studio/backend/requirements/no-torch-runtime.txt
+++ b/studio/backend/requirements/no-torch-runtime.txt
@@ -46,7 +46,7 @@ safetensors>=0.4.3
datasets>=3.4.1,!=4.0.*,!=4.1.0,!=4.4.*,!=4.5.0,<5.0.0
accelerate>=0.34.1
peft>=0.18.0,!=0.11.0
-huggingface_hub>=1.31.0,<2.0; python_version >= "3.10"
+huggingface_hub>=1.32.0,<2.0; python_version >= "3.10"
huggingface_hub==0.36.2; python_version < "3.10"
# --no-deps here, so the hub never pulls it transitively, and without it huggingface_hub refuses any
# single blob over 50GB (file_download.py, MAX_HTTP_DOWNLOAD_SIZE). Arch gate is huggingface-hub's
diff --git a/studio/backend/requirements/single-env/constraints.txt b/studio/backend/requirements/single-env/constraints.txt
index 0de0d05442e..4c94e9dedb0 100644
--- a/studio/backend/requirements/single-env/constraints.txt
+++ b/studio/backend/requirements/single-env/constraints.txt
@@ -8,7 +8,7 @@ transformers==4.57.6; python_version < "3.10"
# transformers pin, from pairing them with a tokenizers transformers rejects.
tokenizers>=0.22.0,<=0.23.0
trl==0.23.1
-huggingface-hub>=1.31.0,<2.0; python_version >= "3.10"
+huggingface-hub>=1.32.0,<2.0; python_version >= "3.10"
huggingface-hub==0.36.2; python_version < "3.10"
hf-xet>=1.5.2,<2.0; python_version >= "3.10" and (platform_machine == "x86_64" or platform_machine == "amd64" or platform_machine == "AMD64" or platform_machine == "arm64" or platform_machine == "aarch64" or platform_machine == "ARM64")
diff --git a/studio/backend/requirements/single-env/overrides-darwin-arm64.txt b/studio/backend/requirements/single-env/overrides-darwin-arm64.txt
index 01d2ae29bb8..3dcd701134f 100644
--- a/studio/backend/requirements/single-env/overrides-darwin-arm64.txt
+++ b/studio/backend/requirements/single-env/overrides-darwin-arm64.txt
@@ -42,7 +42,7 @@ anyio<4.14.0
#
# On python >= 3.10 the premise is gone: constraints.txt, studio.txt,
# no-torch-runtime.txt and the pyproject studio extra take hub 1.x, so a flat
-# <1.0 here is unsatisfiable (macOS-arm only; uv falls back to pip). 1.31.0 is
-# the floor the Diffusers main build in diffusers-main.txt declares.
-huggingface_hub>=1.31.0,<2.0; python_version >= "3.10"
+# <1.0 here is unsatisfiable (macOS-arm only; uv falls back to pip). 1.32.0 is
+# the floor the Diffusers release in diffusers-pin.txt (0.41.0) declares.
+huggingface_hub>=1.32.0,<2.0; python_version >= "3.10"
huggingface_hub>=0.34.0,<1.0; python_version < "3.10"
diff --git a/studio/backend/requirements/studio.txt b/studio/backend/requirements/studio.txt
index c76906e1e99..8ce1687b6af 100644
--- a/studio/backend/requirements/studio.txt
+++ b/studio/backend/requirements/studio.txt
@@ -20,7 +20,7 @@ nest_asyncio==1.6.0
datasets==4.3.0
pyjwt==2.15.1
# gradio>=4.0.0 # 148 MB - Unsloth uses React + FastAPI, not Gradio
-huggingface-hub>=1.31.0,<2.0; python_version >= "3.10"
+huggingface-hub>=1.32.0,<2.0; python_version >= "3.10"
huggingface-hub==0.36.2; python_version < "3.10"
# Matches no-torch-runtime.txt, the file that actually needs it; see there for the arch gate.
hf-xet>=1.5.2,<2.0; python_version >= "3.10" and (platform_machine == "x86_64" or platform_machine == "amd64" or platform_machine == "AMD64" or platform_machine == "arm64" or platform_machine == "aarch64" or platform_machine == "ARM64")
diff --git a/studio/backend/tests/test_diffusers_repair.py b/studio/backend/tests/test_diffusers_repair.py
index 21da8c65b75..f412bee71f9 100644
--- a/studio/backend/tests/test_diffusers_repair.py
+++ b/studio/backend/tests/test_diffusers_repair.py
@@ -23,6 +23,7 @@ import utils.diffusers_repair as dr # noqa: E402
_REAL_PEER_HOLDS_PASS = dr._peer_holds_pass
_REAL_INSTALLER_WOULD_SKIP = dr._installer_would_skip
_REAL_LOADED_REPLACEABLE = dr._loaded_replaceable_modules
+_REAL_MAIN_PIN_ACTIVE = dr._main_pin_active
class _Dist:
@@ -40,8 +41,10 @@ def _reset(monkeypatch):
monkeypatch.delenv(dr.DISABLE_ENV_VAR, raising = False)
monkeypatch.delenv("UNSLOTH_DIFFUSERS_MAIN", raising = False)
monkeypatch.setattr(dr, "_peer_holds_pass", lambda: False)
- monkeypatch.setattr(dr, "_installer_would_skip", lambda: False)
+ monkeypatch.setattr(dr, "_installer_would_skip", lambda *a, **k: False)
monkeypatch.setattr(dr, "_loaded_replaceable_modules", lambda: [])
+ # Git-main route; release mode (the shipped file) is covered at the end.
+ monkeypatch.setattr(dr, "_main_pin_active", lambda: True)
def _installed_diffusers(monkeypatch, direct_url):
@@ -173,7 +176,7 @@ def test_a_timed_out_repair_stops_the_installers_children_and_records_it(monkeyp
"""Stop uv children before app imports and record the timeout to prevent repeated retries."""
pid_file, started = _slow_installer(monkeypatch, tmp_path)
recorded = []
- monkeypatch.setattr(dr, "_record_failure", lambda: recorded.append(True))
+ monkeypatch.setattr(dr, "_record_failure", lambda *a: recorded.append(True))
lines = []
assert dr._run_repair(lines.append) is False
assert recorded == [True]
@@ -187,7 +190,7 @@ def test_a_peer_that_started_during_a_slow_prefetch_stops_startup(monkeypatch, t
"""The prefetch holds no lock, so a pass can begin under it; importing then mixes versions."""
pid_file, started = _slow_installer(monkeypatch, tmp_path, timeout_s = 2)
recorded = []
- monkeypatch.setattr(dr, "_record_failure", lambda: recorded.append(True))
+ monkeypatch.setattr(dr, "_record_failure", lambda *a: recorded.append(True))
monkeypatch.setattr(dr, "_peer_holds_pass", lambda: True)
with pytest.raises(dr.PeerInstallInProgress, match = "Start Unsloth Studio again"):
dr._run_repair(lambda _line: None)
@@ -201,7 +204,7 @@ def test_our_own_install_stopped_at_the_deadline_stops_startup(monkeypatch, tmp_
"""Stopped mid-install, packages may be half replaced: never import them, never record."""
pid_file, started = _slow_installer(monkeypatch, tmp_path, timeout_s = 2)
recorded = []
- monkeypatch.setattr(dr, "_record_failure", lambda: recorded.append(True))
+ monkeypatch.setattr(dr, "_record_failure", lambda *a: recorded.append(True))
with pytest.raises(dr.InstallInterrupted, match = "Start Unsloth Studio again"):
dr._run_repair(lambda _line: None, prefetch = False)
assert started == ["--repair-diffusers-main"]
@@ -214,7 +217,7 @@ def test_a_peer_still_in_the_pass_at_the_deadline_stops_startup_in_time(monkeypa
"""Abort at timeout if a peer is still installing, without changing its manifest."""
pid_file, _started = _slow_installer(monkeypatch, tmp_path, timeout_s = 2)
recorded = []
- monkeypatch.setattr(dr, "_record_failure", lambda: recorded.append(True))
+ monkeypatch.setattr(dr, "_record_failure", lambda *a: recorded.append(True))
monkeypatch.setattr(dr, "_peer_holds_pass", lambda: True)
started = time.monotonic()
with pytest.raises(dr.PeerInstallInProgress, match = "Start Unsloth Studio again"):
@@ -437,3 +440,79 @@ def test_the_installer_exposes_the_repair_flag():
source = dr._INSTALLER.read_text(encoding = "utf-8")
assert '["--repair-diffusers-main"]' in source
assert '["--prefetch-diffusers-main"]' in source
+
+
+def _release_mode(monkeypatch, installed):
+ import importlib.metadata
+
+ monkeypatch.setattr(dr, "_main_pin_active", _REAL_MAIN_PIN_ACTIVE)
+ monkeypatch.setattr(dr, "_installer_would_skip", _REAL_INSTALLER_WOULD_SKIP)
+ real_version = importlib.metadata.version
+ monkeypatch.setattr(
+ importlib.metadata,
+ "version",
+ lambda name: installed if name == "diffusers" else real_version(name),
+ )
+ _installed_diffusers(monkeypatch, None) # an index install, whatever the host has
+
+
+def test_the_shipped_main_pin_is_inactive():
+ assert _REAL_MAIN_PIN_ACTIVE() is False
+
+
[email protected]("installed", ["0.41.0", "0.41.0.post1"])
+def test_a_current_release_starts_nothing(monkeypatch, installed):
+ _release_mode(monkeypatch, installed)
+ monkeypatch.setattr(dr, "_run_installer", lambda *a, **k: pytest.fail("started a repair"))
+ lines = []
+ assert dr.repair_diffusers_before_imports(lines.append) is False and lines == []
+
+
[email protected]("env", [{}, {"UNSLOTH_DIFFUSERS_MAIN": "0"}])
+def test_a_release_behind_the_pin_is_prefetched_then_repaired(monkeypatch, env):
+ _release_mode(monkeypatch, "0.40.0")
+ # An old git-main failure must not strand the PyPI release.
+ _manifest(monkeypatch, {"diffusers_main_repair": "failed"})
+ for key, value in env.items():
+ monkeypatch.setenv(key, value)
+ flags = []
+ monkeypatch.setattr(
+ dr, "_run_installer", lambda flag, timeout: flags.append(flag) or (dr._INSTALLED, "")
+ )
+ assert dr.repair_diffusers_before_imports() is True
+ assert flags == ["--prefetch-diffusers-main", "--repair-diffusers-main"]
+
+
+ "direct_url",
+ [
+ {"url": "file:///src/diffusers", "dir_info": {"editable": True}},
+ {"url": "https://github.com/huggingface/diffusers", "vcs_info": {"vcs": "git"}},
+ ],
+)
+def test_release_mode_never_replaces_a_build_the_user_put_there(monkeypatch, direct_url):
+ _release_mode(monkeypatch, "0.40.0")
+ _installed_diffusers(monkeypatch, direct_url)
+ monkeypatch.setattr(dr, "_run_installer", lambda *a, **k: pytest.fail("started a repair"))
+ assert dr.repair_diffusers_before_imports() is False
+
+
+def test_a_timed_out_release_prefetch_records_the_release_key(monkeypatch):
+ _release_mode(monkeypatch, "0.40.0")
+ recorded = []
+ monkeypatch.setattr(
+ dr, "_record_failure", lambda main_active = True: recorded.append(main_active)
+ )
+ monkeypatch.setattr(dr, "_run_installer", lambda flag, timeout: (None, ""))
+ assert dr.repair_diffusers_before_imports() is False
+ assert recorded == [False]
+
+
+def test_release_mode_honours_the_autorepair_opt_out_and_its_own_failure(monkeypatch):
+ _release_mode(monkeypatch, "0.40.0")
+ monkeypatch.setattr(dr, "_run_installer", lambda *a, **k: pytest.fail("started a repair"))
+ _manifest(monkeypatch, {"diffusers_release_repair": "failed"})
+ assert dr.repair_diffusers_before_imports() is False
+ _manifest(monkeypatch, {})
+ monkeypatch.setenv(dr.DISABLE_ENV_VAR, "1")
+ assert dr.repair_diffusers_before_imports() is False
diff --git a/studio/backend/tests/test_diffusion_more_families.py b/studio/backend/tests/test_diffusion_more_families.py
index 64270515022..b5b3e5bc76e 100644
--- a/studio/backend/tests/test_diffusion_more_families.py
+++ b/studio/backend/tests/test_diffusion_more_families.py
@@ -766,7 +766,9 @@ def test_the_pinned_prebuilt_is_one_that_can_load_qwen_image_21():
)
-def test_a_minimum_that_has_not_shipped_does_not_prescribe_an_impossible_upgrade():
+def test_a_minimum_that_has_not_shipped_does_not_prescribe_an_impossible_upgrade(
+ monkeypatch, tmp_path
+):
"""``pip install -U 'diffusers>=0.41.0'`` has no candidate while 0.41.0 is unreleased, so the
refusal has to name the pinned main build Studio actually installs for this class.
@@ -774,22 +776,30 @@ def test_a_minimum_that_has_not_shipped_does_not_prescribe_an_impossible_upgrade
host whose git exits non-zero: the install keeps diffusers 0.40.0, and the old text sent the
reader to `pip install -r diffusers-main.txt`, which resolves the same git+https requirement
and fails identically. The quoted zip URL needs no git, so it is the one line here that has to
- stay true, hence the check that it names the commit the pin file actually carries."""
+ stay true, hence the check that it names the commit the pin file actually carries.
+
+ 0.41.0 has since shipped, so this runs as the next unreleased pin would: the minimum marked
+ unreleased and diffusers-main.txt with its commit line uncommented."""
import pathlib
import re as _re
- from core.inference.diffusion_families import (
- _PIPELINE_MIN_DIFFUSERS,
- _UNRELEASED_MIN_DIFFUSERS,
- _too_old_message,
+ from core.inference import diffusion_families as families
+ from core.inference.diffusion_families import _PIPELINE_MIN_DIFFUSERS, _too_old_message
+
+ shipped = pathlib.Path(__file__).resolve().parents[1] / "requirements" / "diffusers-main.txt"
+ pin = tmp_path / "diffusers-main.txt"
+ pin.write_text(
+ shipped.read_text(encoding = "utf-8").replace("\n# diffusers @ git+", "\ndiffusers @ git+"),
+ encoding = "utf-8",
)
+ monkeypatch.setattr(families, "_DIFFUSERS_MAIN_PIN", pin)
+ monkeypatch.setattr(families, "_UNRELEASED_MIN_DIFFUSERS", frozenset({"0.41.0"}))
message = _too_old_message("QwenImage21Pipeline", "qwen-image-2.1", "0.40.0")
assert "pip install -U 'diffusers>=0.41.0'" not in message
assert "has not been released yet" in message
assert "git --version" in message, "the likely cause has to be checkable by the reader"
- pin = pathlib.Path(__file__).resolve().parents[1] / "requirements" / "diffusers-main.txt"
commit = _re.search(r"@([0-9a-fA-F]{40})\b", pin.read_text(encoding = "utf-8"))
assert commit is not None, "the main pin must carry a full commit for the zip route to exist"
assert (
@@ -803,7 +813,20 @@ def test_a_minimum_that_has_not_shipped_does_not_prescribe_an_impossible_upgrade
# Every unreleased entry must still be a minimum some class actually declares, so a stale one
# cannot sit here unnoticed after its release ships.
declared = set(_PIPELINE_MIN_DIFFUSERS.values())
- assert _UNRELEASED_MIN_DIFFUSERS <= declared, sorted(_UNRELEASED_MIN_DIFFUSERS - declared)
+ monkeypatch.undo()
+ unreleased = families._UNRELEASED_MIN_DIFFUSERS
+ assert unreleased <= declared, sorted(unreleased - declared)
+
+
+def test_qwen_image_21_on_0_40_points_at_the_released_0_41():
+ """0.41.0 is on PyPI: a 0.40.0 install is told to update, not sent to a git build."""
+ from core.inference.diffusion_families import _UNRELEASED_MIN_DIFFUSERS, _too_old_message
+
+ assert "0.41.0" not in _UNRELEASED_MIN_DIFFUSERS
+ message = _too_old_message("QwenImage21Pipeline", "qwen-image-2.1", "0.40.0")
+ assert "pip install -U 'diffusers>=0.41.0'" in message
+ assert "Settings, Check for updates" in message
+ assert "has not been released yet" not in message and "git" not in message, message
def test_qwen_image_21_takes_reference_images_but_is_not_an_edit_only_family():
diff --git a/studio/backend/tests/test_diffusion_single_file_krea2_hunyuanimage.py b/studio/backend/tests/test_diffusion_single_file_krea2_hunyuanimage.py
index c972693fb80..ed938c8cfac 100644
--- a/studio/backend/tests/test_diffusion_single_file_krea2_hunyuanimage.py
+++ b/studio/backend/tests/test_diffusion_single_file_krea2_hunyuanimage.py
@@ -468,16 +468,18 @@ def test_comfy_int8_krea2_file_loads_with_codes_exact(tmp_path, monkeypatch):
assert loaded._unsloth_comfy_quant["dequantized"] == len(expected)
-def test_plain_krea2_file_loads_like_the_base_repo(tmp_path, monkeypatch):
[email protected]("prefix", ["", "model.model.", "diffusion_model."])
+def test_plain_krea2_file_loads_like_the_base_repo(tmp_path, monkeypatch, prefix):
"""A plain bf16 ComfyUI file through Studio's loader (used while diffusers gives Krea 2 no
from_single_file): same tensors as the diffusers weights, the _keep_in_fp32_modules norms in float32
- as from_pretrained leaves them, strict on keys."""
+ as from_pretrained leaves them, strict on keys. Every container prefix, including the two diffusers
+ 0.41's own Krea 2 converter does not strip."""
cls = _class("Krea2Transformer2DModel")
model = _tiny("Krea2Transformer2DModel", KREA2_CFG)
path = tmp_path / "krea2_tiny_bf16.safetensors"
safetensors_torch.save_file(
{
- k: v.to(torch.bfloat16).contiguous()
+ prefix + k: v.to(torch.bfloat16).contiguous()
for k, v in krea2_original(model.state_dict()).items()
},
str(path),
@@ -508,7 +510,10 @@ def test_the_single_file_branch_uses_studio_loader_only_without_from_single_file
# Whitespace-free, so a formatter rewrapping the condition cannot break the check.
source = "".join(inspect.getsource(studio).split())
- gate = source.index('ifkind!="gguf"andnothasattr(transformer_cls,"from_single_file"):')
+ gate = source.index('ifkind!="gguf"and(nothasattr(transformer_cls,"from_single_file")')
+ assert source.index('=="Krea2Transformer2DModel"', gate) < source.index(
+ "transformer=load_original_layout_transformer(", gate
+ )
assert (
gate
< source.index("transformer=load_original_layout_transformer(", gate)
@@ -536,6 +541,20 @@ def test_both_classes_register_and_resolve(monkeypatch):
assert fn is conv.hunyuanimage_checkpoint_to_diffusers
+def test_studio_converters_win_over_a_later_upstream_entry(monkeypatch):
+ """diffusers 0.41 registers its own Krea 2 converter, which strips only model.diffusion_model."""
+ from diffusers.loaders import single_file_model as sfm
+
+ cls = _class("Krea2Transformer2DModel")
+ monkeypatch.setitem(
+ sfm.SINGLE_FILE_LOADABLE_CLASSES,
+ "Krea2Transformer2DModel",
+ {"checkpoint_mapping_fn": lambda **k: {}, "default_subfolder": "transformer"},
+ )
+ fn, _ = cq._mapping(cls)
+ assert fn is conv.krea2_checkpoint_to_diffusers
+
+
@pytest.mark.parametrize(
"filename, family",
[
diff --git a/studio/backend/utils/diffusers_repair.py b/studio/backend/utils/diffusers_repair.py
index b8fd0d04a57..5a08fdf5238 100644
--- a/studio/backend/utils/diffusers_repair.py
+++ b/studio/backend/utils/diffusers_repair.py
@@ -1,7 +1,8 @@
# SPDX-License-Identifier: AGPL-3.0-only
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
-"""Startup self-heal for the pinned Diffusers main build.
+"""Startup self-heal for the pinned Diffusers main build, or the pinned release while
+diffusers-main.txt is commented out.
Older installers can miss the pinned build during an update. Repair before importing the app:
the build also upgrades huggingface_hub, which would otherwise mix new files with cached modules.
@@ -78,13 +79,60 @@ _ENV_ALLOWLIST = frozenset(
)
-def _opted_out() -> bool:
+def _opted_out(main_active: bool = True) -> bool:
if os.environ.get(DISABLE_ENV_VAR) == "1":
return True
+ if not main_active:
+ return False
value = (os.environ.get("UNSLOTH_DIFFUSERS_MAIN") or "").strip().lower()
return value in ("0", "false", "no", "off")
+def _target(main_active: bool) -> str:
+ return "main build" if main_active else "release"
+
+
+def _main_pin_active() -> bool:
+ try:
+ text = _MAIN_PIN.read_text(encoding = "utf-8-sig")
+ except (OSError, ValueError):
+ return False
+ return any(
+ line.strip() and not line.strip().startswith("#") and "git+" in line
+ for line in text.splitlines()
+ )
+
+
+def _release_behind() -> bool:
+ """The installer's ``_diffusers_release_behind`` for an index install (the only kind repaired), metadata only."""
+ try:
+ from importlib.metadata import version
+ from packaging.requirements import Requirement
+ from packaging.version import Version
+
+ installed = version("diffusers")
+ text = (_MAIN_PIN.parent / "diffusers-pin.txt").read_text(encoding = "utf-8-sig")
+ except Exception: # noqa: BLE001 - no diffusers or no pin file is the installer's job
+ return False
+ for line in text.splitlines():
+ line = line.split("#", 1)[0].strip()
+ try:
+ requirement = Requirement(line) if line else None
+ except Exception: # noqa: BLE001 - a line packaging cannot parse names no target
+ requirement = None
+ if requirement is None or requirement.name.lower() != "diffusers":
+ continue
+ if requirement.marker is not None and not requirement.marker.evaluate():
+ continue
+ for spec in requirement.specifier:
+ if spec.operator == "==":
+ try:
+ return Version(installed) < Version(spec.version)
+ except Exception: # noqa: BLE001 - an unparseable version is left alone
+ return False
+ return False
+
+
def _diffusers_is_an_index_install() -> bool:
"""True when diffusers came from an index, the only state the repair acts on.
@@ -148,24 +196,27 @@ INTERRUPTED_MESSAGE = (
)
-def _record_failure() -> None:
+def _record_failure(main_active: bool = True) -> None:
"""Suppress startup retries until an explicit update clears the failure key."""
+ key = "diffusers_main_repair" if main_active else "diffusers_release_repair"
try:
from studio.install_manifest import update_manifest
- update_manifest(diffusers_main_repair = "failed")
+ update_manifest(**{key: "failed"})
except Exception as exc: # noqa: BLE001 - unrecorded means the next start tries again
logger.warning("diffusers self-heal could not record its failure: %s", exc)
-def _installer_would_skip() -> bool:
+def _installer_would_skip(main_active: bool = True) -> bool:
"""The installer's no-op gates: a start it would skip must not block or claim to install."""
- if sys.version_info[:2] < _MAIN_MIN_PYTHON:
+ if main_active and sys.version_info[:2] < _MAIN_MIN_PYTHON:
return True
try:
from studio.install_manifest import read_manifest
manifest = read_manifest() or {}
except Exception: # noqa: BLE001 - an unreadable manifest is no record of a failed try
return False
+ if not main_active:
+ return manifest.get("diffusers_release_repair") == "failed"
step_results = manifest.get("step_results")
update_failed = (
isinstance(step_results, dict) and step_results.get("diffusers-main.txt") == "failed"
@@ -209,7 +260,11 @@ def _run_installer(flag: str, timeout: float) -> "tuple[int | None, str]":
return proc.returncode, output or ""
-def _run_repair(echo: Callable[[str], None], prefetch: bool = True) -> bool:
+def _run_repair(
+ echo: Callable[[str], None],
+ prefetch: bool = True,
+ main_active: bool = True,
+) -> bool:
started = time.monotonic()
if prefetch:
# The slow part (clone or download, then build) goes into uv's cache only, so stopping it
@@ -224,7 +279,7 @@ def _run_repair(echo: Callable[[str], None], prefetch: bool = True) -> bool:
if _peer_holds_pass():
logger.warning("diffusers self-heal timed out while a peer's dependency pass ran")
raise PeerInstallInProgress(PEER_INSTALL_MESSAGE)
- _record_failure()
+ _record_failure(main_active)
echo(
f" - the pinned Diffusers build took over {_REPAIR_TIMEOUT_S}s to download and "
"was stopped; run `unsloth studio update` to install it"
@@ -251,7 +306,7 @@ def _run_repair(echo: Callable[[str], None], prefetch: bool = True) -> bool:
raise InstallInterrupted(INTERRUPTED_MESSAGE)
if code == _INSTALLED:
echo(" - installed the pinned Diffusers build")
- logger.info("diffusers self-heal installed the pinned Diffusers main build")
+ logger.info("diffusers self-heal installed the pinned Diffusers %s", _target(main_active))
return True
if code != _NOTHING_TO_DO:
echo(
@@ -276,10 +331,13 @@ def repair_diffusers_before_imports(echo: Callable[[str], None] = lambda _line:
Raise PeerInstallInProgress if a peer holds the install lock at timeout, and
InstallInterrupted if our own install had to be stopped.
"""
- if _opted_out() or not _MAIN_PIN.is_file() or not _INSTALLER.is_file():
+ main_active = _main_pin_active()
+ if _opted_out(main_active) or not _MAIN_PIN.is_file() or not _INSTALLER.is_file():
return False
+ # Release mode: only an index install older than the pin; a user's checkout or git build is theirs.
+ candidate = _diffusers_is_an_index_install() and (main_active or _release_behind())
# Check the lock too: an active install may have temporarily removed the metadata.
- if _diffusers_is_an_index_install() and not _installer_would_skip():
+ if candidate and not _installer_would_skip(main_active):
loaded = _loaded_replaceable_modules()
if loaded:
# An embedding host (a notebook kernel) imported them already; replacing the files
@@ -297,5 +355,9 @@ def repair_diffusers_before_imports(echo: Callable[[str], None] = lambda _line:
prefetch = False
else:
return False
- logger.info("installing the pinned Diffusers main build. Set %s=1 to disable.", DISABLE_ENV_VAR)
- return _run_repair(echo, prefetch = prefetch)
+ logger.info(
+ "installing the pinned Diffusers %s. Set %s=1 to disable.",
+ _target(main_active),
+ DISABLE_ENV_VAR,
+ )
+ return _run_repair(echo, prefetch = prefetch, main_active = main_active)
diff --git a/studio/install_python_stack.py b/studio/install_python_stack.py
index afc7f97e088..ea64652b8ad 100644
--- a/studio/install_python_stack.py
+++ b/studio/install_python_stack.py
@@ -11230,6 +11230,54 @@ def _diffusers_main_supersedes_release() -> bool:
return _diffusers_main_requested() and _diffusers_main_resident()
+def _diffusers_main_active(req: "Path | None" = None) -> bool:
+ """Whether diffusers-main.txt has an uncommented line; an all-comment file is not "build missing"."""
+ if req is None:
+ req = REQ_ROOT / "diffusers-main.txt"
+ return _direct_reference_in_requirements(req) is not None
+
+
+def _diffusers_release_target() -> "str | None":
+ try:
+ from packaging.requirements import Requirement
+ text = (REQ_ROOT / "diffusers-pin.txt").read_text(encoding = "utf-8-sig")
+ except (ImportError, OSError, ValueError):
+ return None
+ for line in text.splitlines():
+ line = line.split("#", 1)[0].strip()
+ if not line:
+ continue
+ try:
+ requirement = Requirement(line)
+ except Exception: # noqa: BLE001
+ continue
+ if requirement.name.lower() != "diffusers":
+ continue
+ if requirement.marker is not None and not requirement.marker.evaluate():
+ continue
+ for spec in requirement.specifier:
+ if spec.operator == "==":
+ return spec.version
+ return None
+
+
+def _diffusers_release_behind() -> bool:
+ """Resident diffusers older than diffusers-pin.txt's ``==``; a git / zip / checkout build is judged on
+ release numbers (the main build's 0.41.0.dev0 is current), an index prerelease is not."""
+ target = _diffusers_release_target()
+ installed = _installed_distribution_version("diffusers")
+ if target is None or installed is None:
+ return False
+ direct = _recorded_direct_url("diffusers") or {}
+ built = any(k in direct for k in ("vcs_info", "archive_info", "dir_info"))
+ try:
+ from packaging.version import Version
+ have = Version(installed)
+ return (Version(have.base_version) if built else have) < Version(target)
+ except Exception: # noqa: BLE001 - no packaging, or a version it cannot parse
+ return False
+
+
_ARCHIVE_SHA256_RE = re.compile(r"#\s*archive-sha256:\s*([0-9a-fA-F]{64})")
@@ -11272,8 +11320,9 @@ def _diffusers_main_needs_dependency_pass() -> bool:
github.com would repeat the whole dependency pass on every update.
"""
req = REQ_ROOT / "diffusers-main.txt"
- if not req.is_file():
- return False
+ if not req.is_file() or not _diffusers_main_active(req):
+ # Not same-version damage: 11b's version check would skip it and force the pass on every update.
+ return _diffusers_release_behind() or _installed_distribution_version("diffusers") is None
if not _diffusers_main_requested():
# Opted out while the build is still resident: 11b puts the release back.
return _diffusers_main_resident(req)
@@ -11305,6 +11354,41 @@ def _startup_repair_failed() -> bool:
_REPAIR_LOCK_POLL_S = 5
+# Apart from the git key, so an old github.com failure cannot block the PyPI release.
+_DIFFUSERS_RELEASE_REPAIR_KEY = "diffusers_release_repair"
+
+
+def _release_repair_failed() -> bool:
+ try:
+ manifest = install_manifest.read_manifest() or {}
+ return manifest.get(_DIFFUSERS_RELEASE_REPAIR_KEY) == "failed"
+ except Exception: # noqa: BLE001 - an unreadable manifest is no record of a failed try
+ return False
+
+
+def _repair_diffusers_release() -> int:
+ """11b alone for the startup self-heal, pass lock held: 0 installed, 1 nothing to do, 2 failed."""
+ global USE_UV, _STEP, _TOTAL
+ direct = _recorded_direct_url("diffusers") or {}
+ # A checkout, git or zip build is the user's: also reached by a backend that waited out a peer.
+ if any(k in direct for k in ("vcs_info", "archive_info", "dir_info")):
+ return 1
+ if not _diffusers_release_behind() or _release_repair_failed():
+ return 1
+ USE_UV = _bootstrap_uv()
+ _STEP, _TOTAL = 0, 1
+ _progress("diffusers pin")
+ installed = pip_install_try(
+ "Installing the pinned Diffusers release",
+ "--no-cache-dir",
+ req = REQ_ROOT / "diffusers-pin.txt",
+ )
+ importlib.invalidate_caches()
+ if installed and not _diffusers_release_behind():
+ return 0
+ install_manifest.update_manifest(**{_DIFFUSERS_RELEASE_REPAIR_KEY: "failed"})
+ return 2
+
def _repair_diffusers_main() -> int:
"""11c on its own, for the backend's startup self-heal: 0 installed, 1 nothing to do, 2 failed.
@@ -11321,6 +11405,8 @@ def _repair_diffusers_main() -> int:
# update leaves the pass it may be rewriting diffusers, and returning would let the backend
# that started this import it.
if uncontended:
+ if not _diffusers_main_active():
+ return _repair_diffusers_release()
if (
not _diffusers_main_requested()
or not _diffusers_main_needs_dependency_pass()
@@ -11353,7 +11439,12 @@ def _prefetch_diffusers_main() -> int:
global USE_UV
req = REQ_ROOT / "diffusers-main.txt"
- if (
+ release = not _diffusers_main_active(req)
+ if release:
+ # A timeout here is recorded and survivable; one inside the install refuses every start.
+ if not _diffusers_release_behind() or _release_repair_failed():
+ return 1
+ elif (
not req.is_file()
or not _diffusers_main_requested()
or not _diffusers_main_needs_dependency_pass()
@@ -11371,16 +11462,22 @@ def _prefetch_diffusers_main() -> int:
except OSError:
pass
# The same source _diffusers_main_step will install from, so the install hits this cache entry.
- archive = None if _has_working_git() else _diffusers_main_archive(req)
+ archive = None if release or _has_working_git() else _diffusers_main_archive(req)
scratch = Path(tempfile.mkdtemp(prefix = _PREFETCH_SCRATCH_PREFIX))
temp_reqs: list[Path] = []
try:
- args = ("--no-deps", "--target", str(scratch))
+ args = ("--target", str(scratch)) if release else ("--no-deps", "--target", str(scratch))
+ if release:
+ req = REQ_ROOT / "diffusers-pin.txt"
if archive is not None:
cmd = _build_uv_cmd((*args, f"diffusers @ {archive}"))
else:
actual_req, temp_reqs = _effective_requirements(req)
- cmd = _build_uv_cmd(args) + ["-r", _uv_safe_path(actual_req)]
+ # Same constraints as the install, or its resolve misses the cache.
+ constraints = (
+ ["-c", _uv_safe_path(CONSTRAINTS)] if release and CONSTRAINTS.is_file() else []
+ )
+ cmd = _build_uv_cmd(args) + constraints + ["-r", _uv_safe_path(actual_req)]
cmd, env = _pinned_cmd_and_env(cmd)
result = subprocess.run(
cmd,
@@ -11423,6 +11520,10 @@ def _diffusers_main_step() -> None:
fixed before any of this is known. An early return without a _progress leaves the bar short of
its own total for precisely the users who opted out.
"""
+ if not _diffusers_main_active():
+ _progress("diffusers main (none pinned, skipped)")
+ _record_step("diffusers-main.txt", "skipped")
+ return
if not _diffusers_main_requested():
_progress("diffusers main (opted out, skipped)")
return
diff --git a/tests/sh/test_clean_machine_notools_pinned_git.sh b/tests/sh/test_clean_machine_notools_pinned_git.sh
index aee80858671..20c4c04ddbc 100755
--- a/tests/sh/test_clean_machine_notools_pinned_git.sh
+++ b/tests/sh/test_clean_machine_notools_pinned_git.sh
@@ -14,9 +14,13 @@ set -e
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
REPO_ROOT="$SCRIPT_DIR/../.."
ASSERT_SH="$REPO_ROOT/.github/scripts/clean-machine-assert.sh"
-PIN="$REPO_ROOT/studio/backend/requirements/diffusers-main.txt"
+SHIPPED_PIN="$REPO_ROOT/studio/backend/requirements/diffusers-main.txt"
ROOT=$(mktemp -d)
trap 'rm -rf "$ROOT"' EXIT
+# The shipped pin is commented out while a Diffusers release carries every family, so the
+# allowance is exercised on the same file with its requirement line uncommented.
+PIN="$ROOT/diffusers-main.txt"
+sed 's/^# diffusers @ git+/diffusers @ git+/' "$SHIPPED_PIN" > "$PIN"
PASS=0
FAIL=0
@@ -74,6 +78,7 @@ expect_rc "uv cloning the pinned Diffusers build passes" 0 "$PIN" "$UV_CLONE"
expect_rc "the same trace fails with no allowance, as before" 1 "" "$UV_CLONE"
expect_rc "an allowance file that does not exist allows nothing" 1 "$ROOT/missing.txt" "$UV_CLONE"
expect_rc "the installer's git --version probe alone passes" 0 "$PIN" "git\t--version\n"
+expect_rc "the shipped, commented-out pin allows no clone" 1 "$SHIPPED_PIN" "$UV_CLONE"
# An overlay-free leg installs the released wheel, which can pin an older commit than this
# checkout's file; uv's checkout is named after the commit it installs.
OLDER=1111111111111111111111111111111111111111
diff --git a/tests/studio/install/test_diffusers_pin.py b/tests/studio/install/test_diffusers_pin.py
index 86e6f17a7c9..15fb109cda9 100644
--- a/tests/studio/install/test_diffusers_pin.py
+++ b/tests/studio/install/test_diffusers_pin.py
@@ -32,6 +32,8 @@ PIN_FILE = REQ_ROOT / "diffusers-pin.txt"
# installed by the step immediately after the release pin and by nothing else, which the tests here
# pin down rather than assume.
MAIN_FILE = REQ_ROOT / "diffusers-main.txt"
+# Git-main tests run on a copy with the commit line uncommented (``_active_main``); the shipped state is below.
+_ACTIVE_REQ_ROOT: list = []
# The shape install_python_stack._filter_requirements writes: a dot, the source stem,
# "-filtered-", then tempfile's random suffix. NamedTemporaryFile's suffixes are
@@ -41,6 +43,23 @@ STACK = REPO_ROOT / "studio" / "install_python_stack.py"
INSTALL_SH = REPO_ROOT / "install.sh"
[email protected](scope = "session", autouse = True)
+def _active_req_root(tmp_path_factory):
+ import shutil
+
+ root = tmp_path_factory.mktemp("active_main") / "requirements"
+ shutil.copytree(REQ_ROOT, root)
+ main = root / "diffusers-main.txt"
+ text = main.read_text(encoding = "utf-8")
+ main.write_text(text.replace("\n# diffusers @ git+", "\ndiffusers @ git+"), encoding = "utf-8")
+ _ACTIVE_REQ_ROOT[:] = [root]
+ yield root
+
+
+def _active_main() -> pathlib.Path:
+ return _ACTIVE_REQ_ROOT[0] / "diffusers-main.txt"
+
+
def _requirements(path: pathlib.Path) -> list[str]:
"""Requirement lines only: comments and flag lines dropped."""
out = []
@@ -79,7 +98,9 @@ def test_the_pin_file_exists_and_names_the_first_supported_release():
assert PIN_FILE.is_file(), f"{PIN_FILE} is missing"
lines = _requirements(PIN_FILE)
modern = [line for line in lines if 'python_version >= "3.10"' in line]
- assert modern == ['diffusers==0.40.0 ; python_version >= "3.10"'], modern
+ assert modern == ['diffusers==0.41.0 ; python_version >= "3.10"'], modern
+ legacy = [line for line in lines if 'python_version < "3.10"' in line]
+ assert legacy == ['diffusers==0.36.0 ; python_version < "3.10"'], legacy
assert "://" not in modern[0], "the released dependency must not require a source build"
assert 'python_version >= "3.10"' in modern[0], (
"diffusers dropped Python 3.9 in 0.38, so the release needs a >= 3.10 marker or "
@@ -121,7 +142,7 @@ def test_the_main_build_pins_a_commit_and_runs_after_the_release():
base would otherwise be on whatever main happened to be that morning.
"""
assert MAIN_FILE.is_file(), f"{MAIN_FILE} is missing"
- lines = _requirements(MAIN_FILE)
+ lines = _requirements(_active_main())
assert len(lines) == 1, lines
spec = lines[0]
assert spec.startswith("diffusers @ git+"), spec
@@ -142,15 +163,29 @@ def test_the_main_build_pins_a_commit_and_runs_after_the_release():
# install, so a filename compare answers a different question and passes by accident.
call = "\n _diffusers_main_step()\n"
assert call in source, "the main-build step is never called"
- assert source.index(call) > source.index('req = REQ_ROOT / "diffusers-pin.txt"')
+ assert source.index(call) > source.rindex('req = REQ_ROOT / "diffusers-pin.txt"')
+
+
+def test_the_shipped_main_build_is_commented_out_but_keeps_its_commit():
+ """0.41.0 is on PyPI: nothing installs from git, and re-enabling is one uncomment away."""
+ assert _requirements(MAIN_FILE) == []
+ text = MAIN_FILE.read_text(encoding = "utf-8")
+ assert re.search(r"^# diffusers @ git\+https://\S+@[0-9a-f]{40}$", text, re.M), text
+ assert re.search(r"^# archive-sha256: [0-9a-f]{64}$", text, re.M)
+ module = _probe_module("install_python_stack_probe_shipped", active = False)
+ assert module._diffusers_main_active() is False
+ assert module._diffusers_main_resident() is False
+ assert module._diffusers_main_supersedes_release() is False
-def _probe_module(name: str):
+def _probe_module(name: str, active: bool = True):
import importlib.util
spec = importlib.util.spec_from_file_location(name, STACK)
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
+ if active:
+ module.REQ_ROOT = _ACTIVE_REQ_ROOT[0]
return module
@@ -217,8 +252,8 @@ def test_the_main_build_falls_back_to_the_zip_when_there_is_no_git(monkeypatch):
assert kwargs.get("req") is None, "the git requirement file must not be handed to pip here"
spec = [arg for arg in args if arg.startswith("diffusers @ ")]
assert len(spec) == 1, args
- revision = _requirements(MAIN_FILE)[0].rpartition("@")[2].strip().lower()
- digest = module._archive_sha256_in_requirements(MAIN_FILE)
+ revision = _requirements(_active_main())[0].rpartition("@")[2].strip().lower()
+ digest = module._archive_sha256_in_requirements(_active_main())
assert digest is not None and re.fullmatch(r"[0-9a-f]{64}", digest), digest
# The fragment is what pip and uv verify; the commit in the URL checks no bytes.
assert spec[0] == (
@@ -230,8 +265,8 @@ def test_the_main_build_falls_back_to_the_zip_when_there_is_no_git(monkeypatch):
def test_the_zip_route_is_skipped_without_exactly_one_pinned_digest(tmp_path, monkeypatch):
"""No single valid digest, no zip route: the host keeps the release."""
module = _probe_module("install_python_stack_probe2e")
- spec = _requirements(MAIN_FILE)[0]
- digest = module._archive_sha256_in_requirements(MAIN_FILE)
+ spec = _requirements(_active_main())[0]
+ digest = module._archive_sha256_in_requirements(_active_main())
pin = tmp_path / "diffusers-main.txt"
pin.write_text(f"{spec}\n", encoding = "utf-8")
@@ -294,7 +329,7 @@ def test_an_archive_install_reads_back_as_resident(monkeypatch):
"""
module = _probe_module("install_python_stack_probe2c")
- revision = _requirements(MAIN_FILE)[0].rpartition("@")[2].strip().lower()
+ revision = _requirements(_active_main())[0].rpartition("@")[2].strip().lower()
archive = f"https://github.com/huggingface/diffusers/archive/{revision}.zip"
monkeypatch.setattr(module, "_payload_recorded_intact", lambda *a, **k: True)
@@ -303,7 +338,7 @@ def test_an_archive_install_reads_back_as_resident(monkeypatch):
"_recorded_direct_url",
lambda dist: {"url": archive, "archive_info": {"hash": "sha256=abc"}},
)
- assert module._direct_reference_is_installed(MAIN_FILE, "diffusers") is True
+ assert module._direct_reference_is_installed(_active_main(), "diffusers") is True
# A zip of a DIFFERENT commit is not this one, which is the whole reason the SHA has to be in
# the URL: an archive records no ref, so the URL is the only provenance there is.
@@ -313,7 +348,7 @@ def test_an_archive_install_reads_back_as_resident(monkeypatch):
"_recorded_direct_url",
lambda dist: {"url": other, "archive_info": {"hash": "sha256=abc"}},
)
- assert module._direct_reference_is_installed(MAIN_FILE, "diffusers") is False
+ assert module._direct_reference_is_installed(_active_main(), "diffusers") is False
def test_the_zip_route_refuses_anything_it_cannot_pin():
@@ -428,7 +463,8 @@ def test_the_pin_step_runs_after_every_other_requirements_install():
"""Ordering matters: a later `uv pip install -r ...` can re-resolve diffusers back to a
release. Keeping the pin last means nothing is left that could walk it forward."""
source = _code_only(STACK.read_text(encoding = "utf-8"))
- pin_at = source.index("diffusers-pin.txt")
+ # The pass's own install is the last one; the startup repair's comes earlier.
+ pin_at = source.rindex('req = REQ_ROOT / "diffusers-pin.txt"')
later = [
name
for name in (
@@ -963,3 +999,175 @@ def test_the_startup_prefetch_fills_the_cache_and_never_the_environment(monkeypa
assert module._prefetch_diffusers_main() == 2
monkeypatch.setattr(module, "_bootstrap_uv", lambda: False)
assert module._prefetch_diffusers_main() == 1 and len(runs) == 2, "pip has no cache to fill"
+
+
+def _release_module(
+ monkeypatch,
+ name,
+ installed = "0.41.0",
+):
+ module = _probe_module(name, active = False)
+ monkeypatch.delenv("UNSLOTH_DIFFUSERS_MAIN", raising = False)
+ monkeypatch.setattr(
+ module,
+ "_installed_distribution_version",
+ lambda dist: installed if dist == "diffusers" else None,
+ )
+ monkeypatch.setattr(module, "_payload_recorded_intact", lambda dist: installed is not None)
+ monkeypatch.setattr(module, "_recorded_direct_url", lambda dist: None)
+ return module
+
+
+def test_a_missing_release_still_forces_the_pass(monkeypatch):
+ module = _release_module(monkeypatch, "install_python_stack_release_damaged", "0.41.0")
+ assert module._diffusers_main_needs_dependency_pass() is False
+ # Same-version damage would not converge: 11b's version check skips it.
+ monkeypatch.setattr(module, "_payload_recorded_intact", lambda dist: False)
+ assert module._diffusers_main_needs_dependency_pass() is False
+ module = _release_module(monkeypatch, "install_python_stack_release_missing", None)
+ assert module._diffusers_main_needs_dependency_pass() is True
+
+
+def test_the_shipped_main_step_skips_without_installing(monkeypatch):
+ module = _release_module(monkeypatch, "install_python_stack_release_step")
+ monkeypatch.setattr(module, "pip_install_try", lambda *a, **k: pytest.fail("installed"))
+ monkeypatch.setattr(module, "_has_working_git", lambda: pytest.fail("probed git"))
+ progressed, steps = [], {}
+ monkeypatch.setattr(module, "_progress", lambda label, *a, **k: progressed.append(label))
+ monkeypatch.setattr(module, "_record_step", lambda name, state: steps.__setitem__(name, state))
+ module._diffusers_main_step()
+ assert len(progressed) == 1 and "skipped" in progressed[0], progressed
+ assert steps == {"diffusers-main.txt": "skipped"}
+
+
+ "installed, forced",
+ [
+ ("0.41.0", False),
+ ("0.41.0.dev0", True),
+ ("0.41.0rc1", True),
+ ("0.42.0", False),
+ ("0.40.0", True),
+ ],
+)
+def test_the_fast_path_is_forced_only_by_a_release_behind_the_pin(monkeypatch, installed, forced):
+ module = _release_module(monkeypatch, "install_python_stack_release_fast", installed)
+ monkeypatch.setattr(module, "_has_working_git", lambda: pytest.fail("probed git"))
+ assert module._diffusers_release_target() == "0.41.0"
+ assert module._diffusers_main_needs_dependency_pass() is forced
+
+
+def test_a_git_or_zip_build_of_the_release_keeps_the_fast_path(monkeypatch):
+ module = _release_module(monkeypatch, "install_python_stack_release_built", "0.41.0.dev0")
+ for direct in ({"vcs_info": {"vcs": "git"}}, {"archive_info": {}}):
+ monkeypatch.setattr(module, "_recorded_direct_url", lambda dist, d = direct: dict(d, url = "x"))
+ assert module._diffusers_main_needs_dependency_pass() is False
+
+
+def test_the_release_prefetch_fetches_the_pin_into_scratch_only_when_behind(monkeypatch):
+ module = _release_module(monkeypatch, "install_python_stack_release_prefetch", "0.41.0")
+ monkeypatch.setattr(module.subprocess, "run", lambda *a, **k: pytest.fail("spawned"))
+ monkeypatch.setattr(module, "_bootstrap_uv", lambda: pytest.fail("bootstrapped uv"))
+ assert module._prefetch_diffusers_main() == 1
+
+ module = _release_module(monkeypatch, "install_python_stack_release_prefetch2", "0.40.0")
+ monkeypatch.setattr(module, "_bootstrap_uv", lambda: True)
+ monkeypatch.setattr(module, "_has_working_git", lambda: pytest.fail("probed git"))
+ calls = []
+
+ def run(cmd, **kwargs):
+ calls.append(cmd)
+ return module.subprocess.CompletedProcess(cmd, 0, "")
+
+ monkeypatch.setattr(module.subprocess, "run", run)
+ # Windows ARM64 rewrites the file to a filtered copy, so read what was asked for, not the path.
+ asked = []
+ real_effective = module._effective_requirements
+ monkeypatch.setattr(
+ module,
+ "_effective_requirements",
+ lambda req: asked.append(req.name) or real_effective(req),
+ )
+ assert module._prefetch_diffusers_main() == 0
+ (cmd,) = calls
+ assert "--target" in cmd and "--no-deps" not in cmd
+ assert asked == ["diffusers-pin.txt"]
+ assert "-c" in cmd and str(cmd[cmd.index("-c") + 1]).endswith("constraints.txt"), cmd
+
+
+def _release_repair(
+ monkeypatch,
+ name,
+ installed,
+ manifest = None,
+ install_ok = True,
+):
+ import contextlib
+
+ state = {"version": installed}
+ module = _release_module(monkeypatch, name)
+ monkeypatch.setattr(
+ module,
+ "_installed_distribution_version",
+ lambda dist: state["version"] if dist == "diffusers" else None,
+ )
+ monkeypatch.setattr(
+ module.install_manifest, "pass_lock", lambda *a, **k: contextlib.nullcontext(True)
+ )
+ monkeypatch.setattr(module.install_manifest, "read_manifest", lambda *a, **k: manifest or {})
+ recorded = []
+ monkeypatch.setattr(
+ module.install_manifest, "update_manifest", lambda **extra: recorded.append(extra)
+ )
+ monkeypatch.setattr(module, "_bootstrap_uv", lambda: True)
+ monkeypatch.setattr(module, "_progress", lambda *a, **k: None)
+ monkeypatch.setattr(module, "_diffusers_main_step", lambda: pytest.fail("ran the git step"))
+ installs = []
+
+ def fake_install(
+ label,
+ *args,
+ req = None,
+ **kwargs,
+ ):
+ installs.append(req)
+ if install_ok:
+ state["version"] = "0.41.0"
+ return install_ok
+
+ monkeypatch.setattr(module, "pip_install_try", fake_install)
+ return module, installs, recorded
+
+
+def test_the_startup_repair_installs_the_release_behind_the_pin(monkeypatch):
+ # An old git-main failure must not strand the PyPI release.
+ old = {"diffusers_main_repair": "failed", "step_results": {"diffusers-main.txt": "failed"}}
+ module, installs, recorded = _release_repair(monkeypatch, "rel_repair_ok", "0.40.0", old)
+ assert module._repair_diffusers_main() == 0
+ assert [req.name for req in installs] == ["diffusers-pin.txt"] and recorded == []
+
+
+def test_the_startup_repair_leaves_a_current_release_alone(monkeypatch):
+ for installed in ("0.41.0", "0.41.0.post1"):
+ module, installs, _ = _release_repair(monkeypatch, "rel_repair_noop", installed)
+ assert module._repair_diffusers_main() == 1 and installs == []
+
+
+def test_the_release_repair_leaves_a_user_build_alone(monkeypatch):
+ module, installs, _ = _release_repair(monkeypatch, "rel_repair_user", "0.40.0")
+ monkeypatch.setattr(
+ module, "_recorded_direct_url", lambda dist: {"url": "file:///x", "dir_info": {}}
+ )
+ assert module._repair_diffusers_main() == 1 and installs == []
+
+
+def test_a_failed_release_repair_is_recorded_and_not_retried(monkeypatch):
+ module, installs, recorded = _release_repair(
+ monkeypatch, "rel_repair_fail", "0.40.0", install_ok = False
+ )
+ assert module._repair_diffusers_main() == 2 and len(installs) == 1
+ assert recorded == [{"diffusers_release_repair": "failed"}]
+ module, installs, _ = _release_repair(
+ monkeypatch, "rel_repair_fail2", "0.40.0", {"diffusers_release_repair": "failed"}
+ )
+ assert module._repair_diffusers_main() == 1 and installs == []