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: one Stop rule for batched requests, across accounts
- The Stop route stops this account's waiting and riding batched work
  before its foreign-generation early return. Under managed accounts a
  member riding another account's call saw that call as foreign, so its
  Stop answered cancelled: false while its images still saved.
- cancel_generate applies one rule in every branch: Stop ends this
  account's denoising generation and all of its waiting and riding
  batched requests.
- A Stop during a model change sets only the caller's queued requests;
  each queued cancel now records its account.
  • Loading branch information
danielhanchen committed Nov 26, 2026
commit 2428129385f089f73fdf6e52c55dd1a20f398f05
70 changes: 51 additions & 19 deletions studio/backend/core/inference/diffusion.py
Original file line number Diff line number Diff line change
Expand Up @@ -4983,6 +4983,10 @@ def __init__(self) -> None:
self._queued_generate_cancels: set[threading.Event] = set()
# Requests whose images render in another request's batch, by account: their own Stop leaves the batch.
self._generate_riders: dict[threading.Event, Optional[str]] = {}
# Requests waiting to coalesce, by account.
self._coalesce_waiters: dict[threading.Event, Optional[str]] = {}
# The account of each queued cancel, so a lifecycle Stop reaches only the caller's requests.
self._queued_cancel_owners: dict[threading.Event, Optional[str]] = {}
self._generation_owns_slot = False

self._transition_owns_slot = False
Expand Down Expand Up @@ -5102,6 +5106,7 @@ def _generation_slot(self, cancel: threading.Event):
self._slot_turns.append(turn)
with self._generation_cancel_lock:
self._queued_generate_cancels.add(cancel)
self._queued_cancel_owners[cancel] = current_account_id()
try:
while True:
self._await_slot_turn(turn, cancel)
Expand All @@ -5116,6 +5121,7 @@ def _generation_slot(self, cancel: threading.Event):
cancelled = cancel.is_set()
if not cancelled and not self._unload_waiters:
self._queued_generate_cancels.discard(cancel)
self._queued_cancel_owners.pop(cancel, None)
self._active_generate_cancel = cancel
self._active_generate_account = current_account_id()
self._generation_owns_slot = True
Expand Down Expand Up @@ -5155,6 +5161,7 @@ def _generation_slot(self, cancel: threading.Event):
if not admitted:
with self._generation_cancel_lock:
self._queued_generate_cancels.discard(cancel)
self._queued_cancel_owners.pop(cancel, None)

# Offload policies fixed by the request; `fast`/`auto` are measurements and cannot be judged network-free.
def assert_precision_available(
Expand Down Expand Up @@ -17886,13 +17893,19 @@ def _enter_decode_phase() -> None:

@contextmanager
def generation_waiter(self, cancel: threading.Event):
"""A request waiting to coalesce: a lifecycle Stop reaches it, and so does a Stop from its own account."""
account = current_account_id()
with self._generation_cancel_lock:
self._queued_generate_cancels.add(cancel)
self._queued_cancel_owners[cancel] = account
self._coalesce_waiters[cancel] = account
try:
yield
finally:
with self._generation_cancel_lock:
self._queued_generate_cancels.discard(cancel)
self._queued_cancel_owners.pop(cancel, None)
self._coalesce_waiters.pop(cancel, None)

def coalesce_plan(self, prompt: str, has_loras: bool) -> Optional[tuple[tuple, bool]]:
"""``(prompt_key, private)`` for joining a batch, or None when this request must render alone. ``private``:
Expand Down Expand Up @@ -17926,16 +17939,27 @@ def generation_rider(self, cancel: threading.Event):
with self._generation_cancel_lock:
self._generate_riders.pop(cancel, None)

def _stop_riders_locked(self, account: Optional[str]) -> bool:
def _stop_waiting_locked(self, account: Optional[str]) -> bool:
"""This account's batched work (None: every account's): requests riding another request's call and requests
waiting to coalesce. Call with ``_generation_cancel_lock`` held."""
# getattr: tests build a bare backend with object.__new__.
riders = [
events = [
event
for event, owner in getattr(self, "_generate_riders", {}).items()
if owner == account
for pool in (
getattr(self, "_generate_riders", {}),
getattr(self, "_coalesce_waiters", {}),
)
for event, owner in pool.items()
if account is None or owner == account
]
for event in riders:
for event in events:
event.set()
return bool(riders)
return bool(events)

def stop_waiting_work(self, account: Optional[str] = None) -> bool:
"""Stop this account's waiting and riding batched requests; True when there were any."""
with self._generation_cancel_lock:
return self._stop_waiting_locked(account)

