diff --git a/studio/backend/core/inference/diffusion.py b/studio/backend/core/inference/diffusion.py index a3f44ac5f728..0466151f63c8 100644 --- a/studio/backend/core/inference/diffusion.py +++ b/studio/backend/core/inference/diffusion.py @@ -20,6 +20,7 @@ from __future__ import annotations from contextlib import contextmanager +import collections import contextvars import functools import inspect @@ -4944,6 +4945,85 @@ 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 +) +# How long a reserved, unclaimed turn may idle first in line with the slot free before a waiter steps past it. +_RESERVED_TURN_GRACE_S = 0.5 +_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_counts(pipe: Any, prompt: str) -> Optional[tuple]: + """The conditioning chunks the weighted encode builds for ``prompt`` in each of the pipeline's CLIP encoders, + weighted and unweighted (BREAK and comma backtracking included): a batch pads every row to its longest, so + members must match exactly. None when there is no encoder to ask.""" + from .diffusion_prompt_weighting import _encoders, tokenize_chunks + + pairs = _encoders(pipe) + if not pairs: + return None + convert = getattr(pipe, "maybe_convert_prompt", None) + return tuple( + len(tokenize_chunks(prompt, tokenizer, weighted = weighted, convert = convert)) + for tokenizer, _ in pairs + for weighted in (True, False) + ) + + +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_counts(pipe, 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.""" @@ -4955,6 +5035,13 @@ def __init__(self) -> None: self._unload_waiters = 0 # _generate_lock serialises generations and is the ONLY lock the denoise holds. self._generate_lock = threading.Lock() + # 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]] = [] + # Reserved turns no generation has claimed yet: a waiter may step past one that idles at the front. + self._unclaimed_turns: set = set() self._state: Optional[_LoadState] = None self._loading: Optional[_LoadingState] = None # Bumped on begin_load/unload so a superseded worker neither commits nor stamps progress @@ -4971,6 +5058,12 @@ def __init__(self) -> None: self._active_generate_account: Optional[str] = None # Queued requests; cancel_generate() decides which Stop may signal. 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 @@ -5062,26 +5155,137 @@ 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) + self._unclaimed_turns.add(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: + getattr(self, "_unclaimed_turns", set()).discard(turn) + try: + self._slot_turns.remove(turn) + 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.""" + idle_since = None + with self._slot_turn_changed: + while self._slot_turns[0] is not turn: + if cancel.is_set(): + raise RuntimeError(DIFFUSION_CANCELLED_MSG) + head = self._slot_turns[0] + if head in self._unclaimed_turns and not self._generate_lock.locked(): + # A reserved turn first in line with the slot free and no generation claiming it: its owner + # may have no worker (every one waits here). After a grace it steps back one place. + now = time.monotonic() + idle_since = idle_since if idle_since is not None else now + if now - idle_since >= _RESERVED_TURN_GRACE_S: + self._slot_turns.popleft() + self._slot_turns.insert(1, head) + self._slot_turn_changed.notify_all() + idle_since = None + continue + else: + idle_since = None + self._slot_turn_changed.wait(timeout = 0.1) @contextmanager def _generation_slot(self, cancel: threading.Event): - """Yields to teardown fences after taking the lock (not FIFO); the zero-fence check and cancel registration must share one _lock section.""" + """First come, first served: a ticket queues each generation, and only the oldest one takes the lock, so a + 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 + reserved = _RESERVED_SLOT_TURN.get() + with self._slot_turn_changed: + if reserved is not None and reserved in self._slot_turns: + # A coalesced batch keeps the place it took when it opened. + turn = reserved + self._unclaimed_turns.discard(turn) + 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() try: while True: + self._await_slot_turn(turn, cancel) while True: 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: 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 @@ -5089,6 +5293,8 @@ def _generation_slot(self, cancel: threading.Event): else: cancelled = cancel.is_set() if admitted: + # The next waiter becomes the head and waits on the lock this generation now holds. + self._leave_slot_turn(turn) break self._generate_lock.release() if cancelled: @@ -5114,10 +5320,13 @@ 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: 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( @@ -17696,6 +17905,23 @@ def _enter_decode_phase() -> None: except BaseException: if previewer is not None: previewer.finish() + failure = sys.exc_info()[1] + # A failed batched call keeps the images that finished (in job order), so the requests they + # belong to are not rendered again. Never after a Stop. + if ( + isinstance(failure, Exception) + and images + and not cancel.is_set() + and not layer_count + and not latent_output + ): + try: + failure._unsloth_finished_images = { + "images": list(images), + "seeds": list(per_image_seeds), + } + except Exception: # noqa: BLE001 - an exception that takes no attributes keeps none + pass # A cancelled or failed render may already have generalised a reused graph, so the success path never sees the count grow: dirty it now. try: if ( @@ -17892,13 +18118,114 @@ 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``: + a per-account resource (a LoRA, or an embedding this account owns) could apply, so the request batches only + with its own account. Runs in the requesting account's context.""" + 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 prompt_key, private + + 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.""" + state = self._state + if state is None: + return None + 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, + # so a batch measured no faster than serial replay. + return { + "mode": "serial", + "reason": "CUDA graphs replay one batch size; concurrent requests render one at a time", + } + if "compiled" in (state.speed_optims or ()) and compiled_shapes_are_static( + state.pipe, state.speed_mode + ): + return { + "mode": "compiled_sizes", + "reason": "static compile: concurrent requests share a call only at batch sizes already compiled", + } + return { + "mode": "any", + "reason": "concurrent requests with the same settings share one call", + } + + 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, empty = none (CUDA + graphs serve serially; ``request_batching``). A static compile keys its artifacts on the batch, so a new + size would compile inside the slot: only sizes this load already compiled at this size are offered.""" + policy = self.request_batching() + state = self._state + if policy is None or policy["mode"] == "serial": + return frozenset() + if policy["mode"] == "any": + 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 + another account's generation holds the slot.""" + account = current_account_id() + with self._generation_cancel_lock: + self._generate_riders[cancel] = account + try: + yield + finally: + with self._generation_cancel_lock: + self._generate_riders.pop(cancel, None) + + 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__. + events = [ + event + 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 events: + event.set() + 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: @@ -17932,17 +18259,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, - ): - return False + 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 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 ( @@ -17951,8 +18282,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: @@ -18267,6 +18605,7 @@ def status(self) -> dict[str, Any]: tuple(getattr(state.pipe, "_unsloth_cuda_graphs", ()) or ()) or getattr(state, "cuda_graphs", ()) ), + "request_batching": self.request_batching(), "cfg_batch": cfg_batch_status(state.pipe), "zimage_cfg_split": zimage_cfg_split_status(state.pipe), "resolved": resolved, diff --git a/studio/backend/core/inference/diffusion_detailer.py b/studio/backend/core/inference/diffusion_detailer.py index ede2721b71fd..d8ec0ca7185a 100644 --- a/studio/backend/core/inference/diffusion_detailer.py +++ b/studio/backend/core/inference/diffusion_detailer.py @@ -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 diff --git a/studio/backend/core/inference/image_request_batching.py b/studio/backend/core/inference/image_request_batching.py index 14abba776b8d..47466758f6b6 100644 --- a/studio/backend/core/inference/image_request_batching.py +++ b/studio/backend/core/inference/image_request_batching.py @@ -1,15 +1,19 @@ # SPDX-License-Identifier: AGPL-3.0-only # Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0 -"""Batches waiting /v1/images/generations requests; pixels vary with batch size (diffusion_batched).""" +"""Batches waiting image requests from any account; pixels vary with batch size (diffusion_batched). + +Each member gets only its own images through its own future. A shared outcome (a Stop) reaches only members of +the leader's account; every other member renders alone instead.""" from __future__ import annotations import asyncio import os import secrets +from contextlib import nullcontext from dataclasses import dataclass, field -from typing import Any, Awaitable, Callable, Hashable, Optional +from typing import Any, Awaitable, Callable, ContextManager, Hashable, Optional from loggers import get_logger @@ -17,8 +21,10 @@ logger = get_logger(__name__) -BATCH_MAX_DEFAULT = 4 +BATCH_MAX_DEFAULT = 8 POLL_S = 0.05 +# Result fields derived from every prompt in the call: a member must not see them for another account's prompt. +_PROMPT_DERIVED_FIELDS = ("embeddings", "embeddings_skipped") class _RunAlone(Exception): @@ -30,6 +36,7 @@ class _Member: prompt: str seeds: list[int] future: "asyncio.Future[dict[str, Any]]" + owner: Hashable = None @dataclass @@ -37,6 +44,8 @@ class _Batch: key: Hashable members: list[_Member] = field(default_factory = list) images: int = 0 + # Set once the leader snapshots its members: a member leaving later only drops its result. + fired: bool = False _OPEN: dict[Hashable, _Batch] = {} @@ -49,19 +58,54 @@ def batch_max() -> int: return BATCH_MAX_DEFAULT +def collecting() -> bool: + """Whether any batch is open for a request to join.""" + return bool(_OPEN) + + +def seeded_join_enabled() -> bool: + """An explicit seed joins a batch only when opted in: batched pixels can differ slightly from a solo render's.""" + return os.environ.get("UNSLOTH_STUDIO_IMAGE_BATCH_SEEDED", "").strip().lower() in ( + "1", + "true", + "yes", + "on", + ) + + def request_seeds(seed: Optional[int], n: int) -> list[int]: base = seed if seed is not None else secrets.randbelow(SEED_MASK + 1) return [(base + i) & SEED_MASK for i in range(n)] -def _split(result: dict[str, Any], members: list[_Member]) -> list[dict[str, Any]]: +def _split( + result: dict[str, Any], + members: list[_Member], + *, + prefix: bool = False, +) -> list[dict[str, Any]]: + """Each member's slice of a batched result, in order. ``prefix``: a failed call's finished images, so only + the leading members whose images all finished get a part.""" images = list(result.get("images") or []) seeds = list(result.get("seeds") or []) wanted = sum(len(member.seeds) for member in members) + if prefix: + covered, total = [], 0 + for member in members: + if total + len(member.seeds) > len(images): + break + total += len(member.seeds) + covered.append(member) + members, wanted = covered, total + images, seeds = images[:total], seeds[:total] if len(images) != wanted or (seeds and len(seeds) != wanted): raise ValueError(f"a batch of {wanted} images returned {len(images)}") + if len({member.owner for member in members}) > 1: + result = {k: v for k, v in result.items() if k not in _PROMPT_DERIVED_FIELDS} parts = [] start = 0 + # The forward these images came from, so a recipe can tell its pixels were rendered in a batch. + call_size = sum(len(member.seeds) for member in members) for member in members: end = start + len(member.seeds) parts.append( @@ -70,23 +114,112 @@ def _split(result: dict[str, Any], members: list[_Member]) -> list[dict[str, Any "images": images[start:end], "seeds": seeds[start:end] if seeds else list(member.seeds), "seed": member.seeds[0], + "coalesced_batch_size": call_size, + "coalesced_index": start, } ) start = end return parts -def _share(exc: BaseException, members: list[_Member]) -> None: +def _share(exc: BaseException, members: list[_Member], owner: Hashable) -> None: + """Ends the leader's own account's members with the outcome; the finally sends the rest to render alone.""" for member in members: - if not member.future.done(): + if member.owner == owner and not member.future.done(): 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] + + +async def _render_group( + group: list[_Member], + run_batch: Callable[..., Awaitable[dict[str, Any]]], + shared_outcome: Callable[[BaseException], bool], + splittable: Optional[Callable[[BaseException], bool]], + salvage: Optional[Callable[[BaseException], Optional[dict[str, Any]]]], + fits: Optional[Callable[[int], bool]] = None, +) -> dict[int, dict[str, Any]]: + """Renders ``group`` as one call; ``{id(member): part}`` for every member it rendered. A failure keeps the + images that finished; a refusal, a ValueError or an OOM splits the rest by member, so one member's error never + fails the others. Members left out render alone; only a shared outcome raises. Every call, a recovery split + included, uses a size ``fits`` admits.""" + group = [member for member in group if not member.future.done()] + if fits is not None: + group = _fitting_prefix(group, fits) + if len(group) < 2: + return {} + prompts = [member.prompt for member in group for _ in member.seeds] + seeds = [s for member in group for s in member.seeds] + try: + result = await run_batch(prompts, seeds, owners = [member.owner for member in group]) + return {id(m): part for m, part in zip(group, _split(result, group))} + except Exception as exc: # noqa: BLE001 -- keep what finished, split what can be split + if shared_outcome(exc): + raise + done: dict[int, dict[str, Any]] = {} + finished = salvage(exc) if salvage is not None else None + if finished: + try: + parts = _split(finished, group, prefix = True) + except ValueError: # noqa: PERF203 -- a malformed salvage keeps nothing + parts = [] + done.update((id(m), part) for m, part in zip(group, parts)) + rest = [member for member in group if id(member) not in done] + logger.info( + "images.batch_failed: %s; %d of %d requests kept their finished images", + exc, + len(done), + len(group), + ) + if len(rest) > 1 and splittable is not None and splittable(exc): + middle = (len(rest) + 1) // 2 + for half in (rest[:middle], rest[middle:]): + done.update( + await _render_group(half, run_batch, shared_outcome, splittable, salvage, fits) + ) + return done + + def _close(batch: _Batch) -> None: if _OPEN.get(batch.key) is batch: del _OPEN[batch.key] +def _leave(batch: _Batch, member: _Member) -> None: + """A member stopped or disconnected: drop its prompt if the batch has not fired, never its neighbours'.""" + if not batch.fired and member in batch.members: + batch.members.remove(member) + batch.images -= len(member.seeds) + if not member.future.done(): + member.future.cancel() + + +async def _await_member( + batch: _Batch, member: _Member, check: Optional[Callable[[], None]] +) -> dict[str, Any]: + try: + while True: + # Checked again after the result lands: a Stop never hands back images. + if check is not None: + check() + if member.future.done(): + return member.future.result() + await asyncio.wait({member.future}, timeout = POLL_S) + except _RunAlone: + raise + except BaseException: + _leave(batch, member) + raise + + async def generate( key: Hashable, prompt: str, @@ -96,62 +229,90 @@ async def generate( busy: Callable[[], bool], run_batch: Callable[[list[str], list[int]], Awaitable[dict[str, Any]]], shared_outcome: Callable[[BaseException], bool] = lambda exc: False, + owner: Hashable = None, + check: Optional[Callable[[], None]] = None, + ride: Optional[Callable[[], ContextManager[Any]]] = None, + 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.""" cap = batch_max() - # An explicit seed renders alone: a batch's pixels differ slightly from a lone render's. - if cap <= 1 or n >= cap or seed is not None: + # An explicit seed renders alone unless opted in: a batch's pixels differ slightly from a lone render's. + if cap <= 1 or n >= cap or (seed is not None and not seeded_join_enabled()): return None loop = asyncio.get_running_loop() batch = _OPEN.get(key) if batch is not None: - if batch.images + n > cap: - return None - member = _Member(prompt, request_seeds(seed, n), loop.create_future()) - batch.members.append(member) - batch.images += n - try: - return await member.future - except _RunAlone: - return None + if batch.images + n <= cap: + member = _Member(prompt, request_seeds(seed, n), loop.create_future(), owner) + batch.members.append(member) + batch.images += n + # Full: the next request opens a batch of its own instead of rendering alone. + if batch.images >= cap: + _close(batch) + try: + with ride() if ride is not None else nullcontext(): + return await _await_member(batch, member, check) + except _RunAlone: + return None + # It does not fit: that batch keeps its members and stops collecting; this request opens the next one. + _close(batch) if not busy(): return None batch = _OPEN[key] = _Batch(key) - batch.members.append(_Member(prompt, request_seeds(seed, n), loop.create_future())) + batch.members.append(_Member(prompt, request_seeds(seed, n), loop.create_future(), owner)) 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:]) + _share(exc, batch.members[1:], owner) raise _close(batch) - members = list(batch.members) - if len(members) == 1: + batch.fired = True + leader = batch.members[0] + # A blank prompt fails validation for the whole call: it renders alone and gets its own error. + if not leader.prompt.strip(): + return None + members = [member for member in batch.members if member.prompt.strip()] + 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] logger.info( - "openai_images.batch: %d requests render as one call of %d images", + "images.batch: %d requests from %d accounts render as one call of %d images", len(members), - len(seeds), + len({member.owner for member in members}), + sum(len(member.seeds) for member in members), ) try: - parts = _split(await run_batch(prompts, seeds), members) - except Exception as exc: # noqa: BLE001 -- fall back unless the outcome applies to every request - if shared_outcome(exc): - _share(exc, members[1:]) - raise - logger.info("openai_images.batch_failed: %s; each request runs alone", exc) - return None - for member, part in zip(members[1:], parts[1:]): - if not member.future.done(): + done = await _render_group( + members, run_batch, shared_outcome, splittable, salvage, fits + ) + except Exception as exc: + _share(exc, members[1:], owner) + raise + for member in members[1:]: + part = done.get(id(member)) + if part is not None and not member.future.done(): member.future.set_result(part) - return parts[0] + return done.get(id(leader)) finally: _close(batch) + batch.fired = True for member in batch.members[1:]: if not member.future.done(): member.future.set_exception(_RunAlone()) diff --git a/studio/backend/models/inference.py b/studio/backend/models/inference.py index 07c7c99ac656..7a11949e134a 100644 --- a/studio/backend/models/inference.py +++ b/studio/backend/models/inference.py @@ -5948,6 +5948,13 @@ class GalleryImage(BaseModel): batch_size: int = Field( 1, description = "Batch size used; with batch_index it lets restore replay this image" ) + coalesced_batch_size: Optional[int] = Field( + None, + description = "Images in the shared call this one rendered in, when concurrent requests were batched", + ) + coalesced_index: Optional[int] = Field( + None, description = "This image's position in that shared call (0-based)" + ) generation_seconds: Optional[float] = Field( None, description = "Elapsed generation seconds until images are ready to save, shared by the request", @@ -6500,6 +6507,12 @@ class DiffusionStatusResponse(BaseModel): "denoiser calls (whole-step, per block, per-card segments, and the per-block graphs a whole-step graph falls " "back to), and the process's dynamo frame and graph-break totals; null when nothing is loaded.", ) + request_batching: Optional[Dict[str, str]] = Field( + None, + description = "How concurrent text-to-image requests share pipeline calls on this load: mode 'any', " + "'compiled_sizes' (static compile, only batch sizes already compiled) or 'serial' (CUDA graphs, every request " + "renders alone), with the reason; null when nothing is loaded.", + ) fp8_gemm: Optional[Dict[str, Any]] = Field( None, description = "Which fp8 GEMM an fp8 load runs: path 'torchao_rowwise', or 'unit_scale_fallback' when this " diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.py index f14d30cfc31f..badad574d1be 100644 --- a/studio/backend/routes/inference.py +++ b/studio/backend/routes/inference.py @@ -36,6 +36,7 @@ Any, Callable, Collection, + Hashable, List, Literal, NamedTuple, @@ -293,6 +294,9 @@ def _hook(unraisable): # Queued renders wait for the one-render slot inside their thread; on the default executor they would hold every worker. _IMAGE_GENERATE_EXECUTOR_ENV = "UNSLOTH_DIFFUSION_GENERATE_EXECUTOR" _IMAGE_GENERATE_EXECUTOR = ThreadPoolExecutor(max_workers = 32, thread_name_prefix = "image-generate") +# A coalesced batch's own call runs here: its slot turn is first in line, so it starts at once, while requests +# queued behind that turn may hold every worker of the pool above. +_IMAGE_BATCH_EXECUTOR = ThreadPoolExecutor(max_workers = 4, thread_name_prefix = "image-batch") async def _image_generate_in_thread(func, /, *args, **kwargs): @@ -309,6 +313,13 @@ async def _image_generate_in_thread(func, /, *args, **kwargs): return await loop.run_in_executor(_IMAGE_GENERATE_EXECUTOR, call) +async def _image_generate_on_reserved_turn(func, /, *args, **kwargs): + """Runs a call that uses a reserved slot turn on its own pool, never behind the waiters it is ahead of.""" + loop = asyncio.get_running_loop() + call = functools.partial(contextvars.copy_context().run, func, *args, **kwargs) + return await loop.run_in_executor(_IMAGE_BATCH_EXECUTOR, call) + + def _loaded_chat_template() -> Optional[str]: """Chat template llama-server renders for the loaded GGUF: the override when one is set.""" try: @@ -53303,7 +53314,7 @@ async def generate_diffusion_image( if request.xy is not None: response = await _generate_xy_grid(request) else: - response = await _generate_diffusion_image_core(request) + response = await _generate_diffusion_image_core(request, coalesce = True) finished = True return response finally: @@ -53366,12 +53377,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 ) @@ -53420,7 +53432,10 @@ def _save_grid() -> dict: async def _generate_diffusion_image_core( - request: DiffusionGenerateRequest, pinned_load = None + request: DiffusionGenerateRequest, + pinned_load = None, + *, + coalesce: bool = False, ) -> DiffusionGenerateResponse: """The local-engine image run, shared by the route and the chat generate_image tool.""" from core.inference.diffusion_segment import render_fence @@ -53428,13 +53443,40 @@ async def _generate_diffusion_image_core( # From before the run releases the mask segmenter until it ends: a Find cannot reload SAM 3 in the gap before the # render takes the engine's generation slot. with render_fence(): - return await _generate_diffusion_image_run(request, pinned_load = pinned_load) + return await _generate_diffusion_image_run( + request, pinned_load = pinned_load, coalesce = coalesce + ) + + +def _plain_txt2img(request: DiffusionGenerateRequest, enhancement: Any, detailer: Any) -> bool: + """A Create run with no input image, mask, ControlNet, Detailer, hires, variation or prompt / seed lists: the + only /images/generate shape that may share a batched call.""" + return ( + request.prompts is None + and request.seeds is None + and request.init_image is None + and request.mask_image is None + and not request.reference_images + and request.workflow is None + and request.localized_edit is None + and request.controlnet is None + and request.upscale is None + and request.upscale_model is None + and request.hires is None + and request.variation_seed is None + # A random subseed repeats the base seed across the request's images: explicit per-member seeds would not. + and not request.variation_strength + and request.xy is None + and detailer is None + and not getattr(enhancement, "captions", None) + ) async def _generate_diffusion_image_run( request: DiffusionGenerateRequest, captured: Optional[list] = None, pinned_load = None, + coalesce: bool = False, ) -> DiffusionGenerateResponse: from core.inference import image_gallery from core.inference.diffusion_engine_router import get_active_diffusion_engine @@ -53586,8 +53628,7 @@ async def _generate_diffusion_image_run( reset_media_generation_progress("image") try: with account_access.media_generation("diffusion"): - result = await _image_generate_in_thread( - backend.generate, + generate_kwargs = dict( expected_load = expected_load, **_expected_load_loras_kwarg(backend.generate, expected_load_loras), prompt = enhancement.encoded(request.prompt), @@ -53636,6 +53677,23 @@ async def _generate_diffusion_image_run( **_inpaint_mask_kwargs(backend.generate, request), **_hires_kwargs(backend.generate, request), ) + result = None + # Joins a batch only while a render runs, so a lone request starts exactly as before. + if coalesce and captured is None and _plain_txt2img(request, enhancement, detailer): + result = await _coalesced_image_generate( + backend, + status, + prompt = generate_kwargs["prompt"], + n = request.batch_size, + seed = request.seed, + generate_kwargs = { + name: value + for name, value in generate_kwargs.items() + if name not in ("prompt", "seed", "batch_size", "prompts", "seeds") + }, + ) + if result is None: + result = await _image_generate_in_thread(backend.generate, **generate_kwargs) break except ImageActivationShortfallError as exc: # Tagged so the Images page can offer "Generate anyway". @@ -53690,10 +53748,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 @@ -53744,6 +53804,7 @@ def _persist() -> list[dict]: "batch_index": index, # The batch shares one seed, so reproducing a batch_index>0 image needs the original batch_size. "batch_size": 1 if list_driven else request.batch_size, + **_coalesced_recipe(result, index), "generation_seconds": generation_seconds, "generation_count": len(result["images"]), "model": result.get("repo_id"), @@ -54899,6 +54960,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) @@ -54915,6 +54989,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") @@ -55860,21 +55937,77 @@ def _image_generation_defaults(status: dict) -> tuple[int, float]: ) -async def _batched_openai_images( +def _frozen_kwarg(value: Any) -> Hashable: + """A hashable stand-in for one generate() argument, so the batch key holds every setting that changes output.""" + if isinstance(value, dict): + return tuple(sorted((str(k), _frozen_kwarg(v)) for k, v in value.items())) + if isinstance(value, (list, tuple)): + return tuple(_frozen_kwarg(v) for v in value) + if hasattr(value, "model_dump"): + return (type(value).__name__, _frozen_kwarg(value.model_dump())) + if dataclasses.is_dataclass(value) and not isinstance(value, type): + return (type(value).__name__, _frozen_kwarg(dataclasses.asdict(value))) + try: + hash(value) + except TypeError: + return (type(value).__name__, repr(value)) + return value + + +def _coalesced_recipe(result: dict, index: int) -> dict: + """Where an image sat in a coalesced call: its pixels come from a forward of that size, so a solo replay of the + seed lands close to it, not on it. Nothing for an image rendered alone.""" + size = result.get("coalesced_batch_size") + if not size: + return {} + return { + "coalesced_batch_size": int(size), + "coalesced_index": int(result.get("coalesced_index") or 0) + index, + } + + +@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"}) + + +async def _coalesced_image_generate( backend: Any, - status: dict, - body: ImageGenerationRequest, - width: int, - height: int, - steps: int, - guidance: float, - expected_load: Any, - loras: Optional[list[tuple[str, float]]] = None, - expected_load_loras: Optional[tuple] = None, + status: Optional[dict], + *, + prompt: str, + n: int, + seed: Optional[int], + generate_kwargs: dict, ) -> Optional[dict]: + """Joins this request to a batch while a render runs, any account included; None = render alone. + + ``generate_kwargs`` is everything but the prompt / seed / count: all of it goes into the key, so only requests + whose renders would match share a call, and each member gets only its own images back.""" from core.inference import image_request_batching from core.inference.diffusion_engine_router import ENGINE_DIFFUSERS, active_engine_name from core.inference.diffusion_families import DIFFUSION_CANCELLED_MSG + from core.inference.diffusion_anima import ANIMA_FAMILY_NAME + from core.inference.diffusion_families import detect_family from core.inference.diffusion_flux3 import FLUX3_FAMILY_NAMES from core.inference.generation_ticket import ( GenerationTicket, @@ -55883,22 +56016,75 @@ async def _batched_openai_images( ) holder = getattr(backend, "generation_holder", None) - if ( - holder is None - or active_engine_name() != ENGINE_DIFFUSERS - or status.get("family") in FLUX3_FAMILY_NAMES - ): + if holder is None or active_engine_name() != ENGINE_DIFFUSERS: + return None + # An idle engine with no batch collecting renders this request at once, with no extra status read. + if not image_request_batching.collecting(): + try: + if holder() is None: + return None + except Exception: # noqa: BLE001 -- no busy signal; render individually + return None + if status is None: + status = await asyncio.to_thread(backend.status) + family = status.get("family") + # FLUX.3 and Anima render one image per call, and a layered model returns several pictures per image. + if family in FLUX3_FAMILY_NAMES or family == ANIMA_FAMILY_NAME: + return None + if family and getattr(detect_family("", family), "layer_count", 0): return None + if generate_kwargs.get("expected_load") is None: + # Pin the shared call to the model these settings were read for, so a model swapped in meanwhile is refused + # (each member then retries) instead of rendering every member on it. + from core.inference.diffusion_families import load_identity + generate_kwargs = { + **generate_kwargs, + "expected_load": load_identity( + status.get("repo_id"), status.get("base_repo"), status.get("family") + ), + } + # LoRA ids, hosted adapters (with their HF token) and textual-inversion embeddings resolve under the account + # that runs the call, the leader: a request that could use any of them batches with its own account only. + plan = getattr(backend, "coalesce_plan", None) + loras = generate_kwargs.get("loras") + if plan is not None: + decided = await asyncio.to_thread(plan, prompt, bool(loras)) + if decided is None: + return None + prompt_key, private = decided + else: + prompt_key, private = (), bool(loras) ticket = GenerationTicket() stopped = TicketStopEvent(ticket) # 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 @@ -55909,23 +56095,30 @@ def busy() -> bool: arrived_behind.append(current) return current is arrived_behind[0] - async def run_batch(prompts: list[str], seeds: list[int]) -> dict: - with generation_ticket(ticket): + def check() -> None: + if stopped.is_set(): + raise RuntimeError(DIFFUSION_CANCELLED_MSG) + + async def run_batch( + prompts: list[str], + seeds: list[int], + owners: Optional[list] = None, + ) -> dict: + call = dict(generate_kwargs) + if len(set(owners or ())) > 1: + # 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)) + runner = _image_generate_on_reserved_turn if "turn" in lead else _image_generate_in_thread + with generation_ticket(ticket), _reserved_turn(lead.get("turn")): try: - return await _image_generate_in_thread( + return await runner( backend.generate, prompt = prompts[0], - negative_prompt = body.negative_prompt, - width = width, - height = height, - steps = steps, - guidance = guidance, prompts = prompts, seeds = seeds, batch_size = len(seeds), - expected_load = expected_load, - **_expected_load_loras_kwarg(backend.generate, expected_load_loras), - **({"loras": loras} if loras else {}), + **call, ) except Exception as exc: # An engine Stop sets the bound event, not ``stopped``: no member may retry alone. @@ -55933,37 +56126,135 @@ async def run_batch(prompts: list[str], seeds: list[int]) -> dict: raise RuntimeError(DIFFUSION_CANCELLED_MSG) from exc raise + # No account unless a per-account resource could apply: then only this account's requests share the call. key = ( - current_account_id(), - expected_load, - expected_load_loras, - width, - height, - steps, - guidance, - body.negative_prompt or None, - tuple(loras or ()), + current_account_id() if private else None, + prompt_key, + tuple( + sorted( + (name, _frozen_kwarg(value)) + for name, value in generate_kwargs.items() + if name not in _COALESCE_KEY_IGNORED + ) + ), ) def cancelled(exc: BaseException) -> bool: return isinstance(exc, RuntimeError) and str(exc) == DIFFUSION_CANCELLED_MSG + def splittable(exc: BaseException) -> bool: + """One member's input or size can cause these, so the batch splits by member instead of failing all.""" + from core.inference.diffusion_batched import is_oom_error + from core.inference.diffusion_memory import unified_memory_refusal_code + + return ( + isinstance(exc, ValueError) + or unified_memory_refusal_code(exc) is not None + or is_oom_error(exc) + ) + + def salvage(exc: BaseException) -> Optional[dict]: + """The images a failed call finished, as a result its leading members can keep.""" + finished = getattr(exc, "_unsloth_finished_images", None) + if not finished or not finished.get("images"): + return None + return { + "images": list(finished["images"]), + "seeds": list(finished.get("seeds") or []), + "seed": (finished.get("seeds") or [0])[0], + "repo_id": status.get("repo_id"), + "model_kind": status.get("model_kind"), + "gguf_filename": status.get("gguf_filename"), + "negative_prompt": generate_kwargs.get("negative_prompt") or None, + "workflow": "txt2img", + } + + 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) - with waiter(stopped) if waiter is not None else nullcontext(): + rider = getattr(backend, "generation_rider", None) + + async def _coalesce_in_line() -> Optional[dict]: result = await image_request_batching.generate( key, - body.prompt, - body.n, - body.seed, + prompt, + n, + seed, busy = busy, run_batch = run_batch, shared_outcome = cancelled, + owner = current_account_id(), + 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, + 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_on_reserved_turn( + 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, + status: dict, + body: ImageGenerationRequest, + width: int, + height: int, + steps: int, + guidance: float, + expected_load: Any, + loras: Optional[list[tuple[str, float]]] = None, + expected_load_loras: Optional[tuple] = None, +) -> Optional[dict]: + return await _coalesced_image_generate( + backend, + status, + prompt = body.prompt, + n = body.n, + seed = body.seed, + generate_kwargs = dict( + negative_prompt = body.negative_prompt, + width = width, + height = height, + steps = steps, + guidance = guidance, + expected_load = expected_load, + **_expected_load_loras_kwarg(backend.generate, expected_load_loras), + **({"loras": loras} if loras else {}), + ), + ) + # Split out so the monitor row can wrap the whole handler without reindenting it. async def _generate_openai_images( @@ -56171,7 +56462,13 @@ def _persist() -> list[ImageGenerationData]: saves.append( ( image, - {**recipe, "batch_index": index, "seed": seed, "batch_seed": result["seed"]}, + { + **recipe, + "batch_index": index, + "seed": seed, + "batch_seed": result["seed"], + **_coalesced_recipe(result, index), + }, ) ) for record in image_gallery.save_many(saves): diff --git a/studio/backend/tests/test_diffusion_segment.py b/studio/backend/tests/test_diffusion_segment.py index 19574ee0dff4..bc266986922b 100644 --- a/studio/backend/tests/test_diffusion_segment.py +++ b/studio/backend/tests/test_diffusion_segment.py @@ -1725,7 +1725,11 @@ def test_no_find_starts_while_a_render_is_on_its_way(monkeypatch): ) seen = [] - async def _run(request, pinned_load = None): + async def _run( + request, + pinned_load = None, + **_kwargs, + ): # The render released SAM 3 and has not taken the slot yet: a Find is refused, and frees the slot it took. with pytest.raises(seg.SegmenterBusyError, match = "generating"): seg.segment_image(_png_b64(), "sofa") diff --git a/studio/backend/tests/test_image_concurrency.py b/studio/backend/tests/test_image_concurrency.py new file mode 100644 index 000000000000..393b4b9d3ac6 --- /dev/null +++ b/studio/backend/tests/test_image_concurrency.py @@ -0,0 +1,607 @@ +# SPDX-License-Identifier: AGPL-3.0-only +# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0 + +"""Concurrent image users: requests from different accounts share one batched call, each gets only its own images, +and one member's Stop never ends another account's request.""" + +from __future__ import annotations + +import asyncio +import contextlib +import threading + +import httpx +import pytest +from fastapi import FastAPI + +import core.inference.diffusion as diffusion_module +import core.inference.diffusion_engine_router as engine_router +import core.inference.gpu_arbiter as gpu_arbiter +import core.inference.image_gallery as gallery_module +from auth.authentication import authenticated_via_api_key, get_current_subject +from core.inference import image_request_batching as batching +from routes.inference import router, studio_router +from utils.account_context import ( + ROLE_OWNER, + AccountContext, + bind_account, + current_account_id, + reset_account, +) +from utils.api_errors import install_api_error_handlers + + +class _Backend: + """Diffusers-shaped fake: one slot, per-account Stop, batched calls labelled by prompt and seed.""" + + def __init__(self) -> None: + self.rendering = False + self.holder = object() + self.calls: list[dict] = [] + self.waiters: list = [] + self.riders: list[tuple[threading.Event, str]] = [] + self.active_cancel = None + self.active_account = None + self.is_loaded = True + self.during_batch = None + + def status(self) -> dict: + return { + "loaded": True, + "repo_id": "unsloth/Z-Image-Turbo-GGUF", + "family": "z-image", + "base_repo": None, + } + + def load_progress(self) -> dict: + return {"phase": "ready"} + + def generation_holder(self): + return self.holder if self.rendering else None + + @contextlib.contextmanager + def generation_waiter(self, cancel): + self.waiters.append(cancel) + try: + yield + finally: + self.waiters.remove(cancel) + + @contextlib.contextmanager + def generation_rider(self, cancel): + entry = (cancel, current_account_id()) + self.riders.append(entry) + try: + yield + finally: + self.riders.remove(entry) + + def cancel_generate(self, expected_account = None) -> bool: + if self.active_cancel is not None and expected_account in (None, self.active_account): + self.active_cancel.set() + return True + mine = [cancel for cancel, owner in self.riders if owner == expected_account] + for cancel in mine: + cancel.set() + return bool(mine) + + def generate( + self, + *, + prompt, + seed = None, + batch_size = 1, + prompts = None, + seeds = None, + sd_controls = None, + live_preview = None, + **kwargs, + ): + kwargs.update(sd_controls = sd_controls, live_preview = live_preview) + from core.inference.diffusion_families import DIFFUSION_CANCELLED_MSG + from core.inference.generation_ticket import bind_generation_cancel + + cancel = threading.Event() + bind_generation_cancel(cancel) + self.active_cancel, self.active_account = cancel, current_account_id() + self.calls.append( + dict( + account = current_account_id(), + prompt = prompt, + prompts = prompts, + seeds = seeds, + seed = seed, + batch_size = batch_size, + kwargs = kwargs, + ) + ) + try: + if prompts is not None and self.during_batch is not None: + self.during_batch() + if cancel.is_set(): + raise RuntimeError(DIFFUSION_CANCELLED_MSG) + finally: + self.active_cancel = self.active_account = None + if seeds is not None: + base, image_seeds = seeds[0], list(seeds) + else: + base = 4242 if seed is None else seed + image_seeds = [base + i for i in range(batch_size)] + labels = prompts if prompts is not None else [prompt] * len(image_seeds) + return { + "images": [f"{label}#{s}" for label, s in zip(labels, image_seeds)], + "seed": base, + "seeds": image_seeds, + "repo_id": "unsloth/Z-Image-Turbo-GGUF", + "negative_prompt": kwargs.get("negative_prompt"), + # Derived from every prompt of the call, like textual-inversion names. + "embeddings": sorted(set(labels)), + "workflow": "txt2img", + } + + +def _accounts(app): + """Binds the X-Test-Account header as the acting account (owner role, so no managed-account checks).""" + + async def asgi(scope, receive, send): + account = dict(scope.get("headers") or ()).get(b"x-test-account") + if scope["type"] != "http" or account is None: + return await app(scope, receive, send) + name = account.decode() + token = bind_account(AccountContext(name, name, ROLE_OWNER)) + try: + await app(scope, receive, send) + finally: + reset_account(token) + + return asgi + + +@pytest.fixture +def studio(monkeypatch): + backend = _Backend() + saved: list[dict] = [] + + def _save(image, meta): + image_id = f"img{len(saved)}" + record = { + **meta, + "id": image_id, + "url": f"/api/inference/images/gallery/{image_id}/file", + "image": image, + "account": current_account_id(), + } + saved.append(record) + return record + + monkeypatch.setattr(diffusion_module, "get_diffusion_backend", lambda: backend) + monkeypatch.setattr(engine_router, "get_active_diffusion_engine", lambda: backend) + monkeypatch.setattr(engine_router, "_active_engine_name", "diffusers") + monkeypatch.setattr(gpu_arbiter, "_owner", None) + monkeypatch.setattr(gallery_module, "save", _save) + monkeypatch.setattr(gallery_module, "image_b64", lambda image_id: "QUJD") + app = FastAPI() + install_api_error_handlers(app) + app.include_router(router, prefix = "/v1") + app.include_router(studio_router, prefix = "/api/inference") + app.dependency_overrides[get_current_subject] = lambda: "test-user" + app.dependency_overrides[authenticated_via_api_key] = lambda: False + return _accounts(app), backend, saved + + +async def _until(predicate, timeout = 5.0) -> None: + deadline = asyncio.get_running_loop().time() + timeout + while not predicate(): + if asyncio.get_running_loop().time() > deadline: + raise AssertionError("condition never held") + await asyncio.sleep(0.01) + + +def _waiting() -> int: + return sum(len(batch.members) for batch in batching._OPEN.values()) + + +def _openai(prompt: str, **extra) -> dict: + return {"prompt": prompt, "size": "256x256", "response_format": "b64_json", **extra} + + +def _post_while_rendering( + app, + backend, + posts, + waiting, + *, + then = None, +): + """``posts``: (path, account, body). Holds the slot until ``waiting`` requests queue, then frees it.""" + + async def run(): + transport = httpx.ASGITransport(app = app) + async with httpx.AsyncClient(transport = transport, base_url = "http://studio") as client: + backend.rendering = True + sent = [] + # One at a time, so the first post leads its batch. + for path, account, body in posts: + sent.append( + asyncio.ensure_future( + client.post(path, json = body, headers = {"x-test-account": account}) + ) + ) + count = len(sent) + await _until(lambda: _waiting() >= min(count, waiting)) + await _until(lambda: _waiting() >= waiting) + if then is not None: + await then() + backend.rendering = False + return await asyncio.gather(*sent) + + return asyncio.run(run()) + + +def _batched_calls(backend) -> list[dict]: + return [call for call in backend.calls if call["prompts"] is not None] + + +def test_two_accounts_with_identical_settings_share_one_call_and_each_gets_only_its_own_images( + studio, +): + app, backend, saved = studio + posts = [ + ("/v1/images/generations", "alice", _openai("a fox", n = 2)), + ("/v1/images/generations", "bob", _openai("a secret cat")), + ] + responses = _post_while_rendering(app, backend, posts, waiting = 2) + assert [r.status_code for r in responses] == [200, 200] + assert [len(r.json()["data"]) for r in responses] == [2, 1] + [call] = backend.calls + assert sorted(call["prompts"]) == ["a fox", "a fox", "a secret cat"] + by_account: dict[str, list] = {} + for record in saved: + by_account.setdefault(record["account"], []).append((record["prompt"], record["image"])) + assert {prompt for prompt, _ in by_account["alice"]} == {"a fox"} + assert all(image.startswith("a fox#") for _, image in by_account["alice"]) + assert by_account["bob"] == [("a secret cat", by_account["bob"][0][1])] + assert by_account["bob"][0][1].startswith("a secret cat#") + + +def test_prompt_derived_result_fields_never_cross_accounts(): + from core.inference.image_request_batching import _Member, _split + loop = asyncio.new_event_loop() + try: + members = [ + _Member("a fox", [1], loop.create_future(), "alice"), + _Member("a secret cat", [2], loop.create_future(), "bob"), + ] + result = {"images": ["fox", "cat"], "seeds": [1, 2], "seed": 1, "embeddings": ["cat"]} + parts = _split(result, members) + assert [part["images"] for part in parts] == [["fox"], ["cat"]] + assert all("embeddings" not in part for part in parts) + same = [ + _Member("a", [1], loop.create_future(), "alice"), + _Member("b", [2], loop.create_future(), "alice"), + ] + assert _split(result, same)[0]["embeddings"] == ["cat"] + finally: + loop.close() + + +@pytest.mark.parametrize( + "other", + [ + {"size": "512x512"}, + {"negative_prompt": "blurry"}, + {"steps": 4}, + {"guidance": 2.5}, + {"loras": [{"id": "style-lora", "weight": 0.5}]}, + ], +) +def test_requests_with_different_settings_never_share_a_call(studio, other): + app, backend, _saved = studio + posts = [ + ("/v1/images/generations", "alice", _openai("a fox")), + ("/v1/images/generations", "bob", _openai("a cat", **other)), + ] + responses = _post_while_rendering(app, backend, posts, waiting = 2) + assert all(r.status_code == 200 for r in responses), [r.text for r in responses] + assert len(backend.calls) == 2 + assert _batched_calls(backend) == [] + + +def test_mixed_settings_group_only_the_matching_accounts(studio): + app, backend, _saved = studio + posts = [ + ("/v1/images/generations", "alice", _openai("a fox")), + ("/v1/images/generations", "bob", _openai("a cat")), + ("/v1/images/generations", "carol", _openai("an owl", steps = 3)), + ] + 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 cat", "a fox"] + assert [c["prompt"] for c in backend.calls if c["prompts"] is None] == ["an owl"] + + +def test_a_member_stop_leaves_the_batch_and_the_other_accounts_still_render(studio): + app, backend, saved = studio + posts = [ + ("/v1/images/generations", "alice", _openai("a fox")), + ("/v1/images/generations", "bob", _openai("a cat")), + ("/v1/images/generations", "carol", _openai("an owl")), + ] + + async def bob_stops(): + await _until(lambda: len(backend.riders) == 2) + assert backend.cancel_generate(expected_account = "bob") is True + await _until(lambda: _waiting() == 2) + + responses = _post_while_rendering(app, backend, posts, waiting = 3, then = bob_stops) + assert [r.status_code == 200 for r in responses] == [True, False, True] + [call] = backend.calls + assert sorted(call["prompts"]) == ["a fox", "an owl"] + assert sorted(record["account"] for record in saved) == ["alice", "carol"] + + +def test_the_leaders_stop_ends_its_own_account_and_other_accounts_render_alone(studio): + app, backend, saved = studio + posts = [ + ("/v1/images/generations", "alice", _openai("a fox")), + ("/v1/images/generations", "alice", _openai("a second fox")), + ("/v1/images/generations", "bob", _openai("a cat")), + ] + # Alice's Stop lands on the shared call while it renders. + backend.during_batch = lambda: backend.cancel_generate(expected_account = "alice") + responses = _post_while_rendering(app, backend, posts, waiting = 3) + assert [r.status_code == 200 for r in responses] == [False, False, True] + assert len(_batched_calls(backend)) == 1 + [alone] = [call for call in backend.calls if call["prompts"] is None] + assert alone["prompt"] == "a cat" and alone["account"] == "bob" + assert [record["account"] for record in saved] == ["bob"] + + +def test_a_stop_from_another_account_does_not_reach_a_render_it_does_not_ride_in(): + """The real engine: Stop from bob signals only bob's riders, never alice's running generation.""" + from core.inference.diffusion import DiffusionBackend + + engine = DiffusionBackend() + alice_render, bob_ride, carol_ride = threading.Event(), threading.Event(), threading.Event() + + def as_account(name, func): + token = bind_account(AccountContext(name, name, ROLE_OWNER)) + try: + return func() + finally: + reset_account(token) + + with contextlib.ExitStack() as stack: + as_account("alice", lambda: stack.enter_context(engine._generation_slot(alice_render))) + as_account("bob", lambda: stack.enter_context(engine.generation_rider(bob_ride))) + as_account("carol", lambda: stack.enter_context(engine.generation_rider(carol_ride))) + assert engine.cancel_generate(expected_account = "bob") is True + assert bob_ride.is_set() and not alice_render.is_set() and not carol_ride.is_set() + assert engine.cancel_generate(expected_account = "dave") is False + assert engine.cancel_generate(expected_account = "alice") is True + assert alice_render.is_set() and not carol_ride.is_set() + assert engine._generate_riders == {} + + +def _png_b64() -> str: + import base64 + import io + + from PIL import Image + + buffer = io.BytesIO() + Image.new("RGB", (8, 8), "white").save(buffer, format = "PNG") + return base64.b64encode(buffer.getvalue()).decode() + + +def _create(prompt: str, **extra) -> dict: + return {"prompt": prompt, "width": 256, "height": 256, "steps": 4, "guidance": 0.0, **extra} + + +def test_images_generate_plain_txt2img_from_two_accounts_shares_one_call(studio): + app, backend, saved = studio + posts = [ + ("/api/inference/images/generate", "alice", _create("a fox", batch_size = 2)), + ("/api/inference/images/generate", "bob", _create("a secret cat")), + ] + responses = _post_while_rendering(app, backend, posts, waiting = 2) + assert [r.status_code for r in responses] == [200, 200], [r.text for r in responses] + [call] = backend.calls + assert sorted(call["prompts"]) == ["a fox", "a fox", "a secret cat"] + assert call["kwargs"]["init_image"] is None + alice, bob = (r.json()["images"] for r in responses) + assert [image["prompt"] for image in alice] == ["a fox", "a fox"] + assert [image["prompt"] for image in bob] == ["a secret cat"] + by_account = {} + for record in saved: + by_account.setdefault(record["account"], []).append(record["image"]) + assert all(image.startswith("a fox#") for image in by_account["alice"]) + assert [image.split("#")[0] for image in by_account["bob"]] == ["a secret cat"] + # The batch seeds derive like a lone request's: base, base + 1. + assert alice[1]["seed"] == alice[0]["seed"] + 1 and alice[1]["batch_seed"] == alice[0]["seed"] + + +def test_images_generate_with_an_init_image_never_joins_a_batch(studio): + app, backend, _saved = studio + + async def run(): + transport = httpx.ASGITransport(app = app) + async with httpx.AsyncClient(transport = transport, base_url = "http://studio") as client: + backend.rendering = True + first = asyncio.ensure_future( + client.post( + "/api/inference/images/generate", + json = _create("a fox"), + headers = {"x-test-account": "alice"}, + ) + ) + await _until(lambda: _waiting() == 1) + edits = [ + asyncio.ensure_future( + client.post( + "/api/inference/images/generate", + json = _create("a cat", **extra), + headers = {"x-test-account": "bob"}, + ) + ) + for extra in ( + {"init_image": _png_b64(), "strength": 0.5}, + {"variation_seed": 7, "variation_strength": 0.3}, + {"seeds": [1, 2]}, + ) + ] + await asyncio.sleep(0.3) + assert _waiting() == 1 + backend.rendering = False + return await asyncio.gather(first, *edits) + + responses = asyncio.run(run()) + assert all(r.status_code == 200 for r in responses), [ + (r.status_code, r.text[:300]) for r in responses if r.status_code != 200 + ] + # Four calls, none batched: the plain Create rendered alone too, as nothing could join it. + assert len(backend.calls) == 4 + assert _batched_calls(backend) == [] + assert sorted(call["prompt"] for call in backend.calls) == ["a cat", "a cat", "a cat", "a fox"] + + +def test_a_lone_images_generate_request_renders_at_once_without_a_batch(studio): + app, backend, _saved = studio + + async def run(): + transport = httpx.ASGITransport(app = app) + async with httpx.AsyncClient(transport = transport, base_url = "http://studio") as client: + return await client.post( + "/api/inference/images/generate", + json = _create("a fox"), + headers = {"x-test-account": "alice"}, + ) + + response = asyncio.run(run()) + assert response.status_code == 200, response.text + [call] = backend.calls + assert call["prompts"] is None and call["prompt"] == "a fox" + + +@pytest.mark.parametrize("path", ["/v1/images/generations", "/api/inference/images/generate"]) +def test_seeded_requests_join_a_batch_only_when_opted_in(studio, monkeypatch, path): + app, backend, saved = studio + body = _openai if path.startswith("/v1") else _create + + async def run(): + transport = httpx.ASGITransport(app = app) + async with httpx.AsyncClient(transport = transport, base_url = "http://studio") as client: + backend.rendering = True + sent = [] + for account, prompt, seed in (("alice", "a fox", 11), ("bob", "a cat", 22)): + sent.append( + asyncio.ensure_future( + client.post( + path, + json = body( + prompt, + seed = seed, + **({"n": 2} if path.startswith("/v1") else {"batch_size": 2}), + ), + headers = {"x-test-account": account}, + ) + ) + ) + await asyncio.sleep(0.2) + backend.rendering = False + return await asyncio.gather(*sent) + + monkeypatch.delenv("UNSLOTH_STUDIO_IMAGE_BATCH_SEEDED", raising = False) + assert all(r.status_code == 200 for r in asyncio.run(run())) + assert _batched_calls(backend) == [] + assert sorted(call["seed"] for call in backend.calls) == [11, 22] + + backend.calls.clear() + saved.clear() + monkeypatch.setenv("UNSLOTH_STUDIO_IMAGE_BATCH_SEEDED", "1") + assert all(r.status_code == 200 for r in asyncio.run(run())) + [call] = backend.calls + # Each member keeps the seeds a lone request would use: base, base + 1. + assert call["seeds"] == [11, 12, 22, 23] + assert call["prompts"] == ["a fox", "a fox", "a cat", "a cat"] + images = sorted((record["account"], record["seed"], record["image"]) for record in saved) + assert images == [ + ("alice", 11, "a fox#11"), + ("alice", 12, "a fox#12"), + ("bob", 22, "a cat#22"), + ("bob", 23, "a cat#23"), + ] + + +def _queued(engine) -> int: + with engine._generation_cancel_lock: + return len(engine._queued_generate_cancels) + + +def _wait_for(predicate, timeout = 5.0) -> None: + import time + deadline = time.monotonic() + timeout + while not predicate(): + if time.monotonic() > deadline: + raise AssertionError("condition never held") + time.sleep(0.005) + + +def test_the_generation_slot_serves_waiters_in_arrival_order(): + from core.inference.diffusion import DiffusionBackend + + engine = DiffusionBackend() + served: list[int] = [] + threads = [] + with engine._generation_slot(threading.Event()): + for index in range(8): + + def run(index = index): + with engine._generation_slot(threading.Event()): + served.append(index) + + thread = threading.Thread(target = run, daemon = True) + thread.start() + threads.append(thread) + _wait_for(lambda: _queued(engine) == index + 1) + # Each waiter has polled the lock a few times before the next one arrives. + threading.Event().wait(0.25) + for thread in threads: + thread.join(timeout = 10) + assert served == list(range(8)) + + +def test_a_cancelled_waiter_leaves_the_queue_and_the_next_one_is_served(): + from core.inference.diffusion import DiffusionBackend + from core.inference.diffusion_families import DIFFUSION_CANCELLED_MSG + + engine = DiffusionBackend() + first_cancel = threading.Event() + outcome: dict[str, object] = {} + + def first(): + try: + with engine._generation_slot(first_cancel): + outcome["first"] = "served" + except RuntimeError as exc: + outcome["first"] = str(exc) + + def second(): + with engine._generation_slot(threading.Event()): + outcome["second"] = "served" + + with engine._generation_slot(threading.Event()): + a = threading.Thread(target = first, daemon = True) + a.start() + _wait_for(lambda: _queued(engine) == 1) + b = threading.Thread(target = second, daemon = True) + b.start() + _wait_for(lambda: _queued(engine) == 2) + first_cancel.set() + a.join(timeout = 2) + assert outcome == {"first": DIFFUSION_CANCELLED_MSG} + assert "second" not in outcome + b.join(timeout = 5) + assert outcome["second"] == "served" + assert not engine._generate_lock.locked() diff --git a/studio/backend/tests/test_image_concurrency_review.py b/studio/backend/tests/test_image_concurrency_review.py new file mode 100644 index 000000000000..b1abc69baf3d --- /dev/null +++ b/studio/backend/tests/test_image_concurrency_review.py @@ -0,0 +1,929 @@ +# SPDX-License-Identifier: AGPL-3.0-only +# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0 + +"""Coalescing review fixes: per-account resources, Stop, previews, compiled shapes, partial failures, FIFO +follow-ups, recipes and per-family prompt grouping.""" + +from __future__ import annotations + +import asyncio +import sys +import threading +import types +from pathlib import Path + +import pytest + +from core.inference import image_request_batching as batching + +sys.path.insert(0, str(Path(__file__).resolve().parent)) +from test_image_concurrency import ( # noqa: E402,F401 (fixture) + _Backend, + _batched_calls, + _create, + _openai, + _post_while_rendering, + _until, + _waiting, + studio, +) +from utils.account_context import current_account_id # noqa: E402 + + +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()) + backend.coalesce_plan = types.MethodType(DiffusionBackend.coalesce_plan, backend) + + +def test_requests_with_loras_batch_only_with_their_own_account(studio): + app, backend, _saved = studio + lora = {"loras": [{"id": "style-lora", "weight": 0.8}]} + posts = [ + ("/v1/images/generations", "alice", _openai("a fox", **lora)), + ("/v1/images/generations", "bob", _openai("a cat", **lora)), + ("/v1/images/generations", "alice", _openai("an owl", **lora)), + ] + responses = _post_while_rendering(app, backend, posts, waiting = 3) + assert all(r.status_code == 200 for r in responses), [r.text for r in responses] + [call] = _batched_calls(backend) + assert call["account"] == "alice" and sorted(call["prompts"]) == ["a fox", "an owl"] + [alone] = [c for c in backend.calls if c["prompts"] is None] + assert alone["account"] == "bob" + + +def test_an_account_with_embeddings_never_shares_a_call_with_another_account(studio, monkeypatch): + import core.inference.diffusion_embeddings as embeddings + + app, backend, _saved = studio + _real_plan(backend, types.SimpleNamespace(name = "sdxl", textual_inversion = "sdxl")) + owned = {"bob": ["secret-style"]} + monkeypatch.setattr( + embeddings, "list_embeddings", lambda kind = None: owned.get(current_account_id(), []) + ) + posts = [ + ("/v1/images/generations", "alice", _openai("a fox")), + ("/v1/images/generations", "bob", _openai("a cat in secret-style")), + ("/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 sorted(call["prompts"]) == ["a fox", "an owl"] + assert [c["account"] for c in backend.calls if c["prompts"] is None] == ["bob"] + + +def test_the_engine_plan_marks_loras_and_owned_embeddings_private(monkeypatch): + import core.inference.diffusion_embeddings as embeddings + from core.inference.diffusion import DiffusionBackend + + 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) + 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(), + ) + 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())))} + + +class _ClipWords: + """A CLIP-shaped tokenizer: one id per word, a comma id, bos / eos.""" + + bos_token_id, eos_token_id, pad_token_id = 0, 1, None + + def get_vocab(self): + return {",": 2} + + def __call__(self, text, **_kwargs): + return { + "input_ids": [ + 2 if word == "," else 10 + len(word) for word in text.replace(",", " , ").split() + ] + } + + +def _clip_pipe(**extra): + return types.SimpleNamespace(tokenizer = _ClipWords(), text_encoder = object(), **extra) + + +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 = _clip_pipe() + 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" + ] + + +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() + _wait_until(lambda: len(engine._queued_generate_cancels) >= 2) + 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} + + +def test_a_batch_shared_across_accounts_shows_no_live_preview(studio): + app, backend, _saved = studio + posts = [ + ("/api/inference/images/generate", "alice", _create("a fox", live_preview = True)), + ("/api/inference/images/generate", "bob", _create("a cat", live_preview = True)), + ] + 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 False + + backend.calls.clear() + posts = [ + ("/api/inference/images/generate", "alice", _create("a fox", live_preview = True)), + ("/api/inference/images/generate", "alice", _create("a cat", live_preview = True)), + ] + 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 + # CUDA graphs serve serially, compiled sizes or not. + engine._state.cuda_graphs = (object(),) + assert engine.coalesce_batch_sizes(512, 512) == frozenset() + + +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] + + +def _queue_members(specs, run_batch, **extra): + """Starts one request per (prompt, n) behind a running render, frees it, returns each result.""" + rendering = {"on": True} + + async def run(): + tasks = [ + asyncio.ensure_future( + batching.generate( + "key", + prompt, + n, + None, + busy = lambda: rendering["on"], + run_batch = run_batch, + **extra, + ) + ) + for prompt, n in specs + ] + await _until(lambda: _waiting() == len(specs)) + rendering["on"] = False + return await asyncio.gather(*tasks) + + return asyncio.run(run()) + + +def _echo(prompts, seeds): + return {"images": list(prompts), "seeds": list(seeds), "seed": seeds[0]} + + +def test_a_failed_call_keeps_the_images_that_finished(): + calls = [] + + class Failed(RuntimeError): + pass + + async def run_batch( + prompts, + seeds, + owners = None, + ): + calls.append(list(prompts)) + exc = Failed("CUDA error: device lost") + exc.finished = _echo(prompts[:2], seeds[:2]) + raise exc + + results = _queue_members( + [("a", 1), ("b", 1), ("c", 1)], + run_batch, + splittable = lambda exc: False, + salvage = lambda exc: getattr(exc, "finished", None), + ) + assert calls == [["a", "b", "c"]] + assert [r["images"] if r else None for r in results] == [["a"], ["b"], None] + + +def test_one_members_value_error_never_fails_the_others(): + calls = [] + + async def run_batch( + prompts, + seeds, + owners = None, + ): + calls.append(list(prompts)) + if "bad" in prompts: + raise ValueError("bad is not a valid prompt for this model") + return _echo(prompts, seeds) + + results = _queue_members( + [("a", 1), ("bad", 1), ("c", 1), ("d", 1)], + run_batch, + splittable = lambda exc: isinstance(exc, ValueError), + ) + assert calls == [["a", "bad", "c", "d"], ["a", "bad"], ["c", "d"]] + # c and d keep a shared call; a and the bad request render alone, so only the bad one sees its error. + assert [r["images"] if r else None for r in results] == [None, None, ["c"], ["d"]] + + +def test_a_blank_prompt_renders_alone_and_the_rest_still_batch(): + calls = [] + + async def run_batch( + prompts, + seeds, + owners = None, + ): + calls.append(list(prompts)) + return _echo(prompts, seeds) + + results = _queue_members([("a", 1), (" ", 1), ("c", 1)], run_batch) + assert calls == [["a", "c"]] + assert [r["images"] if r else None for r in results] == [["a"], None, ["c"]] + + +def test_the_route_keeps_finished_images_from_a_failed_call(studio): + app, backend, saved = studio + real_generate = backend.generate + + def generate(**kwargs): + if kwargs.get("prompts") is None: + return real_generate(**kwargs) + done = real_generate( + **{**kwargs, "prompts": kwargs["prompts"][:2], "seeds": kwargs["seeds"][:2]} + ) + exc = RuntimeError("CUDA error: an illegal memory access was encountered") + exc._unsloth_finished_images = {"images": done["images"], "seeds": done["seeds"]} + raise exc + + backend.generate = generate + 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) + # One partial batched call, then only the unfinished member renders again. + assert [c["prompts"] for c in backend.calls] == [["a fox", "a cat"], None] + assert backend.calls[1]["prompt"] == "an owl" + assert sorted(record["account"] for record in saved) == ["alice", "bob", "carol"] + + +def _wait_until(predicate, polls = 1000): + """Poll until predicate holds, failing after a fixed number of 5 ms waits (no clock comparison).""" + for _ in range(polls): + if predicate(): + return + threading.Event().wait(0.005) + assert predicate(), "condition never held" + + +def _hold_slot(engine): + """A render holding the slot in a thread until the returned Event is set.""" + held, release = threading.Event(), threading.Event() + + def run(): + with engine._generation_slot(threading.Event()): + held.set() + release.wait(10) + + threading.Thread(target = run, daemon = True).start() + held.wait(5) + return release + + +def _queued_render( + engine, + served, + name, + context = None, +): + import contextlib + + def run(): + with context() if context is not None else contextlib.nullcontext(): + with engine._generation_slot(threading.Event()): + served.append(name) + + import contextvars + + # Like the image executor: the thread runs in a copy of the caller's context, reserved turn included. + thread = threading.Thread(target = contextvars.copy_context().run, args = (run,), daemon = True) + thread.start() + return thread + + +def test_a_batch_keeps_the_place_in_line_it_took_when_it_opened(): + from core.inference.diffusion import DiffusionBackend, reserved_slot_turn + + engine = DiffusionBackend() + served: list = [] + release = _hold_slot(engine) + turn = engine.reserve_slot_turn() # the batch opens behind the running render + later = _queued_render(engine, served, "arrived later") + _wait_until(lambda: len(engine._slot_turns) == 2) + assert not engine.slot_turn_ready(turn) + woken = [] + remove = engine.add_slot_listener(lambda: woken.append(1)) + release.set() + _wait_until(lambda: engine.slot_turn_ready(turn)) + assert woken, "the slot release woke the batch" + remove() + with reserved_slot_turn(turn): + batch = _queued_render(engine, served, "batch") + batch.join(5) + later.join(5) + assert served == ["batch", "arrived later"] + + +def test_follow_up_passes_go_before_requests_waiting_in_line(monkeypatch): + import core.inference.diffusion_engine_router as engine_router + from core.inference import diffusion_detailer + from core.inference.diffusion import DiffusionBackend, slot_follow_up + + engine = DiffusionBackend() + served: list = [] + release = _hold_slot(engine) + waiting = _queued_render(engine, served, "waiting") + _wait_until(lambda: len(engine._slot_turns) == 1) + follow_up = _queued_render(engine, served, "x/y cell 2", context = slot_follow_up) + _wait_until(lambda: len(engine._slot_turns) == 2) + release.set() + follow_up.join(5) + waiting.join(5) + assert served == ["x/y cell 2", "waiting"] + + # A Detailer crop takes the lock directly; it too goes before a waiting request. + served.clear() + monkeypatch.setattr(engine_router, "get_active_diffusion_engine", lambda: engine) + release = _hold_slot(engine) + waiting = _queued_render(engine, served, "waiting") + _wait_until(lambda: len(engine._slot_turns) == 1) + got = [] + + def detailer(): + lock = diffusion_detailer._take_generation_slot() + served.append("detailer crop") + lock.release() + engine._notify_slot_listeners() + got.append(lock) + + crop = threading.Thread(target = detailer, daemon = True) + crop.start() + _wait_until(lambda: len(engine._slot_turns) == 2) + release.set() + crop.join(5) + waiting.join(5) + assert served == ["detailer crop", "waiting"] + + +def test_a_waiting_batch_wakes_from_the_slot_instead_of_polling(): + calls = {"wait": 0} + rendering = {"on": True} + + async def wait(): + calls["wait"] += 1 + await asyncio.sleep(0.05) + rendering["on"] = False + + async def run_batch( + prompts, + seeds, + owners = None, + ): + return _echo(prompts, seeds) + + async def run(): + tasks = [ + asyncio.ensure_future( + batching.generate( + "key", p, 1, None, busy = lambda: rendering["on"], run_batch = run_batch, wait = wait + ) + ) + for p in ("a", "b") + ] + return await asyncio.gather(*tasks) + + results = asyncio.run(run()) + assert [r["images"] for r in results] == [["a"], ["b"]] + assert calls["wait"] == 1 + + +def test_recipes_record_the_shared_call_size_and_position(studio): + app, backend, saved = studio + posts = [ + ("/api/inference/images/generate", "alice", _create("a fox", batch_size = 2)), + ("/api/inference/images/generate", "bob", _create("a cat")), + ("/v1/images/generations", "carol", _openai("an owl")), + ] + responses = _post_while_rendering(app, backend, posts[:2], waiting = 2) + assert all(r.status_code == 200 for r in responses) + recipes = sorted((r["account"], r["coalesced_batch_size"], r["coalesced_index"]) for r in saved) + assert recipes == [("alice", 3, 0), ("alice", 3, 1), ("bob", 3, 2)] + assert [image["coalesced_batch_size"] for image in responses[1].json()["images"]] == [3] + + saved.clear() + responses = _post_while_rendering( + app, backend, [posts[2], ("/v1/images/generations", "dave", _openai("a hen"))], waiting = 2 + ) + assert sorted((r["account"], r["coalesced_index"]) for r in saved) == [ + ("carol", 0), + ("dave", 1), + ] + + +def test_a_lone_render_records_no_shared_call(): + import routes.inference as inference_routes + assert inference_routes._coalesced_recipe({"images": ["x"]}, 0) == {} + + +def test_a_coalesced_call_is_always_pinned_to_the_model_its_settings_were_read_for(studio): + from core.inference.diffusion_families import load_identity + + app, backend, _saved = studio + # Every field explicit and no adapters: the route itself pins no load for this request. + posts = [ + ("/api/inference/images/generate", "alice", _create("a fox", loras = [])), + ("/api/inference/images/generate", "bob", _create("a cat", loras = [])), + ] + assert all(r.status_code == 200 for r in _post_while_rendering(app, backend, posts, waiting = 2)) + [call] = _batched_calls(backend) + status = backend.status() + assert call["kwargs"]["expected_load"] == load_identity( + status["repo_id"], status["base_repo"], status["family"] + ) + + +def test_sdxl_groups_by_the_chunks_the_weighted_encode_actually_builds(): + from core.inference.diffusion import coalesce_prompt_key + + family = types.SimpleNamespace(name = "sdxl", textual_inversion = "sdxl") + pipe = _clip_pipe(tokenizer_2 = _ClipWords(), text_encoder_2 = object()) + # Same raw token count and both weighted, but BREAK closes a chunk: two conditioning chunks against one. + assert coalesce_prompt_key(family, pipe, "a BREAK cat") != coalesce_prompt_key( + family, pipe, "a (cat)" + ) + assert coalesce_prompt_key(family, pipe, "a (cat)") == coalesce_prompt_key( + family, pipe, "a (dog)" + ) + + +def test_a_random_subseed_variation_request_never_joins_a_batch(studio): + import httpx + + app, backend, _saved = studio + + async def run(): + transport = httpx.ASGITransport(app = app) + async with httpx.AsyncClient(transport = transport, base_url = "http://studio") as client: + backend.rendering = True + first = asyncio.ensure_future( + client.post( + "/api/inference/images/generate", + json = _create("a fox"), + headers = {"x-test-account": "alice"}, + ) + ) + await _until(lambda: _waiting() == 1) + variation = asyncio.ensure_future( + client.post( + "/api/inference/images/generate", + json = _create("a cat", batch_size = 2, variation_strength = 0.3), + headers = {"x-test-account": "bob"}, + ) + ) + await asyncio.sleep(0.3) + assert _waiting() == 1 + backend.rendering = False + return await asyncio.gather(first, variation) + + responses = asyncio.run(run()) + assert all(r.status_code == 200 for r in responses), [r.text[:200] for r in responses] + assert _batched_calls(backend) == [] + [variation_call] = [c for c in backend.calls if c["prompt"] == "a cat"] + assert variation_call["batch_size"] == 2 and variation_call["seeds"] is None + + +class _SlotBackend(_Backend): + """The fake engine over the real engine's slot line, so queued renders block in ``_generation_slot``.""" + + def __init__(self): + from core.inference.diffusion import DiffusionBackend + + super().__init__() + self.engine = DiffusionBackend() + for name in ( + "generation_holder", + "generation_waiter", + "generation_rider", + "reserve_slot_turn", + "release_slot_turn", + "slot_turn_ready", + "add_slot_listener", + "stop_waiting_work", + ): + setattr(self, name, getattr(self.engine, name)) + + def generate(self, **kwargs): + with self.engine._generation_slot(threading.Event()): + return super().generate(**kwargs) + + +def test_a_reserved_batch_runs_even_when_queued_requests_hold_every_generate_worker( + studio, monkeypatch +): + from concurrent.futures import ThreadPoolExecutor + + import httpx + + import core.inference.diffusion as diffusion_module + import core.inference.diffusion_engine_router as engine_router + import routes.inference as inference_routes + + app, _fake, saved = studio + backend = _SlotBackend() + monkeypatch.setattr(diffusion_module, "get_diffusion_backend", lambda: backend) + monkeypatch.setattr(engine_router, "get_active_diffusion_engine", lambda: backend) + pool = ThreadPoolExecutor(max_workers = 2, thread_name_prefix = "test-generate") + monkeypatch.setattr(inference_routes, "_IMAGE_GENERATE_EXECUTOR", pool) + engine = backend.engine + release = _hold_slot(engine) + + async def run(): + transport = httpx.ASGITransport(app = app) + async with httpx.AsyncClient(transport = transport, base_url = "http://studio") as client: + + def post(account, body): + return asyncio.ensure_future( + client.post( + "/v1/images/generations", json = body, headers = {"x-test-account": account} + ) + ) + + batch = [post("alice", _openai("a fox"))] + await _until(lambda: _waiting() == 1 and len(engine._slot_turns) == 1) + batch.append(post("bob", _openai("a cat"))) + await _until(lambda: _waiting() == 2) + # Seeded requests never join: they take both generate workers and queue behind the batch's turn. + seeded = [ + post("carol", _openai("an owl", seed = 5)), + post("dave", _openai("a hen", seed = 6)), + ] + await _until(lambda: len(engine._slot_turns) == 3) + release.set() + return await asyncio.wait_for(asyncio.gather(*batch, *seeded), timeout = 15) + + try: + responses = asyncio.run(run()) + finally: + release.set() + # Unstick any waiter a failing run left behind the reserved turn. + with engine._slot_turn_changed: + engine._slot_turns.clear() + engine._slot_turn_changed.notify_all() + pool.shutdown(wait = False, cancel_futures = True) + assert all(r.status_code == 200 for r in responses) + calls = [c["prompts"] or c["prompt"] for c in backend.calls] + assert calls[0] == ["a fox", "a cat"] + assert sorted(calls[1:]) == ["a hen", "an owl"] + assert len(saved) == 4 + + +def test_an_unclaimed_reservation_cannot_stall_waiters_that_hold_every_worker(): + """The recheck's schedule: one pool runs everything, and both of its workers wait behind a reservation whose + owner then has no worker. The waiters step past the idle reservation and the queue drains.""" + from concurrent.futures import ThreadPoolExecutor + + from core.inference.diffusion import DiffusionBackend, reserved_slot_turn + + engine = DiffusionBackend() + started, release = threading.Event(), threading.Event() + entered = [] + + def active(): + with engine._generation_slot(threading.Event()): + started.set() + release.wait(5) + + def later(name): + with engine._generation_slot(threading.Event()): + entered.append(name) + + def earlier(turn): + with reserved_slot_turn(turn), engine._generation_slot(threading.Event()): + entered.append("reserved") + + with ThreadPoolExecutor(max_workers = 2) as pool: + holder = pool.submit(active) + assert started.wait(5) + turn = engine.reserve_slot_turn() + first = pool.submit(later, "later 1") + _wait_until(lambda: len(engine._slot_turns) == 2) + release.set() + holder.result(timeout = 5) + second = pool.submit(later, "later 2") + _wait_until(lambda: len(engine._slot_turns) == 3) + reserved = pool.submit(earlier, turn) + for future in (first, second, reserved): + future.result(timeout = 10) + assert sorted(entered) == ["later 1", "later 2", "reserved"] + assert not engine._slot_turns and not engine._unclaimed_turns + + +def test_sdxl_keys_break_prompts_apart_in_both_tokenizers(): + from core.inference.diffusion import coalesce_prompt_key + + family = types.SimpleNamespace(name = "sdxl", textual_inversion = "sdxl") + pipe = _clip_pipe(tokenizer_2 = _ClipWords(), text_encoder_2 = object()) + assert coalesce_prompt_key(family, pipe, "(red) BREAK blue") != coalesce_prompt_key( + family, pipe, "(red) blue" + ) + # A pipe with a tokenizer but no encoder to count for never batches. + tokenizer_only = types.SimpleNamespace(tokenizer = _ClipWords()) + assert coalesce_prompt_key(family, tokenizer_only, "(red) blue") is None + + +def test_failure_recovery_renders_only_admitted_sizes(): + attempts = [] + + async def run_batch( + prompts, + seeds, + owners = None, + ): + attempts.append(len(seeds)) + if len(seeds) == 4: + raise ValueError("controlled batch failure") + return _echo(prompts, seeds) + + results = _queue_members( + [("0", 1), ("1", 1), ("2", 1), ("3", 1)], + run_batch, + fits = lambda size: size == 4, + splittable = lambda exc: isinstance(exc, ValueError), + ) + # The halves (size 2) are not admitted: every member falls back to rendering alone. + assert attempts == [4] + assert results == [None, None, None, None] + + +def test_status_tells_how_concurrent_requests_are_served(monkeypatch): + import core.inference.diffusion as diffusion_module + from core.inference.diffusion import DiffusionBackend + + engine = DiffusionBackend() + assert engine.request_batching() is None + engine._state = types.SimpleNamespace( + speed_optims = (), speed_mode = "off", pipe = None, cuda_graphs = (), compile_cache_ctx = None + ) + assert engine.request_batching()["mode"] == "any" + assert engine.coalesce_batch_sizes(512, 512) is None + engine._state.speed_optims = ("compiled",) + monkeypatch.setattr(diffusion_module, "compiled_shapes_are_static", lambda pipe, mode: True) + assert engine.request_batching()["mode"] == "compiled_sizes" + engine._state.cuda_graphs = (object(),) + policy = engine.request_batching() + assert policy["mode"] == "serial" and "CUDA graphs" in policy["reason"] + assert engine.coalesce_batch_sizes(512, 512) == frozenset() + + +def test_the_status_model_carries_request_batching(): + from models.inference import DiffusionStatusResponse + status = DiffusionStatusResponse(request_batching = {"mode": "serial", "reason": "CUDA graphs"}) + assert status.model_dump()["request_batching"] == {"mode": "serial", "reason": "CUDA graphs"} diff --git a/studio/backend/tests/test_openai_images_batching.py b/studio/backend/tests/test_openai_images_batching.py index f6603d55a154..312d69e0c3ca 100644 --- a/studio/backend/tests/test_openai_images_batching.py +++ b/studio/backend/tests/test_openai_images_batching.py @@ -424,12 +424,16 @@ def test_request_seeds_derive_like_a_lone_request(): assert drawn[1] == (drawn[0] + 1) & SEED_MASK -def test_a_batch_stops_collecting_at_the_cap_and_the_rest_render_alone(monkeypatch): +def test_a_full_batch_stops_collecting_and_the_next_request_opens_another(monkeypatch): monkeypatch.setenv("UNSLOTH_STUDIO_IMAGE_BATCH_MAX", "4") rendering = {"on": True} batches: list[list[str]] = [] - async def run_batch(prompts, seeds): + async def run_batch( + prompts, + seeds, + owners = None, + ): batches.append(prompts) return {"images": list(prompts), "seeds": list(seeds), "seed": seeds[0]} @@ -441,20 +445,19 @@ def request(prompt, n): ) ) - lead, joined, overflow, too_big = ( - request("a", 2), - request("b", 2), - request("c", 1), - request("d", 4), - ) - await _until(lambda: overflow.done() and too_big.done()) - assert overflow.result() is None and too_big.result() is None + lead, joined = request("a", 2), request("b", 2) + await _until(lambda: "key" not in batching._OPEN) + second, joined_second = request("c", 3), request("d", 1) + too_big = request("e", 4) + await _until(lambda: too_big.done()) + assert too_big.result() is None rendering["on"] = False - return await lead, await joined + return await lead, await joined, await second, await joined_second - lead, joined = asyncio.run(run()) - assert batches == [["a", "a", "b", "b"]] + lead, joined, second, joined_second = asyncio.run(run()) + assert sorted(batches) == [["a", "a", "b", "b"], ["c", "c", "c", "d"]] assert lead["images"] == ["a", "a"] and joined["images"] == ["b", "b"] + assert second["images"] == ["c", "c", "c"] and joined_second["images"] == ["d"] def test_a_cap_of_one_turns_batching_off(monkeypatch):