Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
Show all changes
25 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
43ed7c3
Studio images: a leader whose Stop was acknowledged returns no images
danielhanchen Nov 26, 2026
97c4054
Studio images: test per-family batch grouping with interleaved arrivals
danielhanchen Nov 26, 2026
6659015
Studio images: read batch keys through private tokenizer copies
danielhanchen Nov 26, 2026
8b82bdf
Studio images: keep Qwen-Image-2.1 out of cross-account batches
danielhanchen Nov 26, 2026
ec19318
Studio images: coalesce across requests only when the denoiser stream…
danielhanchen Nov 26, 2026
e6a3595
Studio images: keep MOSS-Image out of cross-account batches
danielhanchen Nov 26, 2026
34029ec
Studio images: serve serially when the DiT scales activations per call
danielhanchen Nov 26, 2026
d27a985
Trim comments in image request batching
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: group batch members by what their family encodes per call
Some families render a prompt differently, or gain nothing, inside a
batch, so the batch key now carries a per-prompt group:

- MiniMax-H3-Image loops per image when resident: never batched.
- Qwen-Image-2.1 builds its RoPE layout from row 0: equal prompt token
  lengths only.
- FLUX.1 / Kontext pad T5 to one bucket per call: 256 and 512 apart.
- SD / SDXL weight and chunk prompts per call: prompt weighting and the
  77-token chunk count must match.

A prompt that cannot be measured renders alone.
  • Loading branch information