def generation_holder(self) -> Optional[object]:
with self._generation_cancel_lock:
Expand Down Expand Up @@ -17969,20 +17993,21 @@ def generate_progress(self) -> dict[str, Any]:
def cancel_generate(self, expected_account: Optional[str] = None) -> bool:
"""Stops the in-flight generation at the next step callback; returns False when nothing runs; a cancel in VAE decode or encode lands after it."""
with self._generation_cancel_lock:
# Stop targets the denoising generation, not a serialized waiter.
# One rule: Stop ends this account's denoising generation and all of its waiting and riding batched
# requests; a plain request queued for the slot is not the running one and keeps its place.
active = self._active_generate_cancel
if active is not None:
if expected_account is not None and self._active_generate_account not in (
None,
expected_account,
):
# Another account's call may be rendering this account's batched images.
return self._stop_riders_locked(expected_account)
hit = False
if active is not None and (
expected_account is None
or self._active_generate_account in (None, expected_account)
):
active.set()
hit = True
if self._stop_waiting_locked(expected_account):
hit = True
if hit:
return True
if expected_account is not None and self._stop_riders_locked(expected_account):
return True
if self._generation_owns_slot:
if active is not None or self._generation_owns_slot:
return False
# An accepted eject raises _unload_waiters long before teardown; without this Stop answered False.
if (
Expand All @@ -17991,8 +18016,15 @@ def cancel_generate(self, expected_account: Optional[str] = None) -> bool:
and not self._unload_waiters
):
return False
# Recheck live state so timed waiters observe a replacement handoff.
cancels = set(self._queued_generate_cancels)
# Recheck live state so timed waiters observe a replacement handoff. Only the caller's own requests:
# an unknown owner (registered by older code) counts as the caller's.
owners = getattr(self, "_queued_cancel_owners", {})
cancels = {
cancel
for cancel in self._queued_generate_cancels
if expected_account is None
or owners.get(cancel, expected_account) == expected_account
}
if not cancels:
return False
for cancel in cancels:
Expand Down
16 changes: 16 additions & 0 deletions studio/backend/routes/inference.py
Original file line number Diff line number Diff line change
Expand Up @@ -54944,6 +54944,19 @@ def _hidden():
return DiffusionGenerateProgressResponse(**progress)


def _stop_batched_image_work() -> bool:
"""This account's requests waiting to coalesce or riding another account's batched call."""
from core.inference.diffusion_engine_router import get_active_diffusion_engine

try:
stop = getattr(get_active_diffusion_engine(), "stop_waiting_work", None)
except Exception: # noqa: BLE001 -- no engine: nothing batched
return False
if stop is None:
return False
return bool(stop(account_access.tracked_generation_account()))


