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: queued image generations wait on their own pool, not the default executor (#17108)
Daniel Han8f8b34c60a22
diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.pyindex 5edc7efba0f..699c8025799 100644--- a/studio/backend/routes/inference.py+++ b/studio/backend/routes/inference.py@@ -279,6 +279,24 @@ _OLLAMA_LEASE_EXECUTOR = ThreadPoolExecutor(# Own workers so a cancel is not queued behind generations blocking the default executor; kept off the loop since native cancel kills a process tree._CANCEL_EXECUTOR = ThreadPoolExecutor(max_workers = 2, thread_name_prefix = "inference-cancel")+# Queued renders wait for the one-render slot inside their thread; on the default executor they would hold every worker.+_IMAGE_GENERATE_EXECUTOR_ENV = "UNSLOTH_DIFFUSION_GENERATE_EXECUTOR"+_IMAGE_GENERATE_EXECUTOR = ThreadPoolExecutor(max_workers = 32, thread_name_prefix = "image-generate")+++async def _image_generate_in_thread(func, /, *args, **kwargs):+ """``asyncio.to_thread`` (same context copy) on the image-generation pool."""+ if (os.environ.get(_IMAGE_GENERATE_EXECUTOR_ENV) or "").strip().lower() in (+ "0",+ "off",+ "false",+ "no",+ ):+ return await asyncio.to_thread(func, *args, **kwargs)+ loop = asyncio.get_running_loop()+ call = functools.partial(contextvars.copy_context().run, func, *args, **kwargs)+ return await loop.run_in_executor(_IMAGE_GENERATE_EXECUTOR, call)+def _loaded_chat_template() -> Optional[str]:"""Chat template llama-server renders for the loaded GGUF: the override when one is set."""@@ -49771,7 +49789,7 @@ async def _generate_diffusion_image_run(reset_media_generation_progress("image")try:with account_access.media_generation("diffusion"):- result = await asyncio.to_thread(+ result = await _image_generate_in_thread(backend.generate,expected_load = expected_load,prompt = enhancement.encoded(request.prompt),@@ -51958,7 +51976,7 @@ async def _batched_openai_images(async def run_batch(prompts: list[str], seeds: list[int]) -> dict:with generation_ticket(ticket):try:- return await asyncio.to_thread(+ return await _image_generate_in_thread(backend.generate,prompt = prompts[0],negative_prompt = body.negative_prompt,@@ -52077,7 +52095,7 @@ async def _generate_openai_images(backend, status, body, width, height, steps, guidance, expected_load)if result is None:- result = await asyncio.to_thread(+ result = await _image_generate_in_thread(backend.generate,prompt = body.prompt,negative_prompt = body.negative_prompt,diff --git a/studio/backend/tests/test_image_generate_executor.py b/studio/backend/tests/test_image_generate_executor.pynew file mode 100644index 00000000000..b8dcca9cbe1--- /dev/null+++ b/studio/backend/tests/test_image_generate_executor.py@@ -0,0 +1,90 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Queued image generations wait on their own pool, not the default executor every other route uses."""++from __future__ import annotations++import asyncio+import contextvars+import threading+import time+from concurrent.futures import ThreadPoolExecutor++import pytest++import routes.inference as inference++ENV = "UNSLOTH_DIFFUSION_GENERATE_EXECUTOR"+_ACCOUNT = contextvars.ContextVar("account", default = None)+++def _queued_renders_then_a_status_read(n_renders: int, workers: int) -> tuple[float, list]:+ """``n_renders`` generations queued behind one held render slot, then a default-executor read (status)."""+ slot = threading.Lock()+ slot.acquire()+ seen = []++ def generate(i):+ seen.append((i, _ACCOUNT.get(), threading.current_thread().name))+ with slot:+ return i++ async def main():+ loop = asyncio.get_running_loop()+ loop.set_default_executor(ThreadPoolExecutor(max_workers = workers))+ _ACCOUNT.set("acct")+ renders = [+ asyncio.ensure_future(inference._image_generate_in_thread(generate, i))+ for i in range(n_renders)+ ]+ while len(seen) < min(n_renders, workers):+ await asyncio.sleep(0.01)+ t0 = time.perf_counter()+ try:+ await asyncio.wait_for(asyncio.to_thread(lambda: None), timeout = 0.5)+ waited = time.perf_counter() - t0+ except asyncio.TimeoutError:+ waited = float("inf")+ slot.release()+ assert sorted(await asyncio.gather(*renders)) == list(range(n_renders))+ return waited++ return asyncio.run(main()), seen+++def test_queued_image_generations_leave_the_default_executor_free(monkeypatch):+ monkeypatch.delenv(ENV, raising = False)+ waited, seen = _queued_renders_then_a_status_read(n_renders = 4, workers = 4)+ assert waited < 0.25+ assert all(+ account == "acct" for _i, account, _t in seen+ ) # the caller's context reaches the render+ assert all(name.startswith("image-generate") for _i, _a, name in seen)+++def test_the_executor_switch_restores_asyncio_to_thread(monkeypatch):+ monkeypatch.setenv(ENV, "0")+ assert inference._IMAGE_GENERATE_EXECUTOR_ENV == ENV+ waited, seen = _queued_renders_then_a_status_read(n_renders = 4, workers = 4)+ assert waited == float("inf") # every default worker waits on the render slot+ assert all(account == "acct" for _i, account, _t in seen)++[email protected]("raises", [False, True])+def test_results_and_errors_pass_through(monkeypatch, raises):+ monkeypatch.delenv(ENV, raising = False)++ def generate(x, *, y):+ if raises:+ raise RuntimeError("cancelled")+ return x + y++ async def main():+ return await inference._image_generate_in_thread(generate, 1, y = 2)++ if raises:+ with pytest.raises(RuntimeError, match = "cancelled"):+ asyncio.run(main())+ else:+ assert asyncio.run(main()) == 3