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: coalesce across requests only when the denoiser stream…
…s from host

Measured per family with a batch of 4, resident loads ran 0.81x to 1.19x
of serial while every member drifted from its solo render (LPIPS up to
0.31). Only loads streaming the denoiser from host gained: FLUX.2-dev
3.35x, Ideogram-4 2.48x, HiDream-I1 1.47x, since one shared call pays for
one pass of weight copies.

request_batching now reports serial (resident weights) unless the load
uses model, sequential or streaming offload, or group offload with any
group unpinned, and coalesce_plan returns None for every serial load, so
those requests render one at a time without waiting to coalesce. The
per-family exclusions stay.

[skip ci]
  • Loading branch information
danielhanchen committed Nov 26, 2026
commit ec193183e057a55a3b41b6ea9717b41a77767607
31 changes: 29 additions & 2 deletions studio/backend/core/inference/diffusion.py
Original file line number Diff line number Diff line change
Expand Up @@ -5108,6 +5108,20 @@ def _coalesce_prompt_key(family: Any, name: Any, pipe: Any, prompt: str) -> Opti
return ()


def _denoiser_streams_from_host(state: Any) -> bool:
"""The loaded placement copies denoiser weights from host memory on every render: model, sequential or
streaming offload, or group offload with any group left unpinned. Resident (no offload, or every group pinned)
is False; an unreadable group placement counts as streamed, as its policy plans."""
policy = getattr(state, "offload_policy", OFFLOAD_NONE) or OFFLOAD_NONE
if policy == OFFLOAD_NONE:
return False
if policy != OFFLOAD_GROUP:
return True
from .diffusion_memory import DENOISER_RESIDENT

return denoiser_offload(getattr(state, "pipe", None), policy) != DENOISER_RESIDENT


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