@studio_router.post("/images/generate/cancel")
async def cancel_diffusion_generation(
target: Optional[str] = None, current_subject: str = Depends(get_current_subject)
Expand All @@ -54960,6 +54973,9 @@ async def cancel_diffusion_generation(
if target == "connection":
return {"cancelled": _stop_external_image_runs()}
grids = _stop_xy_grids()
# Before the account checks: another account's call may be rendering this account's batched images, which
# makes the running generation look foreign although this account has work in it.
grids = _stop_batched_image_work() or grids
if account_access.generation_is_foreign("diffusion"):
return {"cancelled": grids}
mine = account_access.generation_is_mine("diffusion")
Expand Down
103 changes: 103 additions & 0 deletions studio/backend/tests/test_image_concurrency_review.py
Original file line number Diff line number Diff line change
Expand Up @@ -160,3 +160,106 @@ def test_qwen_image_21_members_of_different_lengths_render_apart_through_the_rou
assert [c["prompt"] for c in backend.calls if c["prompts"] is None] == [
"a red fox in deep snow"
]


def _as(name, func):
from utils.account_context import ROLE_OWNER, AccountContext, bind_account, reset_account
token = bind_account(AccountContext(name, name, ROLE_OWNER))
try:
return func()
finally:
reset_account(token)


def test_a_member_stop_through_the_route_reaches_its_batched_images_under_managed_accounts(
studio, monkeypatch
):
import httpx

from hub.services.models import account_access

app, backend, saved = studio

def stop_waiting_work(account = None):
mine = [cancel for cancel, owner in backend.riders if account is None or owner == account]
for cancel in mine:
cancel.set()
return bool(mine)

backend.stop_waiting_work = stop_waiting_work
# Managed accounts: alice's call holds the slot, so the generation is foreign to bob.
monkeypatch.setattr(account_access, "tracked_generation_account", current_account_id)
monkeypatch.setattr(
account_access, "generation_is_foreign", lambda modality: current_account_id() != "alice"
)
posts = [
("/v1/images/generations", "alice", _openai("a fox")),
("/v1/images/generations", "bob", _openai("a cat")),
("/v1/images/generations", "carol", _openai("an owl")),
]
answers = []

async def bob_stops():
await _until(lambda: len(backend.riders) == 2)
transport = httpx.ASGITransport(app = app)
async with httpx.AsyncClient(transport = transport, base_url = "http://studio") as client:
answer = await client.post(
"/api/inference/images/generate/cancel", headers = {"x-test-account": "bob"}
)
answers.append(answer.json())
await _until(lambda: _waiting() == 2)

responses = _post_while_rendering(app, backend, posts, waiting = 3, then = bob_stops)
assert answers == [{"cancelled": True}]
assert [r.status_code == 200 for r in responses] == [True, False, True]
assert sorted(record["account"] for record in saved) == ["alice", "carol"]


def test_one_stop_rule_ends_the_accounts_render_and_its_waiting_batched_work():
from core.inference.diffusion import DiffusionBackend

engine = DiffusionBackend()
render, waiting, riding, other = (threading.Event() for _ in range(4))
import contextlib

with contextlib.ExitStack() as stack:
_as("alice", lambda: stack.enter_context(engine._generation_slot(render)))
_as("alice", lambda: stack.enter_context(engine.generation_waiter(waiting)))
_as("alice", lambda: stack.enter_context(engine.generation_rider(riding)))
_as("bob", lambda: stack.enter_context(engine.generation_waiter(other)))
assert engine.cancel_generate(expected_account = "alice") is True
assert render.is_set() and waiting.is_set() and riding.is_set()
assert not other.is_set()


def test_a_stop_during_a_teardown_reaches_only_the_callers_queued_requests():
from core.inference.diffusion import DiffusionBackend
from core.inference.diffusion_families import DIFFUSION_CANCELLED_MSG

engine = DiffusionBackend()
events = {"alice": threading.Event(), "bob": threading.Event()}
outcome: dict = {}

def queued(name):
def run():
try:
with engine._generation_slot(events[name]):
outcome[name] = "served"
except RuntimeError as exc:
outcome[name] = str(exc)

return lambda: _as(name, run)

with engine._model_transition_slot():
threads = [threading.Thread(target = queued(name), daemon = True) for name in events]
for thread in threads:
thread.start()
deadline = __import__("time").monotonic() + 5
while len(engine._queued_generate_cancels) < 2:
assert __import__("time").monotonic() < deadline
threading.Event().wait(0.01)
assert engine.cancel_generate(expected_account = "bob") is True
assert events["bob"].is_set() and not events["alice"].is_set()
for thread in threads:
thread.join(timeout = 5)
assert outcome == {"alice": "served", "bob": DIFFUSION_CANCELLED_MSG}