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: a batch keeps its place in line; follow-up passes go f…
…irst

- A coalesced batch takes its slot ticket when it opens
  (reserve_slot_turn), so requests arriving while it collects members
  queue behind it, and a leader left alone renders in that place
  instead of at the back.
- The waiting batch wakes from the slot itself (add_slot_listener on a
  release or a line change) instead of a 50 ms poll; a 250 ms timeout
  covers lock holders outside the line.
- Follow-up passes of a request already admitted go to the front: X/Y
  cells after the first, Detailer crop inpaints (slot_follow_up), and
  the Detailer's segmenter pass (jump_slot_queue). The head of the line
  rechecks its place after taking the lock. The hires refine already
  runs inside its base pass's slot.
  • Loading branch information
danielhanchen committed Nov 26, 2026
commit 02a10ae93c72a484260002b547d70edaf8121c5c
108 changes: 105 additions & 3 deletions studio/backend/core/inference/diffusion.py
Original file line number Diff line number Diff line change
Expand Up @@ -4913,6 +4913,36 @@ def _converted_shards_pread(dtype: Any, small_host: Any) -> Any:
return pread_safetensors(convert_to = dtype, keep = keep, every_shard = every)


# A slot turn reserved ahead of time (a coalesced batch takes its place in line when it opens), and whether a call
# is a follow-up pass of a request already admitted (X/Y cells, Detailer crops), which goes to the front of the line.
_RESERVED_SLOT_TURN: contextvars.ContextVar[Optional[object]] = contextvars.ContextVar(
"unsloth_reserved_slot_turn", default = None
)
_SLOT_FOLLOW_UP: contextvars.ContextVar[bool] = contextvars.ContextVar(
"unsloth_slot_follow_up", default = False
)


@contextmanager
def reserved_slot_turn(turn: Optional[object]):
"""Generations started in this context use ``turn``; once it was admitted, later ones are follow-ups."""
token = _RESERVED_SLOT_TURN.set(turn)
try:
yield
finally:
_RESERVED_SLOT_TURN.reset(token)


@contextmanager
def slot_follow_up():
"""Generations started in this context continue a request that already held the slot: they go first."""
token = _SLOT_FOLLOW_UP.set(True)
try:
yield
finally:
_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):
Expand Down Expand Up @@ -4965,6 +4995,8 @@ def __init__(self) -> None:
# Generations waiting for the slot, in arrival order: only the head competes for _generate_lock.
self._slot_turns: collections.deque = collections.deque()
self._slot_turn_changed = threading.Condition(threading.Lock())
# Called (from any thread) when the line moves or the slot frees: a waiting batch wakes on it, not a poll.
self._slot_listeners: list[Callable[[], None]] = []
self._state: Optional[_LoadState] = None
self._loading: Optional[_LoadingState] = None
# Bumped on begin_load/unload so a superseded worker neither commits nor stamps progress
Expand Down Expand Up @@ -5078,6 +5110,58 @@ def _model_transition_slot(self):
with self._generation_cancel_lock:
self._transition_owns_slot = False
self._generate_lock.release()
self._notify_slot_listeners()

def add_slot_listener(self, callback: Callable[[], None]) -> Callable[[], None]:
"""``callback`` runs whenever the line moves or the slot frees; returns its remover."""
with self._slot_turn_changed:
self._slot_listeners.append(callback)

def remove() -> None:
with self._slot_turn_changed:
if callback in self._slot_listeners:
self._slot_listeners.remove(callback)

return remove

def _notify_slot_listeners(self) -> None:
with self._slot_turn_changed:
listeners = list(getattr(self, "_slot_listeners", ()))
for callback in listeners:
try:
callback()
except Exception: # noqa: BLE001 - a listener never breaks the slot
pass

def reserve_slot_turn(self) -> object:
"""A place at the back of the line, held before the generation that uses it starts (``reserved_slot_turn``).
Release it with ``release_slot_turn`` if no generation takes it."""
turn = object()
with self._slot_turn_changed:
self._slot_turns.append(turn)
return turn

def release_slot_turn(self, turn: object) -> None:
self._leave_slot_turn(turn)

def slot_turn_ready(self, turn: object) -> bool:
"""The reserved turn is first in line and the slot is free: a generation using it starts at once."""
with self._slot_turn_changed:
first = (
not self._slot_turns or self._slot_turns[0] is turn or turn not in self._slot_turns
)
return first and not self._generate_lock.locked()

@contextmanager
def jump_slot_queue(self):
"""A follow-up pass of the request holding the slot (a Detailer crop) takes the lock before anyone waiting."""
turn = object()
with self._slot_turn_changed:
self._slot_turns.appendleft(turn)
try:
yield
finally:
self._leave_slot_turn(turn)

