Skip to content
Closed
Show file tree
Hide file tree
Changes from 1 commit
Commits
Show all changes
18 commits
Select commit Hold shift + click to select a range
6fac8dc
Studio images: coalesce concurrent requests across accounts
danielhanchen Nov 26, 2026
80a7423
Studio images: coalesce plain text-to-image on /images/generate
danielhanchen Nov 26, 2026
d068da9
Studio images: let seeded requests join a batch behind an opt-in
danielhanchen Nov 26, 2026
a40d678
Studio images: serve the generation slot first come, first served
danielhanchen Nov 26, 2026
7d3e9d2
Studio images: keep per-account LoRAs and embeddings out of shared ba…
danielhanchen Nov 26, 2026
ad1d92c
Studio images: group batch members by what their family encodes per call
danielhanchen Nov 26, 2026
2428129
Studio images: one Stop rule for batched requests, across accounts
danielhanchen Nov 26, 2026
eae66f8
Studio images: no live preview for a batch shared across accounts
danielhanchen Nov 26, 2026
20b7f42
Studio images: batch a static-shape load only at sizes it already com…
danielhanchen Nov 26, 2026
17f3a29
Studio images: one member's failure no longer fails the whole batch
danielhanchen Nov 26, 2026
02a10ae
Studio images: a batch keeps its place in line; follow-up passes go f…
danielhanchen Nov 26, 2026
771a1f0
Studio images: record the shared call in recipes; pin coalesced calls
danielhanchen Nov 26, 2026
077bd66
Studio images: reserved batches get their own worker; tighter batch keys
danielhanchen Nov 26, 2026
e0e4311
Studio images: an idle reservation never stalls the line; recovery ke…
danielhanchen Nov 26, 2026
208b5a6
Studio images: CUDA-graph loads serve serially, and status says so
danielhanchen Nov 26, 2026
f4aaf9c
Studio images: poll review-test conditions by count, not by clock dea…
danielhanchen Nov 26, 2026
aa2e573
Merge origin/main into studio-image-concurrency
danielhanchen Nov 26, 2026
d332c7f
Merge commit 'aa2e57379586099b1c4122b5e9172c5467364929' into pr-19667-ci
danielhanchen Nov 26, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
Studio images: reserved batches get their own worker; tighter batch keys
- A coalesced batch's own call (and a leader left alone) runs on a
  small dedicated pool. Its slot turn is first in line, while requests
  queued behind that turn could hold every worker of the shared image
  pool, so the batch could never start and nothing ran.
- A variation request with a random subseed (variation_strength set,
  no variation_seed) renders alone: per-member seeds would replace the
  base seed it repeats across its images.
- The SD / SDXL batch key counts the conditioning chunks the weighted
  encode actually builds (tokenize_chunks, BREAK and comma backtracking
  included) in every CLIP encoder, weighted and unweighted, so a member
  is never padded with an extra empty chunk.
  • Loading branch information
danielhanchen committed Nov 26, 2026
commit 077bd664246d3d2a5b70f1da1911968fa0ecdb04
21 changes: 15 additions & 6 deletions studio/backend/core/inference/diffusion.py
Original file line number Diff line number Diff line change
Expand Up @@ -4943,12 +4943,21 @@ def slot_follow_up():
_SLOT_FOLLOW_UP.reset(token)


def _clip_chunk_count(tokenizer: Any, prompt: str) -> Optional[int]:
"""77-token CLIP windows the prompt fills (75 content tokens each); None when it cannot be counted."""
if not callable(tokenizer):
def _clip_chunk_counts(pipe: Any, prompt: str) -> Optional[tuple]:
"""The conditioning chunks the weighted encode builds for ``prompt`` in each of the pipeline's CLIP encoders,
weighted and unweighted (BREAK and comma backtracking included): a batch pads every row to its longest, so
members must match exactly. None when there is no encoder to ask."""
from .diffusion_prompt_weighting import _encoders, tokenize_chunks

