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: batch a static-shape load only at sizes it already com…
…piled

A static compile and CUDA graphs key their artifacts on the batch, so a
coalesced call of a new size compiled or captured inside the slot while
every other request waited, and an OOM split resets every graph.
DiffusionBackend.coalesce_batch_sizes reports the batch sizes this load
already compiled at the requested size (None when shapes are dynamic).
A batch keeps the longest arrival-order run of members whose image
total is one of them; the rest render alone.
  • Loading branch information
danielhanchen committed Nov 26, 2026
commit 20b7f42e59a7634752e77fb942554f7580b97178
17 changes: 17 additions & 0 deletions studio/backend/core/inference/diffusion.py
Original file line number Diff line number Diff line change
Expand Up @@ -17926,6 +17926,23 @@ def coalesce_plan(self, prompt: str, has_loras: bool) -> Optional[tuple[tuple, b
private = True
return prompt_key, private

def coalesce_batch_sizes(self, width: int, height: int) -> Optional[frozenset]:
"""Batch sizes a coalesced txt2img call may use at ``width`` x ``height``: None = any. A static compile or
CUDA graphs key their artifacts on the batch, so a new size would compile or capture inside the slot (and an
OOM split resets every graph): only sizes this load already compiled at this size are offered."""
state = self._state
if state is None:
return frozenset()
static = bool(getattr(state, "cuda_graphs", ())) or (
"compiled" in (state.speed_optims or ())
and compiled_shapes_are_static(state.pipe, state.speed_mode)
)
if not static:
return None
dims = (int(width), int(height))
shapes = getattr(state.compile_cache_ctx, "shapes", None) or ()
return frozenset(int(shape[2]) for shape in list(shapes) if tuple(shape[:2]) == dims)

@contextmanager
def generation_rider(self, cancel: threading.Event):
"""A request riding another request's batched call: a Stop from its account sets ``cancel`` even while
Expand Down
15 changes: 14 additions & 1 deletion studio/backend/core/inference/image_request_batching.py
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,16 @@ def _share(exc: BaseException, members: list[_Member], owner: Hashable) -> None:
member.future.set_exception(type(exc)(*exc.args))


def _fitting_prefix(members: list[_Member], fits: Callable[[int], bool]) -> list[_Member]:
"""The longest run of members, in arrival order, whose image total ``fits``; the rest render alone."""
best, total = 0, 0
for index, member in enumerate(members):
total += len(member.seeds)
if fits(total):
best = index + 1
return members[:best]


def _close(batch: _Batch) -> None:
if _OPEN.get(batch.key) is batch:
del _OPEN[batch.key]
Expand Down Expand Up @@ -153,6 +163,7 @@ async def generate(
owner: Hashable = None,
check: Optional[Callable[[], None]] = None,
ride: Optional[Callable[[], ContextManager[Any]]] = None,
fits: Optional[Callable[[int], bool]] = None,
) -> Optional[dict[str, Any]]:
"""None = render alone. ``key`` names no account, so any account joins; ``owner`` is the caller's.
``check`` raises when a joined member must leave (its own Stop); ``ride`` scopes it as rendering."""
Expand Down Expand Up @@ -194,7 +205,9 @@ async def generate(
_close(batch)
batch.fired = True
members = list(batch.members)
if len(members) == 1:
if fits is not None:
members = _fitting_prefix(members, fits)
if len(members) <= 1:
return None
prompts = [member.prompt for member in members for _ in member.seeds]
seeds = [s for member in members for s in member.seeds]
Expand Down
13 changes: 13 additions & 0 deletions studio/backend/routes/inference.py
Original file line number Diff line number Diff line change
Expand Up @@ -56062,6 +56062,18 @@ async def run_batch(
def cancelled(exc: BaseException) -> bool:
return isinstance(exc, RuntimeError) and str(exc) == DIFFUSION_CANCELLED_MSG

sizes_of = getattr(backend, "coalesce_batch_sizes", None)

def fits(total: int) -> bool:
"""Read at fire time: a static-shape load batches only at sizes it already compiled."""
if sizes_of is None:
return True
try:
sizes = sizes_of(generate_kwargs.get("width"), generate_kwargs.get("height"))
except Exception: # noqa: BLE001 -- unknown shapes: render alone
return False
return sizes is None or total in sizes

waiter = getattr(backend, "generation_waiter", None)
rider = getattr(backend, "generation_rider", None)
with waiter(stopped) if waiter is not None else nullcontext():
Expand All @@ -56077,6 +56089,7 @@ def cancelled(exc: BaseException) -> bool:
check = check,
# A Stop from this account reaches its images while another account's call renders them.
ride = (lambda: rider(stopped)) if rider is not None else None,
fits = fits,
)
# A Stop recorded while the batch ran is final: never fall back to rendering alone or retry.
if result is None and stopped.is_set():
Expand Down
81 changes: 81 additions & 0 deletions studio/backend/tests/test_image_concurrency_review.py
Original file line number Diff line number Diff line change
Expand Up @@ -283,3 +283,84 @@ def test_a_batch_shared_across_accounts_shows_no_live_preview(studio):
assert all(r.status_code == 200 for r in _post_while_rendering(app, backend, posts, waiting = 2))
[call] = _batched_calls(backend)
assert call["kwargs"]["live_preview"] is True


def test_a_static_shape_load_batches_only_at_sizes_it_already_compiled(studio):
app, backend, _saved = studio
asked = []

def sizes(width, height):
asked.append((width, height))
return frozenset({1, 2})

backend.coalesce_batch_sizes = sizes
posts = [
("/v1/images/generations", "alice", _openai("a fox")),
("/v1/images/generations", "bob", _openai("a cat")),
("/v1/images/generations", "carol", _openai("an owl")),
]
responses = _post_while_rendering(app, backend, posts, waiting = 3)
assert all(r.status_code == 200 for r in responses)
[call] = _batched_calls(backend)
assert call["prompts"] == ["a fox", "a cat"] and call["batch_size"] == 2
assert [c["prompt"] for c in backend.calls if c["prompts"] is None] == ["an owl"]
assert set(asked) == {(256, 256)}


def test_the_engine_offers_only_compiled_batch_sizes_on_a_static_load(monkeypatch):
import core.inference.diffusion as diffusion_module
from core.inference.diffusion import DiffusionBackend

engine = DiffusionBackend()
engine._state = types.SimpleNamespace(
speed_optims = ("compiled",),
speed_mode = "default",
pipe = None,
cuda_graphs = (),
compile_cache_ctx = types.SimpleNamespace(
shapes = {(512, 512, 1), (512, 512, 4), (768, 768, 2)}
),
)
monkeypatch.setattr(diffusion_module, "compiled_shapes_are_static", lambda pipe, mode: True)
assert engine.coalesce_batch_sizes(512, 512) == frozenset({1, 4})
assert engine.coalesce_batch_sizes(1024, 1024) == frozenset()
monkeypatch.setattr(diffusion_module, "compiled_shapes_are_static", lambda pipe, mode: False)
assert engine.coalesce_batch_sizes(512, 512) is None
engine._state.cuda_graphs = (object(),)
assert engine.coalesce_batch_sizes(512, 512) == frozenset({1, 4})


def test_a_batch_keeps_the_longest_arrival_prefix_that_fits(monkeypatch):
rendering = {"on": True}
batches = []

async def run_batch(
prompts,
seeds,
owners = None,
):
batches.append(list(prompts))
return {"images": list(prompts), "seeds": list(seeds), "seed": seeds[0]}

async def run():
def request(prompt, n):
return asyncio.ensure_future(
batching.generate(
"key",
prompt,
n,
None,
busy = lambda: rendering["on"],
run_batch = run_batch,
fits = lambda total: total in (1, 4),
)
)

tasks = [request("a", 1), request("b", 2), request("c", 1), request("d", 2)]
await _until(lambda: _waiting() == 4)
rendering["on"] = False
return await asyncio.gather(*tasks)

results = asyncio.run(run())
assert batches == [["a", "b", "b", "c"]]
assert [r["images"] if r else None for r in results] == [["a"], ["b", "b"], ["c"], None]