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: route Qwen-Image-Edit / Edit-2509 / Edit-2511 and FLUX.1-Kontext GGUFs to the native sd.cpp engine (#12776)

Daniel Hancc498c83f146
diff --git a/studio/backend/core/inference/diffusion_families.py b/studio/backend/core/inference/diffusion_families.py
index 0b1307b450f..533e670958c 100644
--- a/studio/backend/core/inference/diffusion_families.py
+++ b/studio/backend/core/inference/diffusion_families.py
@@ -335,6 +335,12 @@ _FAMILIES: tuple[DiffusionFamily, ...] = (
base_repo = "black-forest-labs/FLUX.1-Kontext-dev",
aliases = ("flux.1-kontext-dev", "flux1-kontext", "flux-kontext", "kontext"),
edit = True,
+ # Native: FLUX.1's VAE + CLIP-L / T5-XXL, the source as a reference image (sd.cpp docs/kontext.md).
+ sd_cpp_vae = ("black-forest-labs/FLUX.1-schnell", "ae.safetensors"),
+ sd_cpp_text_encoders = (
+ ("unsloth/flux-text-encoders", "clip_l.safetensors", "clip_l"),
+ ("unsloth/flux-text-encoders", "t5xxl_fp16.safetensors", "t5xxl"),
+ ),
),
DiffusionFamily(
# Qwen instruction editing: the 2511 checkpoint ships as QwenImageEditPlusPipeline. Specific aliases first so
@@ -358,6 +364,19 @@ _FAMILIES: tuple[DiffusionFamily, ...] = (
edit = True,
# same DiT as qwen-image
fp16_incompatible = True,
+ # Native: qwen-image's VAE + Qwen2.5-VL, plus its projector (edits read the source through the VLM; a GGUF
+ # encoder has no vision weights). 2511 needs no flag: sd.cpp keys zero_cond_t off __index_timestep_zero__.
+ sd_cpp_vae = ("unsloth/Qwen-Image-ComfyUI", "split_files/vae/qwen_image_vae.safetensors"),
+ sd_cpp_text_encoders = (
+ (
+ "unsloth/Qwen2.5-VL-7B-Instruct-GGUF",
+ "Qwen2.5-VL-7B-Instruct-Q4_K_M.gguf",
+ "qwen2vl",
+ ),
+ ("unsloth/Qwen2.5-VL-7B-Instruct-GGUF", "mmproj-F16.gguf", "llm_vision"),
+ ),
+ sd_cpp_sampling_method = "euler",
+ sd_cpp_flow_shift = 3.0,
),
DiffusionFamily(
name = "qwen-image",
diff --git a/studio/backend/core/inference/sd_cpp_args.py b/studio/backend/core/inference/sd_cpp_args.py
index ce8979c81ea..d5968bf2278 100644
--- a/studio/backend/core/inference/sd_cpp_args.py
+++ b/studio/backend/core/inference/sd_cpp_args.py
@@ -31,11 +31,13 @@ _TE_FLAGS_BY_FAMILY: dict[str, tuple[str, ...]] = {
"flux.2-klein": ("--llm",),
"flux.2-dev": ("--llm",),
"qwen-image": ("--qwen2vl",),
+ "qwen-image-edit": ("--qwen2vl",),
# 2.1 conditions on Qwen3-VL, which sd-cli takes through --llm. --qwen2vl is an alias of --llm
# that also turns on Qwen2-VL's vision path, so it is the wrong door even though both names
# reach the same field.
"qwen-image-2.1": ("--llm",),
"flux.1": ("--clip_l", "--t5xxl"),
+ "flux.1-kontext": ("--clip_l", "--t5xxl"),
}
diff --git a/studio/backend/core/inference/sd_cpp_backend.py b/studio/backend/core/inference/sd_cpp_backend.py
index 85b99238146..52820d00749 100644
--- a/studio/backend/core/inference/sd_cpp_backend.py
+++ b/studio/backend/core/inference/sd_cpp_backend.py
@@ -1809,6 +1809,11 @@ def _native_output_image(fam: Any, im: Any) -> Any:
return im.convert("RGB")
+def _family_reads_vision(fam: Any) -> bool:
+ """Whether ``fam``'s native encoders include a vision projector (``llm_vision``)."""
+ return any(kind == "llm_vision" for _r, _f, kind in getattr(fam, "sd_cpp_text_encoders", ()))
+
+
# Carried only by sd.cpp builds that keep reference alpha (upstream e112ab5) and no longer centre-crop references
# on sd-server (78557f8 / e012065). The pinned build predates all three.
_REFERENCE_FIDELITY_MARKER = "error: allocate memory for channel promotion"
@@ -1824,25 +1829,50 @@ def _native_condition_images(
*,
full_fidelity: bool,
pad_to_output: bool,
+ source_sized: bool = False,
) -> tuple[int, int, list[bytes]]:
"""(width, height, ordered PNG bytes) for one native reference / edit call, decoded through
- the diffusers engine's helper. A ``full_fidelity`` build gets every image as decoded. An older
+ the diffusers engine's helper. ``source_sized`` (edit-only families): the output is the source's size on
+ the family grid, whatever width / height asked for. A ``full_fidelity`` build gets every image as decoded. An older
build reads references as RGB, so each is flattened over white first (else transparent pixels
become noise), and its sd-server centre-crops references to the output aspect, so with
``pad_to_output`` each is padded to it instead: white for images, black for a separate mask.
"""
import io
+ import math
from PIL import Image
from core.inference.diffusion_conditioning import (
+ MIN_OUTPUT_SIDE,
check_output_size,
decode_condition_images,
match_source_size,
)
images = decode_condition_images(fam, init_image, reference_images, localized_edit)
- if width is None or height is None:
+ if source_sized:
+ multiple = int(getattr(fam, "dimension_multiple", 16) or 16)
+ sw, sh = images[0].size
+ max_side = int(getattr(fam, "max_output_side", 2048) or 2048)
+ max_pixels = int(getattr(fam, "max_output_pixels", 2048 * 2048) or 2048 * 2048)
+ # Fit the bounds instead of refusing: the caller has no width / height to change on an edit-only family.
+ up = max(1.0, MIN_OUTPUT_SIDE / float(min(sw, sh)))
+ fit = min(up, max_side / float(max(sw, sh)), math.sqrt(max_pixels / float(sw * sh)))
+ # Same rounding as diffusion._snap_to_multiple.
+ floor = -(-MIN_OUTPUT_SIDE // multiple) * multiple if up > 1.0 else multiple
+ width = max(floor if sw <= sh else multiple, int(round(sw * fit / multiple)) * multiple)
+ height = max(floor if sh <= sw else multiple, int(round(sh * fit / multiple)) * multiple)
+ width = min(width, max_side // multiple * multiple)
+ height = min(height, max_side // multiple * multiple)
+ while width * height > max_pixels:
+ if width >= height:
+ width -= multiple
+ else:
+ height -= multiple
+ if (width, height) != (sw, sh):
+ images[0] = images[0].resize((width, height), Image.LANCZOS)
+ elif width is None or height is None:
width, height = match_source_size(fam, images[0].size, 1024)
check_output_size(fam, int(width), int(height))
target = float(width) / float(height)
@@ -2863,6 +2893,7 @@ class SdCppDiffusionBackend:
hf_token,
cancel_event = cancel_event,
local_files_only = local_files_only,
+ vision_optional = not getattr(fam, "edit", False),
)
files = SdCppModelFiles(
@@ -3455,6 +3486,7 @@ class SdCppDiffusionBackend:
hf_token: Optional[str],
cancel_event: Optional[threading.Event] = None,
local_files_only: bool = False,
+ vision_optional: bool = True,
) -> dict[str, str]:
"""Download every asset (cancellable via this load's own ``cancel_event``, so a replacement
load cannot un-cancel this pull), returning kind -> local path. ``local_files_only``
@@ -3498,7 +3530,7 @@ class SdCppDiffusionBackend:
# (unreachable) online case rather than relabelled, so nothing changes when the flag is off.
if not local_files_only:
raise
- if kind == "llm_vision":
+ if kind == "llm_vision" and vision_optional:
# Only editing reads the projector, and edit is offered only when it is loaded. A
# Qwen-Image-2.1 GGUF cached before the projector was listed still loads for
# text-to-image; opening it from the Images page fetches the projector.
@@ -3590,13 +3622,18 @@ class SdCppDiffusionBackend:
)
def _native_edit_ready(self, state: Optional[_SdState]) -> bool:
- """Whether this load can run the unified edit workflow natively: a unified-edit family, its
- vision projector loaded, and a build carrying the family's edit marker."""
+ """Whether this load can run an edit natively: unified-edit needs its projector and the build's edit marker;
+ edit-only needs its projector if it declares one, and the marker only if it declares one."""
if state is None:
return False
fam = state.family
marker = getattr(fam, "sd_cpp_edit_marker", None)
- if not (getattr(fam, "unified_edit", False) and marker and state.files.llm_vision):
+ if getattr(fam, "edit", False):
+ if _family_reads_vision(fam) and not state.files.llm_vision:
+ return False
+ if not marker:
+ return True
+ elif not (getattr(fam, "unified_edit", False) and marker and state.files.llm_vision):
return False
binary = self._native_binary(state)
if not binary:
@@ -3643,6 +3680,15 @@ class SdCppDiffusionBackend:
from core.inference import diffusion_lora
+ # Edit-only families: an input image with no workflow is an edit (re-checked under the lock below).
+ loaded = self._state
+ if (
+ workflow is None
+ and init_image is not None
+ and loaded is not None
+ and getattr(loaded.family, "edit", False)
+ ):
+ workflow = "edit"
conditioned = workflow in ("edit", "reference")
if conditioned:
if init_image is None:
@@ -3709,6 +3755,21 @@ class SdCppDiffusionBackend:
self._gen = _SdGen(total_steps = int(steps))
try:
ref_pngs: list[bytes] = []
+ edit_only = bool(getattr(state.family, "edit", False))
+ if edit_only and not conditioned:
+ raise ValueError(
+ f"{state.family.name} is an image-editing model: provide an input image."
+ )
+ if edit_only and workflow == "reference":
+ raise ValueError(
+ f"The reference workflow is not supported for the '{state.family.name}' "
+ "model family."
+ )
+ if reference_images and not getattr(state.family, "reference", False):
+ raise ValueError(
+ f"Reference images are not supported for the '{state.family.name}' "
+ "model family."
+ )
if conditioned:
from core.inference.diffusion_conditioning import check_conditioned_fields
@@ -3735,6 +3796,7 @@ class SdCppDiffusionBackend:
height,
full_fidelity = self._native_reference_fidelity(state),
pad_to_output = state.mode == "server" and state.server is not None,
+ source_sized = edit_only,
)
elif width is None or height is None:
raise ValueError("width and height are required for this workflow.")
@@ -4322,16 +4384,20 @@ class SdCppDiffusionBackend:
from core.inference.diffusion_conditioning import conditioning_capabilities
from hub.utils.gguf import extract_quant_token
- workflows = ["txt2img"]
- if self._native_edit_ready(state):
- workflows += ["reference", "edit"]
+ if getattr(state.family, "edit", False):
+ workflows = ["edit"] if self._native_edit_ready(state) else []
+ else:
+ workflows = ["txt2img"]
+ if self._native_edit_ready(state):
+ workflows += ["reference", "edit"]
conditioning = conditioning_capabilities(state.family, workflows)
# No reference detail natively: sd.cpp sizes inputs to the output area.
conditioning["reference_resolutions"] = []
full_fidelity = self._native_reference_fidelity(state)
conditioning["alpha"] = full_fidelity
notes: list[str] = []
- if "edit" in workflows:
+ # The alpha / padding notes are about the unified family's RGBA path; edit-only families are RGB, source-sized.
+ if "edit" in workflows and not getattr(state.family, "edit", False):
if not full_fidelity:
notes.append(
"Transparent parts of input images are filled with white on this native build."
diff --git a/studio/backend/tests/test_diffusion_engine_load_contract.py b/studio/backend/tests/test_diffusion_engine_load_contract.py
index 96aaea20eb3..d320cd4c311 100644
--- a/studio/backend/tests/test_diffusion_engine_load_contract.py
+++ b/studio/backend/tests/test_diffusion_engine_load_contract.py
@@ -200,6 +200,7 @@ def test_a_cache_only_native_load_makes_no_hub_call(monkeypatch):
token,
cancel_event = None,
local_files_only = False,
+ vision_optional = True,
):
fetched.append(local_files_only)
raise RuntimeError("stop here; the Hub calls under test all precede the fetch")
diff --git a/studio/backend/tests/test_diffusion_gated_base.py b/studio/backend/tests/test_diffusion_gated_base.py
index 0c59259ea76..c28fa5b093a 100644
--- a/studio/backend/tests/test_diffusion_gated_base.py
+++ b/studio/backend/tests/test_diffusion_gated_base.py
@@ -672,6 +672,7 @@ def _native_backend_ready(monkeypatch):
token,
cancel_event = None,
local_files_only = False,
+ vision_optional = True,
):
fetched.append(assets)
raise AssertionError("the gated companion must be caught before any byte is fetched")
diff --git a/studio/backend/tests/test_sd_cpp_backend.py b/studio/backend/tests/test_sd_cpp_backend.py
index ecd40814a30..9af70b011e2 100644
--- a/studio/backend/tests/test_sd_cpp_backend.py
+++ b/studio/backend/tests/test_sd_cpp_backend.py
@@ -771,6 +771,18 @@ _FLUX_DEFAULT_GUIDANCE_CASES = [
]
+def _edit_source(fam_name):
+ """Kontext is edit-only on both engines: it renders from a source image, never from text alone."""
+ if detect_family(fam_name).edit:
+ import base64
+ import io
+
+ buf = io.BytesIO()
+ Image.new("RGB", (512, 512), (10, 20, 30)).save(buf, format = "PNG")
+ return {"init_image": base64.b64encode(buf.getvalue()).decode()}
+ return {}
+
+
@pytest.mark.parametrize("repo_id,fam_name,cfg,distilled", _FLUX_DEFAULT_GUIDANCE_CASES)
def test_flux_oneshot_argv_sends_explicit_cfg(repo_id, fam_name, cfg, distilled):
from core.inference.diffusion_families import default_generation_params
@@ -779,7 +791,7 @@ def test_flux_oneshot_argv_sends_explicit_cfg(repo_id, fam_name, cfg, distilled)
steps, guidance = default_generation_params(repo_id)
eng = _FakeEngine()
b = _loaded_backend(fam_name, engine = eng)
- b.generate(prompt = "a fox", steps = steps, guidance = guidance, seed = 1)
+ b.generate(prompt = "a fox", steps = steps, guidance = guidance, seed = 1, **_edit_source(fam_name))
files, params, out, _kw = eng.calls[-1]
argv = build_sd_cpp_command("/bin/sd-cli", files, params, output_path = str(out))
assert float(argv[argv.index("--cfg-scale") + 1]) == cfg
@@ -799,7 +811,7 @@ def test_flux_server_request_sends_txt_cfg(repo_id, fam_name, cfg, distilled):
b = _loaded_backend(fam_name)
server = _FakeServer("/bin/sd-server")
b._state = dataclasses.replace(b._state, mode = "server", server = server)
- b.generate(prompt = "a fox", steps = steps, guidance = guidance, seed = 1)
+ b.generate(prompt = "a fox", steps = steps, guidance = guidance, seed = 1, **_edit_source(fam_name))
g = server.payloads[-1]["sample_params"]["guidance"]
assert g["txt_cfg"] == cfg
assert g.get("distilled_guidance") == distilled
diff --git a/studio/backend/tests/test_sd_cpp_edit_families.py b/studio/backend/tests/test_sd_cpp_edit_families.py
new file mode 100644
index 00000000000..6b75ba5b89e
--- /dev/null
+++ b/studio/backend/tests/test_sd_cpp_edit_families.py
@@ -0,0 +1,397 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Native (sd.cpp) routes for the edit-only families: Qwen-Image-Edit (the original, 2509 and
+2511 checkpoints) and FLUX.1-Kontext. The asset mapping, the guidance each one is sent, the
+readiness gate and advertised workflows, and the source image on both transports: a
+``--ref-image`` on the one-shot sd-cli argv and a ``ref_images`` entry in the sd-server body."""
+
+from __future__ import annotations
+
+import base64
+import io
+import types
+
+import pytest
+from PIL import Image
+
+from core.inference import sd_cpp_backend as bk
+from core.inference.diffusion_families import (
+ detect_family,
+ detect_family_for_pick,
+ family_sd_cpp_supported,
+ sd_cpp_companion_only_repo_ids,
+)
+from core.inference.sd_cpp_args import (
+ SdCppModelFiles,
+ build_sd_cpp_command,
+ text_encoder_flags_for_family,
+)
+from core.inference.sd_cpp_backend import SdCppDiffusionBackend
+
+from .test_sd_cpp_backend import _FakeEngine, _FakeServer
+
+QWEN_EDIT = detect_family("unsloth/Qwen-Image-Edit-2511-GGUF")
+KONTEXT = detect_family("unsloth/FLUX.1-Kontext-dev-GGUF")
+
+QWEN_PICKS = (
+ ("unsloth/Qwen-Image-Edit-GGUF", "qwen-image-edit-Q4_K_M.gguf"),
+ ("unsloth/Qwen-Image-Edit-2509-GGUF", "qwen-image-edit-2509-Q4_K_M.gguf"),
+ ("unsloth/Qwen-Image-Edit-2511-GGUF", "qwen-image-edit-2511-Q4_K_M.gguf"),
+)
+
+QWEN_FILES = SdCppModelFiles(
+ diffusion_model = "/m/qwen-image-edit-2511-Q4_K_M.gguf",
+ vae = "/m/qwen_image_vae.safetensors",
+ qwen2vl = "/m/Qwen2.5-VL-7B-Instruct-Q4_K_M.gguf",
+ llm_vision = "/m/mmproj-F16.gguf",
+)
+KONTEXT_FILES = SdCppModelFiles(
+ diffusion_model = "/m/flux1-kontext-dev-Q4_K_M.gguf",
+ vae = "/m/ae.safetensors",
+ clip_l = "/m/clip_l.safetensors",
+ t5xxl = "/m/t5xxl_fp16.safetensors",
+)
+
+
+def _png(size = (770, 500), color = (200, 10, 10)) -> str:
+ buf = io.BytesIO()
+ Image.new("RGB", size, color).save(buf, format = "PNG")
+ return base64.b64encode(buf.getvalue()).decode()
+
+
+def _state(
+ fam,
+ files,
+ *,
+ mode = "oneshot",
+ server = None,
+):
+ return bk._SdState(
+ repo_id = "unsloth/x-GGUF",
+ base_repo = fam.base_repo,
+ family = fam,
+ device = "cpu",
+ files = files,
+ sampling_method = fam.sd_cpp_sampling_method,
+ flow_shift = fam.sd_cpp_flow_shift,
+ mode = mode,
+ server = server,
+ )
+
+
+def _server_state(fam, files):
+ server = _FakeServer("sd-server")
+ return _state(fam, files, mode = "server", server = server), server
+
+
+# -- asset mapping ------------------------------------------------------------------------------
+
+
[email protected]("repo, filename", QWEN_PICKS)
+def test_every_qwen_edit_checkpoint_maps_to_vae_encoder_and_projector(repo, filename):
+ fam = detect_family_for_pick(repo, filename)
+ assert fam is QWEN_EDIT and family_sd_cpp_supported(fam)
+ specs = SdCppDiffusionBackend(engine = _FakeEngine())._asset_specs(repo, filename, fam)
+ assert specs == [
+ (repo, filename, "diffusion_model"),
+ ("unsloth/Qwen-Image-ComfyUI", "split_files/vae/qwen_image_vae.safetensors", "vae"),
+ (
+ "unsloth/Qwen2.5-VL-7B-Instruct-GGUF",
+ "Qwen2.5-VL-7B-Instruct-Q4_K_M.gguf",
+ "qwen2vl",
+ ),
+ ("unsloth/Qwen2.5-VL-7B-Instruct-GGUF", "mmproj-F16.gguf", "llm_vision"),
+ ]
+ assert (fam.sd_cpp_sampling_method, fam.sd_cpp_flow_shift) == ("euler", 3.0)
+ assert text_encoder_flags_for_family(fam.name) == ("--qwen2vl",)
+
+
+def test_kontext_maps_to_the_flux1_assets():
+ fam = detect_family_for_pick("unsloth/FLUX.1-Kontext-dev-GGUF", "flux1-kontext-dev-Q4_K_M.gguf")
+ assert fam is KONTEXT and family_sd_cpp_supported(fam)
+ flux1 = detect_family("unsloth/FLUX.1-dev-GGUF")
+ assert fam.sd_cpp_vae == flux1.sd_cpp_vae
+ assert fam.sd_cpp_text_encoders == flux1.sd_cpp_text_encoders
+ specs = SdCppDiffusionBackend(engine = _FakeEngine())._asset_specs(
+ "unsloth/FLUX.1-Kontext-dev-GGUF", "flux1-kontext-dev-Q4_K_M.gguf", fam
+ )
+ assert [k for _r, _f, k in specs] == ["diffusion_model", "vae", "clip_l", "t5xxl"]
+ assert text_encoder_flags_for_family(fam.name) == ("--clip_l", "--t5xxl")
+
+
+def test_the_new_companions_stay_fetch_only_and_bases_stay_loadable():
+ companions = sd_cpp_companion_only_repo_ids()
+ assert "unsloth/qwen-image-comfyui" in companions
+ assert "unsloth/qwen2.5-vl-7b-instruct-gguf" in companions
+ # The FLUX.1 VAE lives in a real base; mapping Kontext onto it must not hide that base.
+ assert "black-forest-labs/flux.1-schnell" not in companions
+
+
+def test_layered_and_inpaint_variants_are_still_refused():
+ assert detect_family("unsloth/Qwen-Image-Layered-GGUF") is None
+ assert detect_family("someone/FLUX.1-dev-inpaint-GGUF") is None
+
+
+# -- guidance -----------------------------------------------------------------------------------
+
+
+def test_kontext_runs_one_pass_with_embedded_guidance():
+ assert bk._map_guidance(KONTEXT, 2.5) == (1.0, 2.5)
+ assert bk._map_guidance(KONTEXT, None) == (1.0, None)
+
+
[email protected]("guidance, cfg", [(4.0, 4.0), (2.5, 2.5), (1.0, 1.0), (0.0, 1.0)])
+def test_qwen_edit_uses_real_cfg_like_the_diffusers_true_cfg_scale(guidance, cfg):
+ assert bk._map_guidance(QWEN_EDIT, guidance) == (cfg, None)
+
+
+# -- readiness and advertised workflows --------------------------------------------------------
+
+
+def test_edit_only_families_advertise_edit_and_never_txt2img():
+ b = SdCppDiffusionBackend(engine = _FakeEngine())
+ for fam, files in ((QWEN_EDIT, QWEN_FILES), (KONTEXT, KONTEXT_FILES)):
+ b._state = _state(fam, files)
+ status = b.status()
+ assert status["workflows"] == ["edit"], fam.name
+ assert status["conditioning"]["unified_edit"] is False
+ assert status["conditioning"]["localized_edit_modes"] == []
+ assert status["conditioning"]["notes"] == []
+
+
+def test_qwen_edit_without_its_projector_is_not_edit_ready():
+ b = SdCppDiffusionBackend(engine = _FakeEngine())
+ no_vision = SdCppModelFiles(
+ diffusion_model = "/m/q.gguf", vae = "/m/vae.safetensors", qwen2vl = "/m/llm.gguf"
+ )
+ b._state = _state(QWEN_EDIT, no_vision)
+ assert b.status()["workflows"] == []
+ with pytest.raises(ValueError, match = "Image editing is not available"):
+ b.generate(prompt = "p", steps = 2, init_image = _png())
+
+
+# -- one-shot sd-cli ----------------------------------------------------------------------------
+
+
[email protected]("workflow", [None, "edit"])
+def test_oneshot_kontext_sends_the_source_as_a_ref_image_at_its_own_size(monkeypatch, workflow):
+ engine = _FakeEngine()
+ b = SdCppDiffusionBackend(engine = engine)
+ b._state = _state(KONTEXT, KONTEXT_FILES)
+ seen = {}
+ real_generate = engine.generate
+
+ def _capture(files, params, output_path, **kw):
+ seen["ref"] = Image.open(params.ref_images[0]).copy()
+ seen["argv"] = build_sd_cpp_command(
+ "sd-cli", files, params, output_path = output_path, extra_args = kw.get("extra_args")
+ )
+ return real_generate(files, params, output_path = output_path, **kw)
+
+ monkeypatch.setattr(engine, "generate", _capture)
+ out = b.generate(
+ prompt = "make it night",
+ steps = 20,
+ guidance = 2.5,
+ seed = 7,
+ width = 1024,
+ height = 1024,
+ init_image = _png(),
+ workflow = workflow,
+ )
+ argv = seen["argv"]
+ assert [argv[i + 1] for i, a in enumerate(argv) if a == "--ref-image"] == [
+ engine.calls[0][1].ref_images[0]
+ ]
+ # Source-sized as on the diffusers engine: 770x500 snaps to 768x496, the requested 1024 is ignored.
+ assert argv[argv.index("--width") + 1] == "768" and argv[argv.index("--height") + 1] == "496"
+ assert seen["ref"].size == (768, 496)
+ assert (
+ argv[argv.index("--cfg-scale") + 1] == "1" and argv[argv.index("--guidance") + 1] == "2.5"
+ )
+ for flag, path in (
+ ("--vae", "/m/ae.safetensors"),
+ ("--clip_l", "/m/clip_l.safetensors"),
+ ("--t5xxl", "/m/t5xxl_fp16.safetensors"),
+ ):
+ assert argv[argv.index(flag) + 1] == path
+ assert "--init-img" not in argv and "--strength" not in argv and "--llm_vision" not in argv
+ assert out["workflow"] == "edit"
+
+
+def test_oneshot_qwen_edit_sends_projector_cfg_and_flow_shift(monkeypatch):
+ engine = _FakeEngine()
+ b = SdCppDiffusionBackend(engine = engine)
+ b._state = _state(QWEN_EDIT, QWEN_FILES)
+ b.generate(prompt = "p", steps = 20, guidance = 4.0, seed = 1, init_image = _png((768, 768)))
+ files, params, out_path, kw = engine.calls[0]
+ argv = build_sd_cpp_command(
+ "sd-cli", files, params, output_path = out_path, extra_args = kw.get("extra_args")
+ )
+ assert argv[argv.index("--qwen2vl") + 1] == QWEN_FILES.qwen2vl
+ assert argv[argv.index("--llm_vision") + 1] == QWEN_FILES.llm_vision
+ assert argv.count("--ref-image") == 1
+ assert argv[argv.index("--cfg-scale") + 1] == "4" and "--guidance" not in argv
+ assert argv[argv.index("--sampling-method") + 1] == "euler"
+ assert argv[argv.index("--flow-shift") + 1] == "3.0"
+ assert (params.width, params.height) == (768, 768)
+
+
+# -- sd-server request body ---------------------------------------------------------------------
+
+
+ "fam, files, guidance, expect_guidance, expect_sampling",
+ [
+ (KONTEXT, KONTEXT_FILES, 2.5, {"txt_cfg": 1.0, "distilled_guidance": 2.5}, {}),
+ (
+ QWEN_EDIT,
+ QWEN_FILES,
+ 4.0,
+ {"txt_cfg": 4.0},
+ {"sample_method": "euler", "flow_shift": 3.0},
+ ),
+ ],
+)
+def test_server_body_carries_the_source_as_the_one_ref_image(
+ fam, files, guidance, expect_guidance, expect_sampling
+):
+ b = SdCppDiffusionBackend(engine = _FakeEngine())
+ b._state, server = _server_state(fam, files)
+ b.generate(prompt = "p", steps = 20, guidance = guidance, seed = 3, init_image = _png(), workflow = "edit")
+ body = server.payloads[-1]
+ assert (body["width"], body["height"]) == (768, 496)
+ assert body["sample_params"]["guidance"] == expect_guidance
+ for key, value in expect_sampling.items():
+ assert body["sample_params"][key] == value
+ assert body["seed"] == 3 and body["batch_count"] == 1
+ assert len(body["ref_images"]) == 1
+ head, b64 = body["ref_images"][0].split(",", 1)
+ assert head == "data:image/png;base64"
+ ref = Image.open(io.BytesIO(base64.b64decode(b64)))
+ assert ref.size == (768, 496) and ref.mode == "RGB"
+ assert "init_image" not in body and "mask_image" not in body and "strength" not in body
+
+
+# -- refusals, matching the diffusers engine ----------------------------------------------------
+
+
[email protected]("fam, files", [(QWEN_EDIT, QWEN_FILES), (KONTEXT, KONTEXT_FILES)])
+def test_edit_only_families_refuse_what_the_diffusers_engine_refuses(fam, files):
+ b = SdCppDiffusionBackend(engine = _FakeEngine())
+ b._state = _state(fam, files)
+ with pytest.raises(ValueError, match = "is an image-editing model: provide an input image"):
+ b.generate(prompt = "p", steps = 2, width = 512, height = 512)
+ with pytest.raises(ValueError, match = "reference workflow is not supported"):
+ b.generate(prompt = "p", steps = 2, init_image = _png(), workflow = "reference")
+ with pytest.raises(ValueError, match = "Reference images are not supported"):
+ b.generate(prompt = "p", steps = 2, init_image = _png(), reference_images = [_png()])
+ with pytest.raises(ValueError, match = "mask_image is not supported"):
+ b.generate(prompt = "p", steps = 2, init_image = _png(), mask_image = _png())
+
+
+def test_a_text_to_image_family_keeps_refusing_an_input_image():
+ b = SdCppDiffusionBackend(engine = _FakeEngine())
+ flux1 = detect_family("unsloth/FLUX.1-dev-GGUF")
+ b._state = _state(flux1, KONTEXT_FILES)
+ with pytest.raises(ValueError, match = "not yet supported on the native"):
+ b.generate(prompt = "p", steps = 2, init_image = _png())
+ assert b.status()["workflows"] == ["txt2img"]
+
+
+def test_unified_edit_readiness_is_unchanged(tmp_path):
+ q21 = detect_family("unsloth/Qwen-Image-2.1-GGUF")
+ files = SdCppModelFiles(diffusion_model = "/m/q.gguf", llm = "/m/llm.gguf", llm_vision = "/m/v.gguf")
+ binary = tmp_path / "sd-server"
+ binary.write_bytes(b"no marker here")
+ b = SdCppDiffusionBackend(engine = _FakeEngine())
+ b._state = _state(
+ q21,
+ files,
+ mode = "server",
+ server = types.SimpleNamespace(binary = str(binary), is_alive = lambda: True),
+ )
+ assert b.status()["workflows"] == ["txt2img"]
+ binary.write_bytes(q21.sd_cpp_edit_marker.encode())
+ assert b.status()["workflows"] == ["txt2img", "reference", "edit"]
+
+
+def test_source_size_snaps_like_the_diffusers_engine_and_fits_an_oversized_source():
+ from core.inference.diffusion import _snap_to_multiple
+
+ for size in ((770, 500), (776, 520), (1000, 1000), (513, 1999)):
+ w, h, _blobs = bk._native_condition_images(
+ KONTEXT,
+ _png(size),
+ None,
+ None,
+ 1024,
+ 1024,
+ full_fidelity = False,
+ pad_to_output = True,
+ source_sized = True,
+ )
+ assert (w, h) == _snap_to_multiple(Image.new("RGB", size)).size, size
+ # 4000x3000 exceeds the 2048 side / 2048*2048 pixel bounds: scaled to fit, aspect kept, never refused.
+ w, h, blobs = bk._native_condition_images(
+ QWEN_EDIT,
+ _png((4000, 3000)),
+ None,
+ None,
+ None,
+ None,
+ full_fidelity = False,
+ pad_to_output = False,
+ source_sized = True,
+ )
+ assert (w, h) == (2048, 1536)
+ assert Image.open(io.BytesIO(blobs[0])).size == (2048, 1536)
+
+
+ "size,expected", [((64, 64), (256, 256)), ((200, 100), (512, 256)), ((100, 300), (256, 768))]
+)
+def test_a_source_below_the_minimum_side_is_scaled_up_not_refused(size, expected):
+ # The diffusers engine edits a small source at its own size; the native size check would refuse it, and an
+ # edit-only call has no width / height to change, so the source is scaled up to the minimum side.
+ w, h, blobs = bk._native_condition_images(
+ QWEN_EDIT,
+ _png(size),
+ None,
+ None,
+ None,
+ None,
+ full_fidelity = False,
+ pad_to_output = False,
+ source_sized = True,
+ )
+ assert (w, h) == expected
+ assert Image.open(io.BytesIO(blobs[0])).size == expected
+
+
+def test_an_uncached_projector_fails_an_offline_edit_only_load(monkeypatch, tmp_path):
+ # An edit-only family has no workflow without its projector, so a cache-only load must not succeed without it.
+ from huggingface_hub.errors import LocalEntryNotFoundError
+
+ import utils.hf_xet_fallback as xet
+
+ cached = tmp_path / "Qwen2.5-VL-7B-Instruct-Q4_K_M.gguf"
+ cached.write_bytes(b"")
+
+ def _download(repo_id, filename, token, **kwargs):
+ if filename == "mmproj-F16.gguf":
+ raise LocalEntryNotFoundError("Cannot find the requested files in the disk cache")
+ return str(cached)
+
+ monkeypatch.setattr(xet, "hf_hub_download_with_xet_fallback", _download)
+ repo = "unsloth/Qwen2.5-VL-7B-Instruct-GGUF"
+ assets = [(repo, cached.name, "qwen2vl"), (repo, "mmproj-F16.gguf", "llm_vision")]
+ with pytest.raises(RuntimeError, match = "mmproj-F16.gguf"):
+ SdCppDiffusionBackend(engine = None)._fetch_assets(
+ assets, None, local_files_only = True, vision_optional = False
+ )
+ # The unified family's text-to-image load keeps skipping it.
+ assert SdCppDiffusionBackend(engine = None)._fetch_assets(
+ assets, None, local_files_only = True
+ ) == {"qwen2vl": str(cached)}