Expand Down Expand Up @@ -18225,6 +18239,10 @@ def coalesce_plan(self, prompt: str, has_loras: bool) -> Optional[tuple[tuple, b
state = self._state
if state is None:
return None
# A load that serves one request at a time never waits to coalesce.
policy = self.request_batching()
if policy is None or policy["mode"] == "serial":
return None
prompt_key = coalesce_prompt_key(state.family, state.pipe, prompt)
if prompt_key is None:
return None
Expand All @@ -18239,11 +18257,20 @@ def coalesce_plan(self, prompt: str, has_loras: bool) -> Optional[tuple[tuple, b

def request_batching(self) -> Optional[dict[str, str]]:
"""How concurrent requests share calls on this load, for status: ``mode`` is ``any`` (any batch size),
``compiled_sizes`` (static compile: only batch sizes this load already compiled) or ``serial`` (CUDA graphs:
every request renders alone), with the reason. None when nothing is loaded."""
``compiled_sizes`` (static compile: only batch sizes this load already compiled) or ``serial`` (resident
weights or CUDA graphs: every request renders alone), with the reason. None when nothing is loaded."""
state = self._state
if state is None:
return None
if not _denoiser_streams_from_host(state):
# Measured per family (A100 / RTX PRO 6000, batch of 4): resident loads ran 0.81x to 1.19x of serial
# while each member drifted from its solo render; only loads streaming the denoiser from host gained
# (1.47x to 3.35x), since one batch pays for one pass of weight copies.
return {
"mode": "serial",
"reason": "resident weights: a shared call is no faster than one request at a time, so "
"concurrent requests render one at a time",
}
if getattr(state, "cuda_graphs", ()):
# A graph replays one batch size: a new size captures (seconds, and its own memory pool) inside the slot
# while everyone waits, and an OOM split drops every graph. Graph replay already keeps the card busy,
Expand Down
93 changes: 90 additions & 3 deletions studio/backend/tests/test_image_batching_followups.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,12 +42,20 @@ def __call__(self, text, **_kwargs):
return {"input_ids": [10 + len(word) for word in text.split()]}


def _plan(backend, family, pipe):
"""The real engine's coalesce_plan over a stand-in load state."""
def _plan(
backend,
family,
pipe,
offload_policy = "sequential",
):
"""The real engine's coalesce_plan over a stand-in load state; streamed from host unless told otherwise."""
from core.inference.diffusion import DiffusionBackend

backend._state = types.SimpleNamespace(family = family, pipe = pipe)
backend._state = types.SimpleNamespace(
family = family, pipe = pipe, offload_policy = offload_policy, cuda_graphs = (), speed_optims = ()
)
backend.coalesce_plan = types.MethodType(DiffusionBackend.coalesce_plan, backend)
backend.request_batching = types.MethodType(DiffusionBackend.request_batching, backend)


def _qwen21_pipe():
Expand Down Expand Up @@ -218,3 +226,82 @@ def test_loads_whose_keys_never_tokenize_make_no_copy():
pipe = types.SimpleNamespace(tokenizer = tok)
diffusion.prime_coalesce_tokenizers(types.SimpleNamespace(name = "z-image"), pipe)
assert tok not in diffusion._KEY_TOKENIZERS


def _serves_at_once(app, backend, prompts):
"""Posts while another render holds the slot; each must finish without waiting to coalesce."""
opened: list[int] = []

async def run():
transport = httpx.ASGITransport(app = app)
async with httpx.AsyncClient(transport = transport, base_url = "http://studio") as client:
backend.rendering = True
out = []
for path, account, body in _interleaved(*prompts):
response = await asyncio.wait_for(
client.post(path, json = body, headers = {"x-test-account": account}),
timeout = 5,
)
opened.append(len(batching._OPEN))
out.append(response)
backend.rendering = False
return out

return asyncio.run(run()), opened


def test_a_resident_load_never_batches_and_never_waits(studio):
"""Resident weights: a shared call measured 0.81x to 1.19x of serial while members drifted from their solos."""
app, backend, _saved = studio
_plan(backend, types.SimpleNamespace(name = "z-image"), None, offload_policy = "none")
responses, opened = _serves_at_once(app, backend, ("a fox", "a cat", "an owl"))
assert [r.status_code for r in responses] == [200, 200, 200]
assert opened == [0, 0, 0]
assert _batched_calls(backend) == []


def test_a_streamed_load_still_batches_across_accounts(studio):
app, backend, _saved = studio
_plan(backend, types.SimpleNamespace(name = "z-image"), None, offload_policy = "group")
responses = _post_while_rendering(
app, backend, _interleaved("a fox", "a cat", "an owl"), waiting = 3
)
assert all(r.status_code == 200 for r in responses)
assert _groups(backend) == [sorted(["a fox", "a cat", "an owl"])]


def test_group_offload_with_every_group_pinned_counts_as_resident(monkeypatch):
import core.inference.diffusion as diffusion_module
from core.inference.diffusion import DiffusionBackend
from core.inference.diffusion_memory import (
DENOISER_PARTIAL,
DENOISER_RESIDENT,
DENOISER_STREAMED,
)

engine = DiffusionBackend()
engine._state = types.SimpleNamespace(
family = types.SimpleNamespace(name = "z-image"),
pipe = object(),
offload_policy = "group",
cuda_graphs = (),
speed_optims = (),
)
placement = [DENOISER_RESIDENT]
monkeypatch.setattr(diffusion_module, "denoiser_offload", lambda pipe, policy: placement[0])
policy = engine.request_batching()
assert policy == {
"mode": "serial",
"reason": "resident weights: a shared call is no faster than one request at a time, so concurrent "
"requests render one at a time",
}
assert engine.coalesce_plan("a fox", False) is None
for streamed in (DENOISER_PARTIAL, DENOISER_STREAMED):
placement[0] = streamed
assert engine.request_batching()["mode"] == "any"
assert engine.coalesce_plan("a fox", False) == ((), False)
for name in ("model", "sequential", "streaming"):
engine._state.offload_policy = name
assert engine.request_batching()["mode"] == "any"
engine._state.offload_policy = "none"
assert engine.request_batching()["mode"] == "serial"
25 changes: 23 additions & 2 deletions studio/backend/tests/test_image_concurrency_review.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,8 +34,16 @@ 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 = _clip_pipe())
# A load streaming its denoiser from host: only those coalesce across requests.
backend._state = types.SimpleNamespace(
family = family,
pipe = _clip_pipe(),
offload_policy = "sequential",
cuda_graphs = (),
speed_optims = (),
)
backend.coalesce_plan = types.MethodType(DiffusionBackend.coalesce_plan, backend)
backend.request_batching = types.MethodType(DiffusionBackend.request_batching, backend)


def test_requests_with_loras_batch_only_with_their_own_account(studio):
Expand Down Expand Up @@ -81,12 +89,20 @@ def test_the_engine_plan_marks_loras_and_owned_embeddings_private(monkeypatch):

engine = DiffusionBackend()
assert engine.coalesce_plan("a fox", False) is None # nothing loaded
engine._state = types.SimpleNamespace(family = types.SimpleNamespace(name = "z-image"), pipe = None)
engine._state = types.SimpleNamespace(
family = types.SimpleNamespace(name = "z-image"), pipe = None, speed_optims = ()
)
assert (
engine.coalesce_plan("a fox", False) is None
) # resident weights serve one request at a time
engine._state.offload_policy = "sequential"
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 = _clip_pipe(),
offload_policy = "sequential",
speed_optims = (),
)
monkeypatch.setattr(embeddings, "list_embeddings", lambda kind = None: [])
assert engine.coalesce_plan("a fox", False)[1] is False
Expand Down Expand Up @@ -314,6 +330,7 @@ def test_the_engine_offers_only_compiled_batch_sizes_on_a_static_load(monkeypatc
speed_mode = "default",
pipe = None,
cuda_graphs = (),
offload_policy = "sequential",
compile_cache_ctx = types.SimpleNamespace(
shapes = {(512, 512, 1), (512, 512, 4), (768, 768, 2)}
),
Expand Down Expand Up @@ -894,6 +911,10 @@ def test_status_tells_how_concurrent_requests_are_served(monkeypatch):
engine._state = types.SimpleNamespace(
speed_optims = (), speed_mode = "off", pipe = None, cuda_graphs = (), compile_cache_ctx = None
)
policy = engine.request_batching()
assert policy["mode"] == "serial" and policy["reason"].startswith("resident weights")
assert engine.coalesce_batch_sizes(512, 512) == frozenset()
engine._state.offload_policy = "sequential"
assert engine.request_batching()["mode"] == "any"
assert engine.coalesce_batch_sizes(512, 512) is None
engine._state.speed_optims = ("compiled",)
Expand Down