Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Studio Images: run Detailer inpaints eager and uncounted (#15063)
Daniel Hanb276691bb5aa
diff --git a/studio/backend/core/inference/diffusion.py b/studio/backend/core/inference/diffusion.pyindex 95cb17b1b13..a44a36afb9e 100644--- a/studio/backend/core/inference/diffusion.py+++ b/studio/backend/core/inference/diffusion.py@@ -13119,6 +13119,9 @@ class DiffusionBackend:bg = Nonebg_eager = Falsebg_token = None+ # A Detailer crop inpaint (diffusion_bg_compile.auxiliary_pass): eager, uncounted, nothing recorded.+ aux_pass = bg_compile.auxiliary()+ restore_eager_gate: Optional[Callable[[], None]] = Nonetry:self._state_device_target(state)# The local `state` ref keeps the pipe alive even if unload() nulls _state. Resolve the per-image@@ -13154,6 +13157,7 @@ class DiffusionBackend:if (state.speed_deferredand state.generation_count >= 2+ and not aux_passand not lora_requestedand not loras_attached):@@ -13170,6 +13174,11 @@ class DiffusionBackend:bg_eager = bg is not None and bg.pending()if bg_eager:bg_token = bg_compile._FORCE_EAGER.set(True)+ if aux_pass:+ # The force-eager signal never reaches a whole-module compiled U-Net on its own.+ restore_eager_gate = bg_compile.gate_compiled_eager(+ cuda_graph._denoiser_modules(state.pipe)+ )# Apply/adjust LoRA before picking the workflow pipe; from_pipe pipes share the transformer.self._apply_loras(state, loras, cancel)@@ -14148,7 +14157,9 @@ class DiffusionBackend:# a STATIC compile makes new artifacts per (w,h,batch), so register this shape. The write itself is# QUEUED, not performed: nothing in this response depends on it (only the NEXT process reads the# bundle), so save_async hands it to the shared worker and the user stops waiting on it.- if bg_eager:+ if aux_pass:+ pass+ elif bg_eager:# Nothing compiled ran, so nothing to register or save yet.bg.note_eager_generation()if _hires_pass is None or not _hires_pass.defer_bg_kick:@@ -14197,7 +14208,7 @@ class DiffusionBackend:# Components are offloaded and transfer copies dropped; return the pages now.reclaim_offload_host_memory(state.offload_policy, logger = logger)# Count the finished generation (drives deferred speed); a batch is one generation.- if _hires_pass is None or not _hires_pass.refine:+ if (_hires_pass is None or not _hires_pass.refine) and not aux_pass:object.__setattr__(state, "generation_count", state.generation_count + 1)result = {"images": list(images),@@ -14272,6 +14283,8 @@ class DiffusionBackend:applied_embeddings.restore()if bg_token is not None:bg_compile._FORCE_EAGER.reset(bg_token)+ if restore_eager_gate is not None:+ restore_eager_gate()if static_skip_pipe is not None:try:reset_static_step_skip(static_skip_pipe, None)diff --git a/studio/backend/core/inference/diffusion_bg_compile.py b/studio/backend/core/inference/diffusion_bg_compile.pyindex 7b2aeb010db..09645f49f54 100644--- a/studio/backend/core/inference/diffusion_bg_compile.py+++ b/studio/backend/core/inference/diffusion_bg_compile.py@@ -35,6 +35,9 @@ _NO_CAPTURE: contextvars.ContextVar[bool] = contextvars.ContextVar(_NO_RECORD: contextvars.ContextVar[bool] = contextvars.ContextVar("unsloth_diffusion_no_record", default = False)+_AUXILIARY: contextvars.ContextVar[bool] = contextvars.ContextVar(+ "unsloth_diffusion_auxiliary_pass", default = False+)def enabled() -> bool:@@ -67,6 +70,63 @@ def no_record():_NO_RECORD.reset(token)+def auxiliary() -> bool:+ return _AUXILIARY.get()+++def auxiliary_pass():+ """Detailer crop inpaints: eager, uncaptured, unrecorded, uncounted. Each box is its own size, so compiling+ them recompiled per detection and used up the per-module graph cap the main render needs."""+ tokens = (_AUXILIARY.set(True), _NO_RECORD.set(True), _FORCE_EAGER.set(True))+ try:+ yield+ finally:+ _FORCE_EAGER.reset(tokens[2])+ _NO_RECORD.reset(tokens[1])+ _AUXILIARY.reset(tokens[0])+++def gate_compiled_eager(modules: Any) -> Callable[[], None]:+ """Route ``Module.compile``d modules to eager ``_call_impl`` under ``force_eager``; returns the restore.+ Without it force_eager only reaches regional blocks and graph wrappers, which still call the compiled U-Net."""+ installed: list = []+ for module in modules or ():+ inner = getattr(module, "_compiled_call_impl", None)+ if inner is None:+ continue+ eager = getattr(module, "_call_impl", None)+ if eager is None:+ continue++ def gate(+ *args: Any,+ _inner: Any = inner,+ _eager: Any = eager,+ **kwargs: Any,+ ) -> Any:+ if _FORCE_EAGER.get():+ return _eager(*args, **kwargs)+ return _inner(*args, **kwargs)++ try:+ module._compiled_call_impl = gate+ except Exception: # noqa: BLE001 - not a settable module+ continue+ installed.append((module, gate, inner))++ def restore() -> None:+ for module, gate, inner in installed:+ try:+ if getattr(module, "_compiled_call_impl", None) is gate:+ module._compiled_call_impl = inner+ except Exception: # noqa: BLE001+ pass+ installed.clear()++ return restore++@contextlib.contextmanagerdef force_eager(on: bool = True):token = _FORCE_EAGER.set(bool(on))diff --git a/studio/backend/core/inference/diffusion_detailer.py b/studio/backend/core/inference/diffusion_detailer.pyindex 7493269c7f1..b5fc09a3dbf 100644--- a/studio/backend/core/inference/diffusion_detailer.py+++ b/studio/backend/core/inference/diffusion_detailer.py@@ -718,20 +718,24 @@ def _detail_images(inherited: dict = {}def _inpaint(crop, mask, seed, det_prompt, det_negative):- out = generate(- prompt = det_prompt,- negative_prompt = det_negative,- width = crop.width,- height = crop.height,- steps = step_count,- guidance = cfg,- seed = seed,- batch_size = 1,- init_image = _png_b64(crop),- mask_image = _png_b64(mask),- strength = settings.denoise,- **generate_kwargs,- )+ from core.inference import diffusion_bg_compile++ # Every box is its own size: run eager and uncounted so no crop compiles, captures or feeds the compiler.+ with diffusion_bg_compile.auxiliary_pass():+ out = generate(+ prompt = det_prompt,+ negative_prompt = det_negative,+ width = crop.width,+ height = crop.height,+ steps = step_count,+ guidance = cfg,+ seed = seed,+ batch_size = 1,+ init_image = _png_b64(crop),+ mask_image = _png_b64(mask),+ strength = settings.denoise,+ **generate_kwargs,+ )if not same_build(result, out):raise ValueError("the model changed")if det_negative and out.get("negative_prompt") and not result.get("negative_prompt"):diff --git a/studio/backend/tests/test_diffusion_backend.py b/studio/backend/tests/test_diffusion_backend.pyindex d1442e23ea1..f6086aa62fc 100644--- a/studio/backend/tests/test_diffusion_backend.py+++ b/studio/backend/tests/test_diffusion_backend.py@@ -1206,6 +1206,35 @@ def test_deferred_speed_skips_when_lora_requested(fake_runtime, tmp_path, monkeyassert len(engaged) == 1+def test_detailer_passes_neither_count_nor_engage_deferred_speed(+ fake_runtime, tmp_path, monkeypatch+):+ from core.inference import diffusion as dmod+ from core.inference import diffusion_bg_compile as bg++ monkeypatch.setattr(dmod, "compile_eligible", lambda *a, **k: True)+ engaged: list = []++ def fake_engage(self, state):+ engaged.append(state.generation_count)+ state.speed_deferred = False++ monkeypatch.setattr(DiffusionBackend, "_engage_deferred_speed", fake_engage)++ backend = _loaded_backend(+ tmp_path, gguf_filename = "model.safetensors", family_override = "qwen-image"+ )+ backend.generate(prompt = "one")+ backend.generate(prompt = "two")+ with bg.auxiliary_pass():+ for _ in range(3):+ backend.generate(prompt = "face")+ assert engaged == [], "a Detailer crop engaged the compile mid-pass"+ assert backend._state.generation_count == 2+ backend.generate(prompt = "three")+ assert engaged == [2]++def test_deferred_speed_skips_while_adapter_attached(fake_runtime, tmp_path, monkeypatch):from core.inference import diffusion as dmoddiff --git a/studio/backend/tests/test_diffusion_cold_start.py b/studio/backend/tests/test_diffusion_cold_start.pyindex d81ce4fc549..ec21fc8a802 100644--- a/studio/backend/tests/test_diffusion_cold_start.py+++ b/studio/backend/tests/test_diffusion_cold_start.py@@ -144,6 +144,60 @@ def test_recording_dedups_by_input_shape_and_ignores_unforced_calls():job.close()+def test_a_detailer_pass_neither_compiles_a_whole_compiled_unet_nor_feeds_the_recorder():+ """Detailer crops are box-dependent sizes: on a static whole-module compile each one was a fresh compile, and a+ pending background compile recorded them as the shapes to build."""+ counter = _Counter()+ net = _whole_compiled(counter)+ job = bg.arm(net)+ with torch.no_grad():+ with bg.force_eager():+ net(torch.randn(2, 8), return_dict = False)+ assert len(job.samples) == 1+ restore = bg.gate_compiled_eager([net])+ try:+ with bg.auxiliary_pass():+ assert bg.auxiliary() and bg.eager_forced()+ for rows in (3, 4, 5):+ net(torch.randn(rows, 8), return_dict = False)+ finally:+ restore()+ assert not bg.auxiliary() and not bg.eager_forced()+ assert (+ len(job.samples) == 1+ ), "a Detailer crop shape was recorded for the background compile"+ job.close()+ assert counter.compiles == 0+ net(torch.randn(2, 8), return_dict = False)+ assert counter.compiles == 1+++def test_force_eager_alone_still_reaches_a_whole_compiled_module():+ """Why the Detailer installs the gate: GraphedCompiledCall's eager path is the compiled U-Net call."""+ counter = _Counter()+ net = _whole_compiled(counter)+ with torch.no_grad(), bg.force_eager():+ net(torch.randn(2, 8), return_dict = False)+ assert counter.compiles == 1+++def test_a_whole_compiled_unet_under_the_gate_takes_no_cuda_graph():+ counter = _Counter()+ net = _whole_compiled(counter)+ graphed = cg.GraphedCompiledCall(net).install()+ restore = bg.gate_compiled_eager([net])+ try:+ with torch.no_grad(), bg.auxiliary_pass():+ net(torch.randn(3, 8), return_dict = False)+ assert graphed.stats["captures"] == 0 and graphed.stats["eager_calls"] == 0+ assert counter.compiles == 0+ finally:+ restore()+ graphed.uninstall()+ graphed.free()+ assert net._compiled_call_impl is graphed.compiled++def test_close_breaks_the_hook_job_cycle():net = _whole_compiled(_Counter())job = bg.arm(net)diff --git a/studio/backend/tests/test_diffusion_detailer.py b/studio/backend/tests/test_diffusion_detailer.pyindex ab14f30e39a..252c7e9912b 100644--- a/studio/backend/tests/test_diffusion_detailer.py+++ b/studio/backend/tests/test_diffusion_detailer.py@@ -558,6 +558,38 @@ def test_detail_result_runs_every_image_with_its_own_seed(monkeypatch):assert result["detailer"][0]["model"] == "sam3.1"+def test_every_inpaint_runs_as_an_auxiliary_eager_unrecorded_pass(monkeypatch):+ from core.inference import diffusion_bg_compile as bg++ _patch_detect(monkeypatch, [[_face((40, 30, 80, 80)), _face((150, 60, 230, 150))]])+ seen = []++ def _generate(**kwargs):+ seen.append(+ (bg.eager_forced(), bg._NO_RECORD.get(), getattr(bg, "auxiliary", lambda: False)())+ )+ crop = Image.open(+ __import__("io").BytesIO(+ __import__("base64").b64decode(kwargs["init_image"].split(",", 1)[1])+ )+ )+ return {"images": [crop.convert("RGB")]}++ result = {"images": [_scene()], "seeds": [3], "seed": 3}+ det.detail_result(+ _generate,+ result,+ det.DetailerSettings(),+ prompt_for = lambda i: "p",+ negative_prompt = None,+ steps = 8,+ guidance = 0.0,+ generate_kwargs = {},+ )+ assert seen == [(True, True, True), (True, True, True)]+ assert not bg.eager_forced() and not bg._NO_RECORD.get()++def test_a_failed_pass_keeps_the_render(monkeypatch):_patch_detect(monkeypatch, [[_face((150, 60, 200, 120))]])image = _scene()