def _leave_slot_turn(self, turn: object) -> None:
with self._slot_turn_changed:
Expand All @@ -5086,6 +5170,7 @@ def _leave_slot_turn(self, turn: object) -> None:
except ValueError:
return
self._slot_turn_changed.notify_all()
self._notify_slot_listeners()

def _await_slot_turn(self, turn: object, cancel: threading.Event) -> None:
"""Blocks until ``turn`` is the oldest waiting generation; a cancel still ends the wait within 0.1 s."""
Expand All @@ -5101,9 +5186,18 @@ def _generation_slot(self, cancel: threading.Event):
later arrival cannot overtake it. Yields to teardown fences after taking the lock, keeping its place; the
zero-fence check and cancel registration must share one _lock section."""
admitted = False
turn = object()
reserved = _RESERVED_SLOT_TURN.get()
with self._slot_turn_changed:
self._slot_turns.append(turn)
if reserved is not None and reserved in self._slot_turns:
# A coalesced batch keeps the place it took when it opened.
turn = reserved
else:
turn = object()
if reserved is not None or _SLOT_FOLLOW_UP.get():
# A follow-up pass of a request already admitted goes first.
self._slot_turns.appendleft(turn)
else:
self._slot_turns.append(turn)
with self._generation_cancel_lock:
self._queued_generate_cancels.add(cancel)
self._queued_cancel_owners[cancel] = current_account_id()
Expand All @@ -5114,7 +5208,14 @@ def _generation_slot(self, cancel: threading.Event):
if cancel.is_set():
raise RuntimeError(DIFFUSION_CANCELLED_MSG)
if self._generate_lock.acquire(timeout = 0.1):
break
with self._slot_turn_changed:
first = self._slot_turns[0] is turn
if first:
break
# A follow-up pass went to the front while this one waited on the lock.
self._generate_lock.release()
self._notify_slot_listeners()
self._await_slot_turn(turn, cancel)
with self._lock:
if not self._teardown_waiters:
with self._generation_cancel_lock:
Expand Down Expand Up @@ -5156,6 +5257,7 @@ def _generation_slot(self, cancel: threading.Event):
self._active_generate_account = None
self._generation_owns_slot = False
self._generate_lock.release()
self._notify_slot_listeners()
finally:
self._leave_slot_turn(turn)
if not admitted:
Expand Down
12 changes: 8 additions & 4 deletions studio/backend/core/inference/diffusion_detailer.py
Original file line number Diff line number Diff line change
Expand Up @@ -524,14 +524,18 @@ def _take_generation_slot(stop: Optional[Callable[[], bool]] = None) -> Any:
"""Acquire the active engine's generation lock (None if it has none); cancellable while waiting."""
try:
from core.inference.diffusion_engine_router import get_active_diffusion_engine
lock = getattr(get_active_diffusion_engine(), "_generate_lock", None)
engine = get_active_diffusion_engine()
lock = getattr(engine, "_generate_lock", None)
except Exception: # noqa: BLE001 -- no engine: no render to collide with
return None
if lock is None or not hasattr(lock, "acquire"):
return None
while not lock.acquire(timeout = 0.1):
if stop is not None and stop():
raise DetailerCancelled("cancelled")
# A follow-up of the render that just held the slot: it goes before requests waiting in line.
jump = getattr(engine, "jump_slot_queue", None)
with jump() if callable(jump) else contextlib.nullcontext():
while not lock.acquire(timeout = 0.1):
if stop is not None and stop():
raise DetailerCancelled("cancelled")
return lock