pairs = _encoders(pipe)
if not pairs:
return None
ids = tokenizer(prompt, add_special_tokens = False, truncation = False)["input_ids"]
return max(1, -(-len(ids) // 75))
convert = getattr(pipe, "maybe_convert_prompt", None)
return tuple(
len(tokenize_chunks(prompt, tokenizer, weighted = weighted, convert = convert))
for tokenizer, _ in pairs
for weighted in (True, False)
)


def coalesce_prompt_key(family: Any, pipe: Any, prompt: str) -> Optional[tuple]:
Expand All @@ -4974,7 +4983,7 @@ def coalesce_prompt_key(family: Any, pipe: Any, prompt: str) -> Optional[tuple]:
bucket = flux_t5_sequence_length(getattr(pipe, "tokenizer_2", None), [prompt])
return None if bucket is None else ("t5 bucket", bucket)
if getattr(family, "textual_inversion", None) is not None:
chunks = _clip_chunk_count(getattr(pipe, "tokenizer", None), prompt)
chunks = _clip_chunk_counts(pipe, prompt)
return None if chunks is None else ("clip", has_prompt_syntax(prompt), chunks)
except Exception: # noqa: BLE001 - a prompt that cannot be measured renders alone
return None
Expand Down
17 changes: 15 additions & 2 deletions studio/backend/routes/inference.py
Original file line number Diff line number Diff line change
Expand Up @@ -294,6 +294,9 @@ def _hook(unraisable):
# 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")
# A coalesced batch's own call runs here: its slot turn is first in line, so it starts at once, while requests
# queued behind that turn may hold every worker of the pool above.
_IMAGE_BATCH_EXECUTOR = ThreadPoolExecutor(max_workers = 4, thread_name_prefix = "image-batch")


async def _image_generate_in_thread(func, /, *args, **kwargs):
Expand All @@ -310,6 +313,13 @@ async def _image_generate_in_thread(func, /, *args, **kwargs):
return await loop.run_in_executor(_IMAGE_GENERATE_EXECUTOR, call)


async def _image_generate_on_reserved_turn(func, /, *args, **kwargs):
"""Runs a call that uses a reserved slot turn on its own pool, never behind the waiters it is ahead of."""
loop = asyncio.get_running_loop()
call = functools.partial(contextvars.copy_context().run, func, *args, **kwargs)
return await loop.run_in_executor(_IMAGE_BATCH_EXECUTOR, call)


def _loaded_chat_template() -> Optional[str]:
"""Chat template llama-server renders for the loaded GGUF: the override when one is set."""
try:
Expand Down Expand Up @@ -53454,6 +53464,8 @@ def _plain_txt2img(request: DiffusionGenerateRequest, enhancement: Any, detailer
and request.upscale_model is None
and request.hires is None
and request.variation_seed is None
# A random subseed repeats the base seed across the request's images: explicit per-member seeds would not.
and not request.variation_strength
and request.xy is None
and detailer is None
and not getattr(enhancement, "captions", None)
Expand Down Expand Up @@ -56097,9 +56109,10 @@ async def run_batch(
# The preview decodes row 0 of each forward, and an OOM split or an equal-length run can put another
# account's image there: a batch shared across accounts shows no preview.
call.update(_live_preview_kwarg(backend.generate, False))
runner = _image_generate_on_reserved_turn if "turn" in lead else _image_generate_in_thread
with generation_ticket(ticket), _reserved_turn(lead.get("turn")):
try:
return await _image_generate_in_thread(
return await runner(
backend.generate,
prompt = prompts[0],
prompts = prompts,
Expand Down Expand Up @@ -56201,7 +56214,7 @@ async def _coalesce_in_line() -> Optional[dict]:
# A leader that ends up alone renders in the place it held, not at the back of the line.
if result is None and "turn" in lead and not stopped.is_set():
with _reserved_turn(lead["turn"]):
result = await _image_generate_in_thread(
result = await _image_generate_on_reserved_turn(
backend.generate, prompt = prompt, seed = seed, batch_size = n, **generate_kwargs
)
return result
Expand Down
163 changes: 158 additions & 5 deletions studio/backend/tests/test_image_concurrency_review.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,9 +34,7 @@ def _real_plan(backend, family):
"""Bind the real engine's coalesce_plan onto the fake, over a stand-in load state."""
from core.inference.diffusion import DiffusionBackend

backend._state = types.SimpleNamespace(
family = family, pipe = types.SimpleNamespace(tokenizer = _words)
)
backend._state = types.SimpleNamespace(family = family, pipe = _clip_pipe())
backend.coalesce_plan = types.MethodType(DiffusionBackend.coalesce_plan, backend)


Expand Down Expand Up @@ -88,7 +86,7 @@ def test_the_engine_plan_marks_loras_and_owned_embeddings_private(monkeypatch):
assert engine.coalesce_plan("a fox", True) == ((), True)
engine._state = types.SimpleNamespace(
family = types.SimpleNamespace(name = "sdxl", textual_inversion = "sdxl"),
pipe = types.SimpleNamespace(tokenizer = _words),
pipe = _clip_pipe(),
)
monkeypatch.setattr(embeddings, "list_embeddings", lambda kind = None: [])
assert engine.coalesce_plan("a fox", False)[1] is False
Expand All @@ -100,6 +98,26 @@ def _words(text, **_kwargs):
return {"input_ids": list(range(len(text.split())))}


class _ClipWords:
"""A CLIP-shaped tokenizer: one id per word, a comma id, bos / eos."""

bos_token_id, eos_token_id, pad_token_id = 0, 1, None

def get_vocab(self):
return {",</w>": 2}

def __call__(self, text, **_kwargs):
return {
"input_ids": [
2 if word == "," else 10 + len(word) for word in text.replace(",", " , ").split()
]
}


def _clip_pipe(**extra):
return types.SimpleNamespace(tokenizer = _ClipWords(), text_encoder = object(), **extra)


def _qwen21_pipe():
transformer = type("QwenImage21Transformer2DModel", (), {})()
return types.SimpleNamespace(
Expand Down Expand Up @@ -137,7 +155,7 @@ def test_sdxl_groups_only_matching_weighting_and_chunk_count():
from core.inference.diffusion import coalesce_prompt_key

family = types.SimpleNamespace(name = "sdxl", textual_inversion = "sdxl")
pipe = types.SimpleNamespace(tokenizer = _words)
pipe = _clip_pipe()
plain = coalesce_prompt_key(family, pipe, "a red fox")
assert plain == coalesce_prompt_key(family, pipe, "a blue car")
assert plain != coalesce_prompt_key(family, pipe, "a (red:1.3) fox")
Expand Down Expand Up @@ -671,3 +689,138 @@ def test_a_coalesced_call_is_always_pinned_to_the_model_its_settings_were_read_f
assert call["kwargs"]["expected_load"] == load_identity(
status["repo_id"], status["base_repo"], status["family"]
)


def test_sdxl_groups_by_the_chunks_the_weighted_encode_actually_builds():
from core.inference.diffusion import coalesce_prompt_key

family = types.SimpleNamespace(name = "sdxl", textual_inversion = "sdxl")
pipe = _clip_pipe(tokenizer_2 = _ClipWords(), text_encoder_2 = object())
# Same raw token count and both weighted, but BREAK closes a chunk: two conditioning chunks against one.
assert coalesce_prompt_key(family, pipe, "a BREAK cat") != coalesce_prompt_key(
family, pipe, "a (cat)"
)
assert coalesce_prompt_key(family, pipe, "a (cat)") == coalesce_prompt_key(
family, pipe, "a (dog)"
)


def test_a_random_subseed_variation_request_never_joins_a_batch(studio):
import httpx

app, backend, _saved = studio

async def run():
transport = httpx.ASGITransport(app = app)
async with httpx.AsyncClient(transport = transport, base_url = "http://studio") as client:
backend.rendering = True
first = asyncio.ensure_future(
client.post(
"/api/inference/images/generate",
json = _create("a fox"),
headers = {"x-test-account": "alice"},
)
)
await _until(lambda: _waiting() == 1)
variation = asyncio.ensure_future(
client.post(
"/api/inference/images/generate",
json = _create("a cat", batch_size = 2, variation_strength = 0.3),
headers = {"x-test-account": "bob"},
)
)
await asyncio.sleep(0.3)
assert _waiting() == 1
backend.rendering = False
return await asyncio.gather(first, variation)

responses = asyncio.run(run())
assert all(r.status_code == 200 for r in responses), [r.text[:200] for r in responses]
assert _batched_calls(backend) == []
[variation_call] = [c for c in backend.calls if c["prompt"] == "a cat"]
assert variation_call["batch_size"] == 2 and variation_call["seeds"] is None


class _SlotBackend(_Backend):
"""The fake engine over the real engine's slot line, so queued renders block in ``_generation_slot``."""

def __init__(self):
from core.inference.diffusion import DiffusionBackend

super().__init__()
self.engine = DiffusionBackend()
for name in (
"generation_holder",
"generation_waiter",
"generation_rider",
"reserve_slot_turn",
"release_slot_turn",
"slot_turn_ready",
"add_slot_listener",
"stop_waiting_work",
):
setattr(self, name, getattr(self.engine, name))

def generate(self, **kwargs):
with self.engine._generation_slot(threading.Event()):
return super().generate(**kwargs)


def test_a_reserved_batch_runs_even_when_queued_requests_hold_every_generate_worker(
studio, monkeypatch
):
from concurrent.futures import ThreadPoolExecutor

import httpx

import core.inference.diffusion as diffusion_module
import core.inference.diffusion_engine_router as engine_router
import routes.inference as inference_routes

app, _fake, saved = studio
backend = _SlotBackend()
monkeypatch.setattr(diffusion_module, "get_diffusion_backend", lambda: backend)
monkeypatch.setattr(engine_router, "get_active_diffusion_engine", lambda: backend)
pool = ThreadPoolExecutor(max_workers = 2, thread_name_prefix = "test-generate")
monkeypatch.setattr(inference_routes, "_IMAGE_GENERATE_EXECUTOR", pool)
engine = backend.engine
release = _hold_slot(engine)

async def run():
transport = httpx.ASGITransport(app = app)
async with httpx.AsyncClient(transport = transport, base_url = "http://studio") as client:

def post(account, body):
return asyncio.ensure_future(
client.post(
"/v1/images/generations", json = body, headers = {"x-test-account": account}
)
)

batch = [post("alice", _openai("a fox"))]
await _until(lambda: _waiting() == 1 and len(engine._slot_turns) == 1)
batch.append(post("bob", _openai("a cat")))
await _until(lambda: _waiting() == 2)
# Seeded requests never join: they take both generate workers and queue behind the batch's turn.
seeded = [
post("carol", _openai("an owl", seed = 5)),
post("dave", _openai("a hen", seed = 6)),
]
await _until(lambda: len(engine._slot_turns) == 3)
release.set()
return await asyncio.wait_for(asyncio.gather(*batch, *seeded), timeout = 15)

try:
responses = asyncio.run(run())
finally:
release.set()
# Unstick any waiter a failing run left behind the reserved turn.
with engine._slot_turn_changed:
engine._slot_turns.clear()
engine._slot_turn_changed.notify_all()
pool.shutdown(wait = False, cancel_futures = True)
assert all(r.status_code == 200 for r in responses)
calls = [c["prompts"] or c["prompt"] for c in backend.calls]
assert calls[0] == ["a fox", "a cat"]
assert sorted(calls[1:]) == ["a hen", "an owl"]
assert len(saved) == 4