danielhanchen committed Nov 26, 2026
commit ad1d92c5d47541ba6dbeaf5e28f5394b854abb15
43 changes: 42 additions & 1 deletion studio/backend/core/inference/diffusion.py
Original file line number Diff line number Diff line change
Expand Up @@ -4913,6 +4913,44 @@ def _converted_shards_pread(dtype: Any, small_host: Any) -> Any:
return pread_safetensors(convert_to = dtype, keep = keep, every_shard = every)


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):
return None
ids = tokenizer(prompt, add_special_tokens = False, truncation = False)["input_ids"]
return max(1, -(-len(ids) // 75))


def coalesce_prompt_key(family: Any, pipe: Any, prompt: str) -> Optional[tuple]:
"""What a prompt must share with its batch neighbours to render as it would alone; None = never batch it.

MiniMax-H3-Image loops per image when resident, so a batch gains nothing. Qwen-Image-2.1 builds its RoPE
layout from row 0, so only equal prompt token lengths match. FLUX.1 / Kontext pad T5 to one bucket (256 or
512) per call. SD / SDXL weight and chunk prompts per call, so weighting and the 77-token chunk count must
agree."""
from .diffusion_families import MINIMAX_H3_IMAGE_FAMILY_NAME
from .diffusion_prompt_weighting import has_prompt_syntax
from .diffusion_qwenimage21 import _CLASS as QWENIMAGE21_CLASS, _prompt_tokens
from .diffusion_text_length import FLUX_T5_FAMILIES, flux_t5_sequence_length

name = getattr(family, "name", None)
if name == MINIMAX_H3_IMAGE_FAMILY_NAME:
return None
try:
if type(getattr(pipe, "transformer", None)).__name__ == QWENIMAGE21_CLASS:
tokens = _prompt_tokens(pipe, prompt)
return None if tokens is None else ("qwen-image-2.1 tokens", tokens)
if name in FLUX_T5_FAMILIES:
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)
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
return ()


class DiffusionBackend:
"""Holds at most one loaded diffusers pipeline. All mutations are serialised."""

Expand Down Expand Up @@ -17863,14 +17901,17 @@ def coalesce_plan(self, prompt: str, has_loras: bool) -> Optional[tuple[tuple, b
state = self._state
if state is None:
return None
prompt_key = coalesce_prompt_key(state.family, state.pipe, prompt)
if prompt_key is None:
return None
private = bool(has_loras)
if not private and getattr(state.family, "textual_inversion", None) is not None:
# Embeddings come from the leader's folder and match triggers in every member's prompt.
try:
private = bool(diffusion_embeddings.list_embeddings())
except Exception: # noqa: BLE001 - an unreadable folder may still hold one
private = True
return (), private
return prompt_key, private

@contextmanager
def generation_rider(self, cancel: threading.Event):
Expand Down
73 changes: 71 additions & 2 deletions studio/backend/tests/test_image_concurrency_review.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,9 @@ 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 = None)
backend._state = types.SimpleNamespace(
family = family, pipe = types.SimpleNamespace(tokenizer = _words)
)
backend.coalesce_plan = types.MethodType(DiffusionBackend.coalesce_plan, backend)


Expand Down Expand Up @@ -85,9 +87,76 @@ def test_the_engine_plan_marks_loras_and_owned_embeddings_private(monkeypatch):
assert engine.coalesce_plan("a fox", False) == ((), False)
assert engine.coalesce_plan("a fox", True) == ((), True)
engine._state = types.SimpleNamespace(
family = types.SimpleNamespace(name = "sdxl", textual_inversion = "sdxl"), pipe = None
family = types.SimpleNamespace(name = "sdxl", textual_inversion = "sdxl"),
pipe = types.SimpleNamespace(tokenizer = _words),
)
monkeypatch.setattr(embeddings, "list_embeddings", lambda kind = None: [])
assert engine.coalesce_plan("a fox", False)[1] is False
monkeypatch.setattr(embeddings, "list_embeddings", lambda kind = None: ["x"])
assert engine.coalesce_plan("a fox", False)[1] is True


def _words(text, **_kwargs):
return {"input_ids": list(range(len(text.split())))}


def _qwen21_pipe():
transformer = type("QwenImage21Transformer2DModel", (), {})()
return types.SimpleNamespace(
transformer = transformer, prompt_template_t2i = "{}", tokenizer = _words
)


def test_minimax_h3_image_never_batches():
from core.inference.diffusion import coalesce_prompt_key
family = types.SimpleNamespace(name = "minimax-h3-image")
assert coalesce_prompt_key(family, None, "a fox") is None


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

family = types.SimpleNamespace(name = "qwen-image-2.1")
pipe = _qwen21_pipe()
short, same, longer = ("a red fox", "a blue car", "a red fox in deep snow")
assert coalesce_prompt_key(family, pipe, short) == coalesce_prompt_key(family, pipe, same)
assert coalesce_prompt_key(family, pipe, short) != coalesce_prompt_key(family, pipe, longer)


def test_flux1_groups_only_members_in_the_same_t5_bucket():
from core.inference.diffusion import coalesce_prompt_key
for name in ("flux.1", "flux.1-kontext"):
family = types.SimpleNamespace(name = name)
pipe = types.SimpleNamespace(tokenizer_2 = _words)
short = coalesce_prompt_key(family, pipe, "a fox")
assert short == coalesce_prompt_key(family, pipe, "a cat on a mat")
assert short != coalesce_prompt_key(family, pipe, " ".join(["word"] * 300))


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)
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")
assert plain != coalesce_prompt_key(family, pipe, " ".join(["word"] * 80))


def test_qwen_image_21_members_of_different_lengths_render_apart_through_the_route(studio):
app, backend, _saved = studio
_real_plan(backend, types.SimpleNamespace(name = "qwen-image-2.1"))
backend._state.pipe = _qwen21_pipe()
posts = [
("/v1/images/generations", "alice", _openai("a red fox")),
("/v1/images/generations", "bob", _openai("a red fox in deep snow")),
("/v1/images/generations", "carol", _openai("a blue car")),
]
responses = _post_while_rendering(app, backend, posts, waiting = 3)
assert all(r.status_code == 200 for r in responses)
[call] = _batched_calls(backend)
assert sorted(call["prompts"]) == ["a blue car", "a red fox"]
assert [c["prompt"] for c in backend.calls if c["prompts"] is None] == [
"a red fox in deep snow"
]