Expand Down
10 changes: 9 additions & 1 deletion studio/backend/core/inference/image_request_batching.py
Original file line number Diff line number Diff line change
Expand Up @@ -227,6 +227,8 @@ async def generate(
fits: Optional[Callable[[int], bool]] = None,
splittable: Optional[Callable[[BaseException], bool]] = None,
salvage: Optional[Callable[[BaseException], Optional[dict[str, Any]]]] = None,
on_lead: Optional[Callable[[], None]] = None,
wait: Optional[Callable[[], Awaitable[None]]] = 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 @@ -259,8 +261,14 @@ async def generate(
batch.images = n
try:
try:
# The leader takes its place in the slot's line now, so requests arriving later cannot overtake it.
if on_lead is not None:
on_lead()
while busy():
await asyncio.sleep(POLL_S)
if wait is not None:
await wait()
else:
await asyncio.sleep(POLL_S)
except Exception as exc:
if shared_outcome(exc):
_share(exc, batch.members[1:], owner)
Expand Down
81 changes: 72 additions & 9 deletions studio/backend/routes/inference.py
Original file line number Diff line number Diff line change
Expand Up @@ -53367,12 +53367,13 @@ async def _generate_xy_grid(request: DiffusionGenerateRequest) -> DiffusionGener
try:
_xy_grid_stops.append(stop)
with render_fence():
for index in plan.order:
for position, index in enumerate(plan.order):
if ticket.cancelled():
raise HTTPException(status_code = 409, detail = DIFFUSION_CANCELLED_MSG)
captured: list[Any] = []
# The engine binds each cell's cancel to the ticket before it waits for the slot.
with generation_ticket(ticket):
# The engine binds each cell's cancel to the ticket before it waits for the slot. Cells after the
# first continue a grid that already held the slot, so they go first in line.
with generation_ticket(ticket), _follow_up_pass() if position else nullcontext():
result = await _generate_diffusion_image_run(
plan.cells[index].request, captured = captured
)
Expand Down Expand Up @@ -53735,10 +53736,12 @@ async def _generate_diffusion_image_run(
_diffusion_persist_active += 1
try:
with account_access.media_generation("diffusion"):
# Crop inpaints wait on the render slot too, so use the same pool.
await _image_generate_in_thread(
_run_detailer, backend, request, result, enhancement, detailer
)
# Crop inpaints wait on the render slot too, so use the same pool; they continue this render,
# so they go first in line.
with _follow_up_pass():
await _image_generate_in_thread(
_run_detailer, backend, request, result, enhancement, detailer
)
except BaseException:
_diffusion_persist_active -= 1
raise
Expand Down Expand Up @@ -55938,6 +55941,26 @@ def _frozen_kwarg(value: Any) -> Hashable:
return value


@contextmanager
def _reserved_turn(turn: Any):
"""Generations started here use the slot turn a coalesced batch reserved (diffusers engine only)."""
if turn is None:
yield
return
from core.inference.diffusion import reserved_slot_turn

with reserved_slot_turn(turn):
yield


@contextmanager
def _follow_up_pass():
"""Generations started here continue a request that already held the slot, so they go first in line."""
from core.inference.diffusion import slot_follow_up
with slot_follow_up():
yield


# Not part of the batch key: the shared call shows the leader's preview, and the leader's own image is first.
_COALESCE_KEY_IGNORED = frozenset({"live_preview"})

Expand Down Expand Up @@ -56002,10 +56025,31 @@ async def _coalesced_image_generate(

# Wait only for the generation found on arrival, so a later one taking the slot cannot starve the batch.
arrived_behind: list = []
# The leader's place in the slot's line, taken when its batch opens (engines that keep a line only).
lead: dict = {}
reserve = getattr(backend, "reserve_slot_turn", None)
loop = asyncio.get_running_loop()
woken = asyncio.Event()

def on_lead() -> None:
if reserve is None:
return
lead["turn"] = reserve()
lead["remove"] = backend.add_slot_listener(lambda: loop.call_soon_threadsafe(woken.set))

async def wait() -> None:
# Woken by the slot itself; the timeout covers lock holders outside the line.
try:
await asyncio.wait_for(woken.wait(), timeout = 0.25)
except asyncio.TimeoutError:
pass
woken.clear()

def busy() -> bool:
if stopped.is_set():
raise RuntimeError(DIFFUSION_CANCELLED_MSG)
if "turn" in lead:
return not backend.slot_turn_ready(lead["turn"])
try:
current = holder()
except Exception: # noqa: BLE001 -- no busy signal; render individually
Expand All @@ -56030,7 +56074,7 @@ 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))
with generation_ticket(ticket):
with generation_ticket(ticket), _reserved_turn(lead.get("turn")):
try:
return await _image_generate_in_thread(
backend.generate,
Expand Down Expand Up @@ -56103,7 +56147,8 @@ def fits(total: int) -> bool:

waiter = getattr(backend, "generation_waiter", None)
rider = getattr(backend, "generation_rider", None)
with waiter(stopped) if waiter is not None else nullcontext():

async def _coalesce_in_line() -> Optional[dict]:
result = await image_request_batching.generate(
key,
prompt,
Expand All @@ -56119,12 +56164,30 @@ def fits(total: int) -> bool:
fits = fits,
splittable = splittable,
salvage = salvage,
on_lead = on_lead,
wait = wait,
)
# 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():
raise RuntimeError(DIFFUSION_CANCELLED_MSG)
return result

try:
with waiter(stopped) if waiter is not None else nullcontext():
result = await _coalesce_in_line()
# 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(
backend.generate, prompt = prompt, seed = seed, batch_size = n, **generate_kwargs
)
return result
finally:
if "remove" in lead:
lead["remove"]()
if "turn" in lead:
backend.release_slot_turn(lead["turn"])


async def _batched_openai_images(
backend: Any,
Expand Down
Loading