diff --git a/studio/backend/core/inference/diffusion.py b/studio/backend/core/inference/diffusion.py index 8d433cf8dbf4..2ff2c4540c97 100644 --- a/studio/backend/core/inference/diffusion.py +++ b/studio/backend/core/inference/diffusion.py @@ -398,6 +398,7 @@ from . import diffusion_gguf_compile as gguf_compile from . import diffusion_bg_compile as bg_compile from . import diffusion_cuda_graph as cuda_graph +from . import diffusion_batch_trace as batch_trace from . import diffusion_int8_cutlass_defer as int8_defer from .diffusion_block_graph import compile_below_hooks_enabled, compile_pipe_below_offload_hooks from . import diffusion_render_thread as render_thread @@ -1188,6 +1189,19 @@ def _record_load_lora_specs(pipe: Any, loras: Any) -> None: pass +def _race_adapters_active(pipe: Any) -> bool: + """Whether the load carries adapters with a non-zero weight: applied now, baked in, or requested at load.""" + if pipe is None: + return False + if any( + float(entry[2]) != 0 + for entry in getattr(pipe, "_unsloth_loras", ()) or () + if len(entry) > 2 + ): + return True + return any(float(spec.get("weight", 0) or 0) != 0 for spec in _load_lora_specs(pipe)) + + def _load_lora_specs(pipe: Any) -> list: baked = _baked_lora_specs(pipe) if baked: @@ -1861,7 +1875,12 @@ def _generation_chunks( per modular call, so each image is its own chunk: every one then gets its own encode, denoise and decode phase, and the text-encoder release that comes with entering denoise (one chunk of several images would release it once, and the next image's encode would bring it back for the rest of the chunk).""" - if layer_count or is_flux3_family(family) or is_anima_family(family): + from .diffusion_batch_adapters import BATCHED_FORWARD_ATTR + + # A family that says its call fuses the rows (``batched_forward``) chunks like any other. + if getattr(family, BATCHED_FORWARD_ATTR, None) is not True and ( + layer_count or is_flux3_family(family) or is_anima_family(family) + ): return [[job] for job in jobs] return chunk_jobs(jobs, batch_size) @@ -5017,11 +5036,12 @@ def _pipe_tokenizers(pipe: Any) -> list: def _key_tokenizes(family: Any, pipe: Any) -> bool: - from .diffusion_text_length import FLUX_T5_FAMILIES - return ( - getattr(family, "name", None) in FLUX_T5_FAMILIES - or getattr(family, "textual_inversion", None) is not None - ) + from .diffusion_batch_adapters import DEFAULT_ADAPTER, adapter_for, key_tokenizes + + adapter = adapter_for(family, pipe) + if adapter is not None and adapter is not DEFAULT_ADAPTER: + return bool(getattr(adapter, "tokenizes", True)) + return key_tokenizes(family) def prime_coalesce_tokenizers(family: Any, pipe: Any) -> None: @@ -5097,13 +5117,14 @@ def _clip_chunk_counts(pipe: Any, prompt: str) -> Optional[tuple]: def coalesce_prompt_key(family: Any, pipe: Any, prompt: str) -> Optional[tuple]: """What a prompt must share with batch neighbours to render as alone; None = never batch it. - MiniMax-H3 / Qwen-Image-2.1 gain nothing batched; MOSS batches only where its layer-major win was measured; - FLUX.1 pads T5 per call; SD / SDXL chunk per call.""" - from .diffusion_families import MINIMAX_H3_IMAGE_FAMILY_NAME, MOSS_IMAGE_FAMILY_NAME - from .diffusion_qwenimage21 import _CLASS as QWENIMAGE21_CLASS + The family's batch adapter decides (diffusion_batch_adapters): a family whose call does not fuse the rows + (``batched_forward`` False: MiniMax-H3, Qwen-Image-2.1, FLUX.3, Anima, layered by default) never batches; + MOSS batches only where its layer-major win was measured (diffusion_moss_image.coalesce_key); FLUX.1 pads T5 per + call; SD / SDXL chunk per call.""" + from .diffusion_batch_adapters import adapter_for + from .diffusion_families import MOSS_IMAGE_FAMILY_NAME - name = getattr(family, "name", None) - if name == MOSS_IMAGE_FAMILY_NAME: + if getattr(family, "name", None) == MOSS_IMAGE_FAMILY_NAME: if getattr(pipe, "transformer", None) is None: return None try: # the MOSS module needs diffusers at import; a missing or broken one renders alone @@ -5111,29 +5132,20 @@ def coalesce_prompt_key(family: Any, pipe: Any, prompt: str) -> Optional[tuple]: return coalesce_key(pipe) except Exception: # noqa: BLE001 - an unreadable load renders alone return None - if name == MINIMAX_H3_IMAGE_FAMILY_NAME: - return None - if type(getattr(pipe, "transformer", None)).__name__ == QWENIMAGE21_CLASS: + adapter = adapter_for(family, pipe) + if adapter is None: return None pipe = _KeyPipe(pipe) if pipe is not None else None try: with _KEY_TOKENIZE_LOCK: - return _coalesce_prompt_key(family, name, pipe, prompt) + return adapter.prepare(family, pipe, prompt) except Exception: # noqa: BLE001 - a prompt that cannot be measured renders alone return None def _coalesce_prompt_key(family: Any, name: Any, pipe: Any, prompt: str) -> Optional[tuple]: - from .diffusion_prompt_weighting import has_prompt_syntax - from .diffusion_text_length import FLUX_T5_FAMILIES, flux_t5_sequence_length - - 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) - return () + from .diffusion_batch_adapters import DEFAULT_ADAPTER + return DEFAULT_ADAPTER.prepare(family, pipe, prompt) def _per_call_activation_scale(state: Any) -> Optional[str]: @@ -5159,6 +5171,27 @@ def _per_call_activation_scale(state: Any) -> Optional[str]: return None +def _chunk_rows(kwargs: dict) -> int: + """Images one pipe call renders: one generator per image, else prompts x images per prompt.""" + generator = kwargs.get("generator") + if isinstance(generator, (list, tuple)) and generator: + return len(generator) + prompt = kwargs.get("prompt") + count = len(prompt) if isinstance(prompt, (list, tuple)) else 1 + try: + return count * max(1, int(kwargs.get("num_images_per_prompt") or 1)) + except (TypeError, ValueError): + return count + + +def _batch_trace_snapshot() -> Optional[dict]: + try: + from .diffusion_batch_trace import snapshot + return snapshot() + except Exception: # noqa: BLE001 - status never fails on a counter + return None + + def _denoiser_streams_from_host(state: Any) -> bool: """Denoiser weights stream from host each render (any offload with an unpinned group; unreadable = streamed).""" policy = getattr(state, "offload_policy", OFFLOAD_NONE) or OFFLOAD_NONE @@ -5171,6 +5204,90 @@ def _denoiser_streams_from_host(state: Any) -> bool: return denoiser_offload(getattr(state, "pipe", None), policy) != DENOISER_RESIDENT +def _default_request_batching(state: Any) -> dict[str, Any]: + """Today's rules: the conservative answer for any load, card and shape no race has measured.""" + scaled = _per_call_activation_scale(state) + if scaled is not None: + # Per-tensor activation scale from the call's amax: one prompt would set every member's quantization. + return { + "mode": "serial", + "reason": f"per-tensor dynamic activation scales ({scaled}): one request would set every batch " + "member's quantization, so concurrent requests render one at a time", + } + if not _denoiser_streams_from_host(state): + # Measured (A100 / RTX PRO 6000, batch 4): resident 0.81x-1.19x of serial, streamed 1.47x-3.35x. + return { + "mode": "serial", + "reason": "resident weights: a shared call is no faster than one request at a time, so " + "concurrent requests render one at a time", + "measurable": True, + } + if getattr(state, "cuda_graphs", ()): + # A new batch size would record graphs inside a user's slot; batching measured no faster. Only an idle race + # records batch-size graphs (diffusion_cuda_graph.batch_rows). + return { + "mode": "serial", + "reason": "CUDA graphs replay one batch size; concurrent requests render one at a time", + "measurable": True, + } + 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 _step_cache_couples_rows(state: Any, steps: Optional[int]) -> bool: + """Whether FBCache can run this call: it decides skips from one batch-wide residual mean, so one request's image + would decide whether another's blocks run. A static schedule decides by step only and is row-independent. + Unknown steps on an AUTO cache count as engaged.""" + from .diffusion_cache import TC_FBCACHE, auto_step_cache_mode + + if getattr(state, "cache_auto", False): + if steps is None: + return True + try: + return auto_step_cache_mode(int(steps)) == TC_FBCACHE + except (TypeError, ValueError): + return True + return getattr(state, "transformer_cache", None) == TC_FBCACHE + + +def _measured_sizes( + state: Any, + width: Any, + height: Any, + guidance: Optional[float], + steps: Optional[int] = None, + layout: Any = None, +) -> dict[int, dict]: + from . import diffusion_batch_race + from .image_request_batching import batch_max + + if _race_adapters_active(getattr(state, "pipe", None)): + # Verdicts are raced adapter-free and not keyed by adapter set: an adapted load keeps today's rules. + return {} + try: + found = diffusion_batch_race.lookup( + state, width, height, guidance, range(2, batch_max() + 1), steps = steps + ) + from .diffusion_batch_quality import gate + + # A win serves only where an offline G2c verdict passes for this family, card and path. + return { + k: gate(diffusion_batch_race.effective_verdict(v, k, state, layout = layout), state) + for k, v in found.items() + } + except Exception: # noqa: BLE001 - no verdict: today's rules + return {} + + def _note_small_host_hosted_int8(pipe: Any, reason: str, *, picked: bool) -> None: from .diffusion_small_host import mark @@ -17725,7 +17842,8 @@ def _render_chunk( ): # img2img / inpaint / controlnet pipes share the denoiser: predict from this call's scheduler bind_adaln_pipe(pipe) - return pipe(**chunk_kwargs).images + with batch_trace.denoiser_calls(pipe, _chunk_rows(chunk_kwargs)): + return pipe(**chunk_kwargs).images # Re-check an AUTO cache decision against the ACTUAL step count; explicit choices never toggle. if state.cache_auto: @@ -18290,54 +18408,207 @@ def coalesce_plan(self, prompt: str, has_loras: bool) -> Optional[tuple[tuple, b return prompt_key, private def request_batching(self) -> Optional[dict[str, str]]: - """``mode`` (``any`` / ``compiled_sizes`` / ``serial``) and reason for status; None when nothing is loaded.""" + """``mode`` (``any`` / ``compiled_sizes`` / ``measured`` / ``serial``) and reason for status; None when nothing + is loaded. ``measured``: today's rule is serial, but an idle race measured a batch size that wins on this load + (diffusion_batch_race), so requests share a call at the winning sizes only.""" state = self._state if state is None: return None - scaled = _per_call_activation_scale(state) - if scaled is not None: - # Per-tensor activation scale from the call's amax: one prompt would set every member's quantization. - return { - "mode": "serial", - "reason": f"per-tensor dynamic activation scales ({scaled}): one request would set every batch " - "member's quantization, so concurrent requests render one at a time", - } - if not _denoiser_streams_from_host(state): - # Measured (A100 / RTX PRO 6000, batch 4): resident 0.81x-1.19x of serial, streamed 1.47x-3.35x. + from .diffusion_batch_adapters import batched_forward + + if not batched_forward(getattr(state, "family", None), getattr(state, "pipe", None)): return { "mode": "serial", - "reason": "resident weights: a shared call is no faster than one request at a time, so " - "concurrent requests render one at a time", + "reason": "this family's pipeline renders one image per forward, so concurrent requests render one " + "at a time", } - if getattr(state, "cuda_graphs", ()): - # A new batch size recaptures graphs inside the slot and an OOM split drops them; batching measured no faster. + if not getattr(state, "cache_auto", False) and _step_cache_couples_rows(state, None): return { "mode": "serial", - "reason": "CUDA graphs replay one batch size; concurrent requests render one at a time", + "reason": "the step cache (FBCache) decides skips from the whole call, so one request would decide " + "another's; 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", - } + policy = _default_request_batching(state) + if policy["mode"] == "serial" and policy.get("measurable"): + from . import diffusion_batch_race + from .diffusion_batch_quality import any_quality_ok + if diffusion_batch_race.any_promoted(state) and any_quality_ok(state): + policy = { + "mode": "measured", + "reason": "an idle race on this card measured a faster shared call: concurrent requests share " + "one call at the measured batch sizes and shapes only", + } + policy.pop("measurable", None) + return policy - def coalesce_batch_sizes(self, width: int, height: int) -> Optional[frozenset]: - """Allowed batch sizes at this shape: None = any, empty = none; static compile offers only already-compiled sizes.""" + def coalesce_batch_sizes( + self, + width: int, + height: int, + guidance: Optional[float] = None, + steps: Optional[int] = None, + layout: Any = None, + ) -> Optional[frozenset]: + """Allowed batch sizes at this shape: None = any, empty = none; static compile offers only already-compiled sizes. + A race verdict at this shape refines it: a measured loser is dropped, a measured winner is offered. ``layout``: + the request's prompt layout key (coalesce_plan), which a verdict won by graph replay must match.""" policy = self.request_batching() state = self._state if policy is None or policy["mode"] == "serial": return frozenset() + if _step_cache_couples_rows(state, steps): + # An AUTO cache engages FBCache at this step count: its skip decision would couple the rows. + return frozenset() + measured = _measured_sizes(state, width, height, guidance, steps, layout) + winners = frozenset(k for k, v in measured.items() if v.get("promoted")) + # A win the quality gate holds back (no G2c PASS) is not a loss: it keeps today's rule for its size, and only + # a measured speed loss takes a size away from the default policy. + losers = frozenset( + k for k, v in measured.items() if not v.get("promoted") and not v.get("quality_gate") + ) + if policy["mode"] == "measured": + return winners if policy["mode"] == "any": - return None + if not losers: + return None + from .image_request_batching import batch_max + return frozenset(range(2, batch_max() + 1)) - losers 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) + compiled = frozenset(int(shape[2]) for shape in list(shapes) if tuple(shape[:2]) == dims) + return compiled - losers + + def coalesce_seeded_ok( + self, + width: Any, + height: Any, + guidance: Optional[float], + images: int, + steps: Optional[int] = None, + layout: Any = None, + ) -> bool: + """Whether an explicitly seeded request may share a call: the measured path at this shape is neighbour-exact + and replays a member bit for bit (diffusion_batch_race.seeded_join_ok) at every size it could join. A load that + still admits unmeasured sizes (policy ``any``) can fire at one of them, so every admitted size needs a verdict.""" + state = self._state + if state is None: + return False + from . import diffusion_batch_race + from .image_request_batching import batch_max + + admitted = self.coalesce_batch_sizes(width, height, guidance, steps, layout) + sizes = set(range(2, batch_max() + 1)) if admitted is None else set(admitted) + sizes = {k for k in sizes if k > int(images or 1)} + if not sizes: + return False + measured = _measured_sizes(state, width, height, guidance, steps, layout) + return all(diffusion_batch_race.seeded_join_ok(measured.get(k)) for k in sizes) + + def batch_race( + self, + *, + width: int, + height: int, + steps: Optional[int] = None, + guidance: Optional[float] = None, + sizes: tuple = (2, 4), + repeats: int = 5, + accuracy: bool = True, + ) -> dict: + """Race serial against batched on this idle engine and persist the verdicts (an explicit warm-up; never runs + while a request holds or waits for the slot).""" + from . import diffusion_batch_race + from .image_request_batching import collecting + + state = self._state + if state is None: + raise diffusion_batch_race.RaceRefused("no image model is loaded") + load_token = self._load_token + + def idle() -> bool: + with self._generation_cancel_lock: + waiting = bool(self._queued_generate_cancels) or bool( + getattr(self, "_generate_riders", {}) + ) + return ( + self._state is state + and self._load_token == load_token + and not waiting + and not self._slot_turns + and self.generation_holder() is None + and not collecting() + ) + + from .diffusion_batch_adapters import batched_forward + + if not batched_forward(getattr(state, "family", None), getattr(state, "pipe", None)): + raise diffusion_batch_race.RaceRefused( + "this family's pipeline renders one image per forward" + ) + if getattr(state, "speed_deferred", False): + # The deferred profile engages on a load's third render: inside the race it would install graphs after + # the race snapshotted its handles (graph timings recorded as eager, no eager arm, batch graphs kept). + raise diffusion_batch_race.RaceRefused( + "this load's speed profile is still deferred (it engages on the third image); render a few images, " + "then race" + ) + if _race_adapters_active(getattr(state, "pipe", None)): + # The race renders without loras, which generate() reads as none: it would unload or zero the adapters (or, + # baked under streamed graphs, refuse mid-race), and verdicts are not keyed by adapter set. + raise diffusion_batch_race.RaceRefused( + "this load has active LoRA adapters; race an adapter-free load" + ) + if _step_cache_couples_rows(state, steps): + raise diffusion_batch_race.RaceRefused( + "FBCache runs at this step count; its batch-wide skip decision couples the rows" + ) + policy = _default_request_batching(state) + if policy["mode"] == "serial" and not policy.get("measurable"): + raise diffusion_batch_race.RaceRefused(policy["reason"]) + allowed = None + # From the load's compile state, not the policy mode: resident and graphed loads answer serial before it. + if "compiled" in (state.speed_optims or ()) and compiled_shapes_are_static( + state.pipe, state.speed_mode + ): + dims = (int(width), int(height)) + shapes = getattr(state.compile_cache_ctx, "shapes", None) or () + compiled = {int(shape[2]) for shape in list(shapes) if tuple(shape[:2]) == dims} + allowed = compiled.__contains__ + # The race prompts' layout key: a verdict won by graph replay holds only for requests in the same layout. + layout = None + try: + keys = [ + coalesce_prompt_key(state.family, state.pipe, p) + for p in diffusion_batch_race.RACE_PROMPTS[: max([2, *(int(k) for k in sizes)])] + ] + if keys and keys[0] is not None and all(k == keys[0] for k in keys): + layout = keys[0] + except Exception: # noqa: BLE001 - unknown layout: a graphed verdict then admits nothing + layout = None + report = diffusion_batch_race.run_race( + self.generate, + state, + idle = idle, + width = width, + height = height, + steps = steps, + guidance = guidance, + sizes = sizes, + repeats = repeats, + accuracy = accuracy, + allowed_sizes = allowed, + layout = layout, + ) + from .diffusion_batch_quality import gate + + # The persisted verdict is the speed race's; whether a win serves also needs a passing G2c verdict. + for verdict in (report.get("sizes") or {}).values(): + if isinstance(verdict, dict) and verdict.get("promoted"): + gated = gate(verdict, state) + verdict["serves"] = bool(gated.get("promoted")) + if gated.get("quality_gate"): + verdict["quality_gate"] = gated["quality_gate"] + return report @contextmanager def generation_rider(self, cancel: threading.Event): @@ -18775,6 +19046,7 @@ def status(self) -> dict[str, Any]: or getattr(state, "cuda_graphs", ()) ), "request_batching": self.request_batching(), + "batch_trace": _batch_trace_snapshot(), "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_batch_adapters.py b/studio/backend/core/inference/diffusion_batch_adapters.py new file mode 100644 index 000000000000..9a9c3c51a9ec --- /dev/null +++ b/studio/backend/core/inference/diffusion_batch_adapters.py @@ -0,0 +1,160 @@ +# SPDX-License-Identifier: AGPL-3.0-only +# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0 + +"""What a family needs to put several requests' images in one denoiser forward. + +A family says whether its pipeline call fuses a list of prompts into one forward through ``batched_forward`` (bool) on +its family object; unset keeps today's answer (``_DEFAULT_SERIAL`` and the pipe checks below). A family that needs its +own row layout sets ``batch_adapter`` to a ``BatchAdapter``; every other batched family uses ``DefaultAdapter``, the +diffusers list call.""" + +from __future__ import annotations + +from typing import Any, Awaitable, Callable, Hashable, Optional, Sequence + +BATCHED_FORWARD_ATTR = "batched_forward" +BATCH_ADAPTER_ATTR = "batch_adapter" + + +def _default_serial_names() -> frozenset: + from .diffusion_anima import ANIMA_FAMILY_NAME + from .diffusion_families import MINIMAX_H3_IMAGE_FAMILY_NAME, MOSS_IMAGE_FAMILY_NAME + from .diffusion_flux3 import FLUX3_FAMILY_NAMES + + # FLUX.3 and Anima loop one prompt per modular call; MiniMax-H3-Image runs each image as batch 1 (lockstep); + # MOSS loops samples outside its layer loop except on a measured layer-major load (_moss_layer_major). + return frozenset( + ( + *FLUX3_FAMILY_NAMES, + ANIMA_FAMILY_NAME, + MINIMAX_H3_IMAGE_FAMILY_NAME, + MOSS_IMAGE_FAMILY_NAME, + ) + ) + + +def _moss_layer_major(family: Any, pipe: Any) -> bool: + """A MOSS load that runs a batch layer-major on a card with a measured win (diffusion_moss_image.coalesce_key).""" + from .diffusion_families import MOSS_IMAGE_FAMILY_NAME + + if ( + getattr(family, "name", None) != MOSS_IMAGE_FAMILY_NAME + or getattr(pipe, "transformer", None) is None + ): + return False + try: + from .diffusion_moss_image import coalesce_key + return coalesce_key(pipe) is not None + except Exception: # noqa: BLE001 - an unreadable load renders alone + return False + + +def _qwen21_denoiser(pipe: Any) -> bool: + from .diffusion_qwenimage21 import _CLASS + return type(getattr(pipe, "transformer", None)).__name__ == _CLASS + + +def default_batched_forward(family: Any, pipe: Any = None) -> bool: + """Today's answer for a family that does not say: whether its list call runs the rows in one forward.""" + if getattr(family, "layer_count", 0): + return False # the layered pipeline's per-prompt layer stride is only right for one input + if getattr(family, "name", None) in _default_serial_names(): + return _moss_layer_major(family, pipe) + if pipe is not None and _qwen21_denoiser(pipe): + return False # lays out a batch from row 0, so it splits by text length and gains nothing + return True + + +def admits_without_pipe(family: Any) -> bool: + """The route's family check, which has no pipe: refuse only when the answer cannot depend on the load. MOSS fuses + rows only on a measured layer-major load, which the engine decides with its pipe (coalesce_plan).""" + from .diffusion_families import MOSS_IMAGE_FAMILY_NAME + + if batched_forward(family): + return True + return ( + getattr(family, BATCHED_FORWARD_ATTR, None) is None + and getattr(family, "name", None) == MOSS_IMAGE_FAMILY_NAME + ) + + +def batched_forward(family: Any, pipe: Any = None) -> bool: + """The family's ``batched_forward`` when it sets one, else ``default_batched_forward``.""" + said = getattr(family, BATCHED_FORWARD_ATTR, None) + if said is not None: + return bool(said) + return default_batched_forward(family, pipe) + + +class BatchAdapter: + """Per-family row contract. ``prepare`` returns the layout key a row must share with its batch neighbours (token + bucket, reference layout, canvas, CFG structure), or None when the row must render alone.""" + + name = "base" + + def prepare(self, family: Any, pipe: Any, prompt: str) -> Optional[tuple]: + raise NotImplementedError + + def compatible(self, a: Optional[tuple], b: Optional[tuple]) -> bool: + return a is not None and b is not None and a == b + + async def denoise_batched( + self, + run: Callable[..., Awaitable[dict]], + prompts: list[str], + seeds: list[int], + owners: Optional[list[Hashable]] = None, + ) -> dict: + return await run(prompts, seeds, owners = owners) + + def split( + self, + result: dict, + members: Sequence[Any], + *, + prefix: bool = False, + ) -> list[dict]: + from .image_request_batching import _split + return _split(result, list(members), prefix = prefix) + + +class DefaultAdapter(BatchAdapter): + """The diffusers list call: one prompt list, one generator per row, images back in row order.""" + + name = "default" + + def prepare(self, family: Any, pipe: Any, prompt: str) -> Optional[tuple]: + from .diffusion_prompt_weighting import has_prompt_syntax + from .diffusion_text_length import FLUX_T5_FAMILIES, flux_t5_sequence_length + + name = getattr(family, "name", None) + if name in FLUX_T5_FAMILIES: + # FLUX.1 pads T5 to the call's longest prompt bucket. + 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: + # SD / SDXL chunk the CLIP prompt per call: members must match chunk counts and syntax. + from .diffusion import _clip_chunk_counts + chunks = _clip_chunk_counts(pipe, prompt) + return None if chunks is None else ("clip", has_prompt_syntax(prompt), chunks) + return () + + +DEFAULT_ADAPTER = DefaultAdapter() + + +def adapter_for(family: Any, pipe: Any = None) -> Optional[BatchAdapter]: + """The adapter that batches this family's rows, or None when its requests render one at a time.""" + if not batched_forward(family, pipe): + return None + own = getattr(family, BATCH_ADAPTER_ATTR, None) + return own if isinstance(own, BatchAdapter) else DEFAULT_ADAPTER + + +def key_tokenizes(family: Any) -> bool: + """Whether ``DefaultAdapter.prepare`` runs a tokenizer for this family (the caller then needs private copies).""" + from .diffusion_text_length import FLUX_T5_FAMILIES + return ( + getattr(family, "name", None) in FLUX_T5_FAMILIES + or getattr(family, "textual_inversion", None) is not None + ) diff --git a/studio/backend/core/inference/diffusion_batch_quality.py b/studio/backend/core/inference/diffusion_batch_quality.py new file mode 100644 index 000000000000..39ffca01ea5d --- /dev/null +++ b/studio/backend/core/inference/diffusion_batch_quality.py @@ -0,0 +1,158 @@ +# SPDX-License-Identifier: AGPL-3.0-only +# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0 + +"""The quality gate on a measured batching win: a race (diffusion_batch_race) only times a shared call and checks it +bit for bit against a rerun; it cannot tell whether a batched row drifts from the image that request renders alone. +That is an offline G2c verdict: held-out prompts x seeds rendered batched and alone on one execution path, scored with +LPIPS against an eager reference, paired upper bound of (batched - solo) at most ``EPS`` over at least ``MIN_PAIRS``. + +Verdicts are keyed by (family, device class, execution path): the device class is the card's name (one verdict covers +every card of that model), the path is ``eager`` or ``graph`` (what the race's winning arm really ran, persisted as +``path``), or ``any``. A measured win is served only where a PASS verdict exists for its family, card and path; a missing or failing +verdict keeps today's serial rules. ``SHIPPED`` holds the verdicts measured for releases; a local file +(``/batch_quality.json``, written by ``record``) adds this machine's own.""" + +from __future__ import annotations + +import json +import os +import threading +import time +from pathlib import Path +from typing import Any, Optional + +EPS = 0.01 +MIN_PAIRS = 24 +PATHS = ("eager", "graph", "any") +FILE_NAME = "batch_quality.json" + +# (family name, device class, path) -> verdict. Only PASS verdicts measured on a release build belong here. +SHIPPED: dict[tuple[str, str, str], dict] = {} + +_LOCK = threading.Lock() +_DEVICE_CLASS: dict[str, Optional[str]] = {} + + +def _file() -> Optional[Path]: + try: + from utils.paths.storage_roots import cache_root + return cache_root() / FILE_NAME + except Exception: # noqa: BLE001 - no Studio home: shipped verdicts only + return None + + +def _key(family: str, device: str, path: str) -> str: + return f"{family}|{device}|{path}" + + +def _read() -> dict: + path = _file() + if path is None or not path.is_file(): + return {} + try: + data = json.loads(path.read_text(encoding = "utf-8")) + return data if isinstance(data, dict) else {} + except Exception: # noqa: BLE001 - an unreadable file is no verdict + return {} + + +def path_of(verdict: Any) -> str: + """The execution path a race verdict served on: its recorded ``path``, else (a verdict from before it was recorded) + the arm name, which is a guess for a load without graph handles.""" + if isinstance(verdict, dict): + if verdict.get("path") in ("eager", "graph"): + return verdict["path"] + return "eager" if verdict.get("arm") == "batched_eager" else "graph" + return "eager" if verdict == "batched_eager" else "graph" + + +def device_class(state: Any) -> Optional[str]: + """The card's model name (``NVIDIA A100-SXM4-40GB``), None off CUDA / ROCm or when it cannot be read.""" + named = getattr(state, "device_name", None) + if isinstance(named, str) and named: + return named + from .diffusion_batch_race import card_of + + card = card_of(state) + if card is None: + return None + if card not in _DEVICE_CLASS: + try: + import torch + _DEVICE_CLASS[card] = str(torch.cuda.get_device_name(int(card.split(":")[1]))) + except Exception: # noqa: BLE001 + _DEVICE_CLASS[card] = None + return _DEVICE_CLASS[card] + + +def passes(verdict: Any) -> bool: + """A stored verdict that lets a measured win serve: PASS, enough pairs, upper bound within ``EPS``.""" + if not isinstance(verdict, dict) or verdict.get("verdict") != "PASS": + return False + try: + return int(verdict.get("n", 0)) >= MIN_PAIRS and float(verdict.get("upper")) <= EPS + except (TypeError, ValueError): + return False + + +def lookup(family: Optional[str], device: Optional[str], path: str) -> Optional[dict]: + """The verdict that applies (this path's own, else ``any``); local entries over shipped ones.""" + if not family or not device: + return None + local = _read() + for p in (path, "any"): + found = local.get(_key(family, device, p)) + if isinstance(found, dict): + return found + found = SHIPPED.get((family, device, p)) + if isinstance(found, dict): + return found + return None + + +def _family(state: Any) -> Optional[str]: + return getattr(getattr(state, "family", None), "name", None) + + +def quality_ok(state: Any, path: str) -> bool: + return passes(lookup(_family(state), device_class(state), path)) + + +def any_quality_ok(state: Any) -> bool: + """Whether some path of this family on this card has a PASS verdict (status may report the measured mode).""" + family, device = _family(state), device_class(state) + return any(passes(lookup(family, device, p)) for p in ("eager", "graph")) + + +def gate(verdict: Any, state: Any) -> Any: + """``verdict`` as it may serve: a promoted one without a PASS for its family, card and path is not promoted.""" + if not isinstance(verdict, dict) or not verdict.get("promoted"): + return verdict + path = path_of(verdict) + if quality_ok(state, path): + return verdict + family, device = _family(state), device_class(state) + found = lookup(family, device, path) + reason = ( + f"no G2c verdict for {family} on {device} ({path})" + if found is None + else f"G2c verdict for {family} on {device} ({path}) does not pass" + ) + return dict(verdict, promoted = False, quality_gate = reason) + + +def record(family: str, device: str, path: str, verdict: dict) -> bool: + """Persist an offline G2c verdict (``verdict``, ``n``, ``upper`` and whatever else the harness reports).""" + if path not in PATHS: + raise ValueError(f"path must be one of {PATHS}") + target = _file() + if target is None: + return False + with _LOCK: + data = _read() + data[_key(family, device, path)] = dict(verdict, t = verdict.get("t", time.time())) + target.parent.mkdir(parents = True, exist_ok = True) + tmp = target.with_name(f".{target.name}.{os.getpid()}.{threading.get_ident()}.tmp") + tmp.write_text(json.dumps(data, indent = 1, sort_keys = True), encoding = "utf-8") + os.replace(tmp, target) + return True diff --git a/studio/backend/core/inference/diffusion_batch_race.py b/studio/backend/core/inference/diffusion_batch_race.py new file mode 100644 index 000000000000..0f7af38554e4 --- /dev/null +++ b/studio/backend/core/inference/diffusion_batch_race.py @@ -0,0 +1,898 @@ +# SPDX-License-Identifier: AGPL-3.0-only +# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0 + +"""Measured verdicts on whether concurrent image requests should share one call on this load, card and shape. + +A race times k requests served one at a time against the same k requests in one call (each arm including encode, +denoise and decode), interleaved over several repeats, on an idle engine only. A batch size is promoted only when the +lower one-sided 95% bound of the per-repeat speedup is at least ``PROMOTE_LB`` and the batched p95 request latency is at +most ``P95_SLACK`` times the serial one. Winners and losers are both persisted, keyed by the probe fingerprint (torch, +driver, card, env) plus the load's model, variant, precision, attention, placement, graph and compile state, canvas, +guidance and batch size. A (load, shape, size) without a verdict keeps today's rules.""" + +from __future__ import annotations + +import math +import random +import time +from contextlib import contextmanager +from typing import Any, Callable, Iterator, Optional, Sequence + +PROMOTE_LB = 1.05 +P95_SLACK = 1.03 +MIN_REPEATS = 3 +RACE_SIZES = (2, 4) +_N_BOOT = 4000 +# One-sided 95% Student t quantiles by degrees of freedom (a df between rows uses the smaller df: more conservative). +_T95 = ( + (1, 6.314), + (2, 2.920), + (3, 2.353), + (4, 2.132), + (5, 2.015), + (6, 1.943), + (7, 1.895), + (8, 1.860), + (9, 1.833), + (10, 1.812), + (12, 1.782), + (15, 1.753), + (20, 1.725), + (30, 1.697), + (60, 1.671), +) + +# Generic prompts of similar length, so a T5-bucket family keys them alike. +RACE_PROMPTS = ( + "a red fox sitting in fresh snow, photograph", + "a blue sports car on a desert highway at noon", + "a bowl of ramen with a soft boiled egg, top view", + "a lighthouse on a rocky cliff at sunset, painting", + "a green parrot on a branch in the rain forest", + "a wooden cabin beside a frozen lake at night", + "a bicycle leaning on a brick wall in the city", + "a cup of coffee on a table by a sunny window", +) +NEIGHBOUR_PROMPTS = ( + "an old steam train crossing a stone bridge", + "a field of sunflowers under a stormy sky", + "a robot reading a newspaper in a diner", + "a jellyfish glowing in a dark blue ocean", + "a stack of pancakes with berries and syrup", + "a snowy mountain peak above the clouds", + "a cat sleeping on a pile of old books", +) + +# The largest batch a race can run: every row needs its own race prompt, and the neighbour check needs size - 1 others. +MAX_RACE_SIZE = min(len(RACE_PROMPTS), len(NEIGHBOUR_PROMPTS) + 1) + + +def invalid_race_sizes(sizes: Optional[Sequence[Any]]) -> Optional[str]: + """Why these batch sizes cannot be raced (None when they all can): each must be an integer in 2..MAX_RACE_SIZE.""" + if sizes is None: + return None + bad = [ + k + for k in sizes + if isinstance(k, bool) or not isinstance(k, int) or not 2 <= k <= MAX_RACE_SIZE + ] + if not bad: + return None + return f"batch sizes must be integers from 2 to {MAX_RACE_SIZE}; got {bad}" + + +def _pick_arm(verdicts: dict) -> str: + """The arm a size is decided by: among the arms that pass every requirement, the highest speedup bound; when none + passes, the highest bound (whose loss is recorded). Arm order breaks ties (``batched`` first).""" + arms = list(verdicts) + passing = [arm for arm in arms if verdicts[arm].get("promoted")] + return max(passing or arms, key = lambda arm: verdicts[arm].get("speedup_lb") or 0.0) + + +_STORE: list = [] +# Cards with no fingerprint (no driver identity, no CUDA): status polls must not re-probe them every call. +_UNIDENTIFIED: dict = {} +_UNIDENTIFIED_RETRY_S = 300.0 + + +def _store() -> Any: + if not _STORE: + from .diffusion_probe_cache import Namespace + _STORE.append( + Namespace( + "batch_race", + sources = ( + "diffusion_batch_race.py", + "diffusion_batch_adapters.py", + "diffusion_batched.py", + "diffusion_cuda_graph.py", + ), + ) + ) + return _STORE[0] + + +def t95(df: int) -> float: + if df < 1: + return float("inf") + best = _T95[0][1] + for row_df, value in _T95: + if row_df <= df: + best = value + return best + + +def percentile(values: Sequence[float], q: float) -> float: + """Nearest-rank percentile (q in 0..100).""" + if not values: + return float("nan") + ordered = sorted(values) + rank = max(1, math.ceil(q / 100.0 * len(ordered))) + return float(ordered[min(rank, len(ordered)) - 1]) + + +def speedup_lower_bound(ratios: Sequence[float], *, seed: int = 0) -> float: + """One-sided 95% lower bound of the geometric-mean speedup: the smaller of a Student t bound on the log ratios + and a seeded percentile bootstrap bound (the bootstrap under-covers at small n). 0 when fewer than two.""" + logs = [math.log(r) for r in ratios if r and r > 0 and math.isfinite(r)] + n = len(logs) + if n < 2: + return 0.0 + mean = sum(logs) / n + var = sum((x - mean) ** 2 for x in logs) / (n - 1) + t_bound = mean - t95(n - 1) * math.sqrt(var / n) + rng = random.Random(seed) + means = sorted(sum(rng.choice(logs) for _ in range(n)) / n for _ in range(_N_BOOT)) + boot_bound = means[int(0.05 * _N_BOOT)] + return math.exp(min(t_bound, boot_bound)) + + +def burst_latencies(serial_times: Sequence[float], batched_time: float) -> tuple[list, list]: + """Request latencies of one burst of k: served one at a time (each waits for those before it) vs in one call.""" + out, total = [], 0.0 + for t in serial_times: + total += t + out.append(total) + return out, [float(batched_time)] * len(serial_times) + + +def judge(repeats: Sequence[tuple[Sequence[float], float]], *, seed: int = 0) -> dict: + """``repeats``: per repeat (the k serial render times, the one batched call time). The verdict for this size.""" + ratios, serial_lat, batched_lat = [], [], [] + for serial, batched in repeats: + if not serial or batched <= 0: + continue + ratios.append(sum(serial) / batched) + s, b = burst_latencies(serial, batched) + serial_lat.extend(s) + batched_lat.extend(b) + lb = speedup_lower_bound(ratios, seed = seed) + p95_s, p95_b = percentile(serial_lat, 95), percentile(batched_lat, 95) + p50_s, p50_b = percentile(serial_lat, 50), percentile(batched_lat, 50) + enough = len(ratios) >= MIN_REPEATS + fast = lb >= PROMOTE_LB + tail = bool(serial_lat) and p95_b <= P95_SLACK * p95_s + if not enough: + reason = f"{len(ratios)} repeats, fewer than {MIN_REPEATS}" + elif not fast: + reason = f"speedup lower bound {lb:.3f} below {PROMOTE_LB}" + elif not tail: + reason = f"batched p95 {p95_b:.2f}s above {P95_SLACK} x serial p95 {p95_s:.2f}s" + else: + reason = f"speedup lower bound {lb:.3f}, p95 {p95_b:.2f}s vs {p95_s:.2f}s" + ordered = sorted(ratios) + return { + "promoted": bool(enough and fast and tail), + "reason": reason, + "repeats": len(ratios), + "speedup_lb": round(lb, 4), + "speedup_median": round(ordered[len(ordered) // 2], 4) if ordered else None, + "ratios": [round(r, 4) for r in ratios], + "p50_serial_s": round(p50_s, 3) if serial_lat else None, + "p50_batched_s": round(p50_b, 3) if serial_lat else None, + "p95_serial_s": round(p95_s, 3) if serial_lat else None, + "p95_batched_s": round(p95_b, 3) if serial_lat else None, + } + + +# ------------------------------------------------------------------------------------------------ keys + + +def _compile_state(state: Any) -> str: + optims = tuple(getattr(state, "speed_optims", ()) or ()) + if "compiled" not in optims: + return "eager" + try: + from .diffusion import compiled_shapes_are_static + static = compiled_shapes_are_static( + getattr(state, "pipe", None), getattr(state, "speed_mode", None) + ) + except Exception: # noqa: BLE001 + static = True + return "static" if static else "dynamic" + + +def topology(state: Any) -> str: + """Cards the host shows and how this load spans them (component split, CFG replica, layer split): a verdict on one + topology says nothing about another (Kaggle 2xT4: per-card replicas beat the split only from 2 users up).""" + try: + import torch + count = int(torch.cuda.device_count()) if torch.cuda.is_available() else 0 + except Exception: # noqa: BLE001 + count = 0 + pipe = getattr(state, "pipe", None) + parts = [f"cards{count}"] + try: + from . import diffusion_multigpu as mg + + info = mg._PLACEMENTS.get(pipe) if pipe is not None else None + if info: + moved = ",".join(sorted(str(m) for m in info.get("moved") or ())) + parts.append(f"split:{info.get('primary')}>{info.get('secondary')}:{moved}") + if pipe is not None and mg._CFG_ROUTERS.get(pipe) is not None: + parts.append("cfg_replica") + from .diffusion_layer_split_plan import layer_split_status + + if pipe is not None and layer_split_status(pipe): + parts.append("layer_split") + except Exception: # noqa: BLE001 - unreadable placement: its own key, never another load's verdict + parts.append("placement?") + return "+".join(parts) + + +def load_key(state: Any) -> str: + """Everything about the load a verdict depends on (the card side comes from the probe fingerprint).""" + from .diffusion import _denoiser_streams_from_host + + family = getattr(state, "family", None) + pipe = getattr(state, "pipe", None) + resolved = getattr(state, "resolved", None) or {} + revision = "" + if isinstance(resolved, dict): + revision = str( + resolved.get("revision") or resolved.get("sha") or resolved.get("commit") or "" + ) + try: + streamed = bool(_denoiser_streams_from_host(state)) + except Exception: # noqa: BLE001 + streamed = True + parts = ( + str(getattr(state, "repo_id", None) or ""), + revision, + str(getattr(state, "gguf_filename", None) or ""), + str(getattr(family, "name", None) or ""), + type(getattr(pipe, "transformer", None) or getattr(pipe, "unet", None)).__name__, + str(getattr(state, "transformer_quant", None) or "bf16"), + str(getattr(state, "dtype", None) or ""), + str(getattr(state, "speed_mode", None) or ""), + ",".join(sorted(str(o) for o in (getattr(state, "speed_optims", ()) or ()))), + str(getattr(state, "attention_backend", None) or ""), + str(getattr(state, "offload_policy", None) or ""), + "streamed" if streamed else "resident", + "graphs" if getattr(state, "cuda_graphs", ()) else "nographs", + _compile_state(state), + str(getattr(state, "transformer_cache", None) or ""), + topology(state), + ) + return "|".join(parts) + + +def shape_key( + width: Any, + height: Any, + guidance: Any, + steps: Any = None, +) -> str: + """Canvas, guidance and step count: the fixed per-call cost (encode, decode) weighs more at few steps, so a win at + one step count says little about another (one engine's own FLUX.3 batching: 2.00x at 512 / 8 steps, 1.03x at + 1024 / 50).""" + try: + g = "" if guidance is None else f"{float(guidance):.3g}" + except (TypeError, ValueError): + g = str(guidance) + try: + n = "" if steps is None else str(int(steps)) + except (TypeError, ValueError): + n = str(steps) + return f"{int(width or 0)}x{int(height or 0)}|g{g}|s{n}|default" + + +def card_of(state: Any) -> Optional[str]: + device = str(getattr(state, "device", "") or "") + if not device.startswith("cuda"): + return None + ordinal = getattr(state, "placed_ordinal", None) + if ordinal is None: + ordinal = getattr(state, "gpu_ordinal", None) + card = f"cuda:{int(ordinal)}" if ordinal is not None else device + seen = _UNIDENTIFIED.get(card) + if seen is not None and time.monotonic() - seen < _UNIDENTIFIED_RETRY_S: + return None + return card + + +def _slot(card: str) -> Optional[tuple]: + slot = _store()._slot(card) + if slot is None: + _UNIDENTIFIED[card] = time.monotonic() + else: + _UNIDENTIFIED.pop(card, None) + return slot + + +def verdict_key( + state: Any, + width: Any, + height: Any, + guidance: Any, + size: int, + steps: Any = None, +) -> str: + return f"{load_key(state)}#{shape_key(width, height, guidance, steps)}#k{int(size)}" + + +def lookup( + state: Any, + width: Any, + height: Any, + guidance: Any, + sizes: Sequence[int], + steps: Any = None, +) -> dict[int, dict]: + """Persisted verdicts for this load and shape by batch size; {} when there are none or no card identity.""" + card = card_of(state) + if card is None: + return {} + try: + slot = _slot(card) + if slot is None: + return {} + base = f"{load_key(state)}#{shape_key(width, height, guidance, steps)}#k" + out = {} + for size in sizes: + found = slot[2].get(f"{base}{int(size)}") + if isinstance(found, dict): + out[int(size)] = found + return out + except Exception: # noqa: BLE001 - an unreadable store is no verdict + return {} + + +def any_promoted(state: Any) -> bool: + """Whether some shape of this load has a promoted batch size (status reports the measured mode).""" + card = card_of(state) + if card is None: + return False + try: + slot = _slot(card) + if slot is None: + return False + prefix = f"{load_key(state)}#" + return any( + k.startswith(prefix) and isinstance(v, dict) and v.get("promoted") + for k, v in slot[2].items() + ) + except Exception: # noqa: BLE001 + return False + + +def record( + state: Any, + width: Any, + height: Any, + guidance: Any, + size: int, + verdict: dict, + steps: Any = None, +) -> bool: + card = card_of(state) + if card is None: + return False + try: + return bool( + _store().put( + card, verdict_key(state, width, height, guidance, size, steps), dict(verdict) + ) + ) + except Exception: # noqa: BLE001 - a cache write never fails the race + return False + + +# ------------------------------------------------------------------------------------------------ runner + + +class RaceRefused(RuntimeError): + """The engine is not idle (or nothing is loaded): no race runs on a user's request.""" + + +def _pixels(images: Sequence[Any]) -> list: + out = [] + for image in images: + try: + import numpy as np + out.append(np.asarray(image.convert("RGB")).copy()) + except Exception: # noqa: BLE001 + out.append(None) + return out + + +def _same(a: Any, b: Any) -> Optional[bool]: + if a is None or b is None: + return None + try: + return bool(a.shape == b.shape and (a == b).all()) + except Exception: # noqa: BLE001 + return None + + +def _max_abs(a: Any, b: Any) -> Optional[int]: + if a is None or b is None or a.shape != b.shape: + return None + return int(abs(a.astype("int16") - b.astype("int16")).max()) + + +@contextmanager +def _graphs_bypassed(handles: Sequence[Any]) -> Iterator[None]: + """The batched-eager arm: every graph handle runs eager (``set_bypass``) and keeps its graphs.""" + flipped = [] + try: + for handle in handles: + if callable(getattr(handle, "set_bypass", None)): + handle.set_bypass(True) + flipped.append(handle) + yield + finally: + for handle in flipped: + try: + handle.set_bypass(False) + except Exception: # noqa: BLE001 + pass + + +def run_race( + generate: Callable[..., dict], + state: Any, + *, + idle: Callable[[], bool], + width: int, + height: int, + steps: Optional[int] = None, + guidance: Optional[float] = None, + sizes: Sequence[int] = RACE_SIZES, + repeats: int = 5, + accuracy: bool = True, + allowed_sizes: Optional[Callable[[int], bool]] = None, + layout: Any = None, + seed: int = 0, + persist: bool = True, + clock: Callable[[], float] = time.perf_counter, +) -> dict: + """Race serial against batched at each size on an idle engine; persist each size's verdict (losers too). + + ``generate`` is the backend's generate. ``idle`` is checked before every render: a request that starts waiting + aborts the race (nothing is persisted for the size under way). ``allowed_sizes`` (static compile) skips a size + that would compile.""" + from . import diffusion_cuda_graph as cuda_graph + + bad = invalid_race_sizes(list(sizes)) + if bad: + raise ValueError(bad) + if not idle(): + raise RaceRefused("a request holds or waits for the generation slot") + rng = random.Random(seed) + common = {"width": int(width), "height": int(height), "live_preview": False} + if steps is not None: + common["steps"] = int(steps) + if guidance is not None: + common["guidance"] = float(guidance) + handles = tuple(getattr(state, "cuda_graphs", ()) or ()) + configuration = _execution_configuration(state) + canvas = canvas_token(width, height, guidance, steps, layout) + report: dict = {"width": int(width), "height": int(height), "guidance": guidance, "sizes": {}} + + class _Aborted(Exception): + pass + + def solo( + prompt: str, + seed_: int, + *, + eager: bool = False, + ) -> tuple[float, Any]: + if not idle(): + raise _Aborted() + start = clock() + # ``eager``: the solo render on the batched-eager arm's own path, so a replay check compares like for like. + with ( + _graphs_bypassed(handles) if eager else _nullctx(), + cuda_graph.forced_eager() if eager else _nullctx(), + ): + out = generate(prompt = prompt, seed = seed_, **common) + return clock() - start, (out.get("images") or [None])[0] + + def batch( + prompts: list, + seeds: list, + *, + eager: bool = False, + capture: bool = False, + ) -> tuple[float, list]: + if not idle(): + raise _Aborted() + start = clock() + with ( + cuda_graph.batch_rows(len(prompts), capture = capture, canvas = canvas), + _graphs_bypassed(handles) if eager else _nullctx(), + # generate() re-arms the graphs before every chunk; this scope keeps them bypassed through it. + cuda_graph.forced_eager() if eager else _nullctx(), + ): + out = generate( + prompt = prompts[0], + prompts = list(prompts), + seeds = list(seeds), + batch_size = len(prompts), + **common, + ) + return clock() - start, list(out.get("images") or []) + + # Largest first: inside one pool the smaller graphs then reuse the blocks the largest recorded. + for size in sorted({int(k) for k in sizes}, reverse = True): + if size < 2: + continue + if allowed_sizes is not None and not allowed_sizes(size): + report["sizes"][str(size)] = { + "skipped": "static compile has no graph for this batch size" + } + continue + prompts = list(RACE_PROMPTS[:size]) + seeds = [1000 + 7 * i for i in range(size)] + arms = ["batched"] + (["batched_eager"] if handles else []) + try: + # Warm-ups (untimed): the serial shape, then each batched arm; a batched graph at this size records here. + solo(prompts[0], seeds[0]) + batch(prompts, seeds, capture = True) + if "batched_eager" in arms: + batch(prompts, seeds, eager = True) + samples: dict[str, list] = {arm: [] for arm in arms} + for _ in range(max(1, int(repeats))): + order = ["serial", *arms] + rng.shuffle(order) + serial_times: list = [] + times: dict = {} + for arm in order: + if arm == "serial": + serial_times = [solo(p, s)[0] for p, s in zip(prompts, seeds)] + else: + times[arm] = batch( + prompts, seeds, eager = arm == "batched_eager", capture = True + )[0] + for arm in arms: + samples[arm].append((serial_times, times[arm])) + verdicts = {arm: judge(samples[arm], seed = seed) for arm in arms} + eager = verdicts.get("batched_eager") + if eager is not None and eager.get("promoted") and not _enforces_eager(handles): + # Its win could not be served: later batched calls on these handles would replay graphs again. + verdicts["batched_eager"] = dict( + eager, + promoted = False, + reason = "the eager arm won, but these graph handles cannot keep batched calls eager " + "(no drop_batched)", + ) + best = _pick_arm(verdicts) + verdict = dict( + verdicts[best], + arm = best, + # The execution path the winning arm really ran: without graph handles the batched arm is eager. + path = "graph" if best == "batched" and handles else "eager", + arms = verdicts, + size = size, + layout = layout_token(layout), + graph_canvas = canvas, + t = time.time(), + ) + if accuracy: + verdict.update( + _neighbour_check(solo, batch, prompts, seeds, eager = best == "batched_eager") + ) + except _Aborted: + # No verdict for this size, so no request can use what its warm-up recorded: drop it before returning. + report["sizes"][str(size)] = { + "aborted": "a request started waiting for the slot", + "batched_graphs_dropped": _drop_batched(handles, size), + } + report["aborted"] = True + break + except Exception as exc: # noqa: BLE001 - only a capacity failure is a verdict; anything else raises + if not _capacity_failure(exc): + raise + # A loss with its reason; the traceback would pin the failed call's tensors through the smaller sizes. + reason = f"out of memory at batch {size}: {str(exc).splitlines()[0][:200] if str(exc) else type(exc).__name__}" + exc.__traceback__ = None + del exc + verdict = { + "promoted": False, + "failed": reason, + "size": size, + "layout": layout_token(layout), + "t": time.time(), + } + report["sizes"][str(size)] = verdict + if not verdict.get("promoted") or verdict.get("arm") == "batched_eager": + # A losing size never runs batched here, and an eager-won size must not replay the graphs the race + # recorded (dispatch never bypasses them; user calls never record new ones): drop that size's graphs (their + # own pool returns to the card; under BATCH_POOL_ENV=shared they stay in the one pool). + verdict["batched_graphs_dropped"] = _drop_batched(handles, size) + if verdict.get("failed"): + _release_cached() # after the drop, so the batched pool's blocks go back too + if _execution_configuration(state) != configuration: + # The load changed how it runs under the race (a deferred speed profile engaged, graphs installed): this + # size's timings straddle two configurations. Persist nothing and drop what the new handles recorded. + for k in {int(x) for x in sizes}: + _drop_batched(tuple(getattr(state, "cuda_graphs", ()) or ()), k) + raise RaceRefused( + "the load's execution configuration changed during the race; race it again" + ) + if persist: + verdict["persisted"] = record(state, width, height, guidance, size, verdict, steps) + return report + + +def _execution_configuration(state: Any) -> tuple: + """What a race's timings depend on that a render can change: the graph handles and the speed profile.""" + return ( + tuple(id(h) for h in (getattr(state, "cuda_graphs", ()) or ())), + tuple(getattr(state, "speed_optims", ()) or ()), + bool(getattr(state, "speed_deferred", False)), + ) + + +def _drop_batched(handles: Sequence[Any], size: int) -> int: + """Drop every handle's batched graphs of ``size``; how many went.""" + dropped = 0 + for handle in handles: + drop = getattr(handle, "drop_batched", None) + if callable(drop): + try: + dropped += int(drop(size) or 0) + except Exception: # noqa: BLE001 + pass + return dropped + + +def _capacity_failure(exc: BaseException) -> bool: + """CUDA / MPS out of memory or a unified-memory refusal: the size does not fit this card, a verdict, not a bug.""" + try: + from .diffusion_batched import is_oom_error + if is_oom_error(exc): + return True + except Exception: # noqa: BLE001 + pass + try: + from .diffusion_memory import unified_memory_refusal_code + if unified_memory_refusal_code(exc) is not None: + return True + except Exception: # noqa: BLE001 + pass + return "out of memory" in str(exc).lower() + + +def _release_cached() -> None: + try: + import gc + + gc.collect() + import torch + + if torch.cuda.is_available(): + torch.cuda.empty_cache() + except Exception: # noqa: BLE001 + pass + + +@contextmanager +def _nullctx() -> Iterator[None]: + yield + + +def _neighbour_check(solo, batch, prompts: list, seeds: list, *, eager: bool) -> dict: + """G2a at this batch shape: change only the neighbours (prompt and seed), the target first then last; an A/A + repeat of the identical batch gives the noise floor. Plus the batch-shape check G2a cannot see (it holds the batch + shape fixed): whether row 0 equals its own solo render on the SAME execution path (``eager`` renders the solo + eager too). ``b_exact``: bit-identical, or no further from its solo than the A/A floor of that path.""" + size = len(prompts) + others = list(NEIGHBOUR_PROMPTS[: size - 1]) + other_seeds = [9000 + 13 * i for i in range(size - 1)] + _, a = batch(prompts, seeds, eager = eager) + _, a2 = batch(prompts, seeds, eager = eager) + _, b = batch([prompts[0], *others], [seeds[0], *other_seeds], eager = eager) + _, c = batch([*others, prompts[0]], [*other_seeds, seeds[0]], eager = eager) + _, d = batch([*prompts[1:], prompts[0]], [*seeds[1:], seeds[0]], eager = eager) + _, alone = solo(prompts[0], seeds[0], eager = eager) + pa, pa2, pb, pc, pd = (_pixels(x) for x in (a, a2, b, c, d)) + [ps] = _pixels([alone]) + first = _same(pa[0], pb[0]) if pa and pb else None + last = _same(pd[-1], pc[-1]) if pd and pc else None + aa = _same(pa[0], pa2[0]) if pa and pa2 else None + return { + "aa_exact": aa, + "neighbour_exact": bool(first and last), + "neighbour_first_max_abs": _max_abs(pa[0], pb[0]) if pa and pb else None, + "neighbour_last_max_abs": _max_abs(pd[-1], pc[-1]) if pd and pc else None, + "aa_max_abs": _max_abs(pa[0], pa2[0]) if pa and pa2 else None, + "replay_exact": bool(_same(pa[0], ps)) if pa else False, + "replay_max_abs": _max_abs(pa[0], ps) if pa else None, + "replay_path": "eager" if eager else "graph", + "b_exact": _b_exact(pa[0] if pa else None, ps, pa2[0] if pa2 else None), + } + + +def _b_exact(row: Any, alone: Any, again: Any) -> bool: + """Row 0 of a batch against its solo render: equal, or no further than the same batch rerun (the kernel noise of + that shape and path).""" + if row is None or alone is None: + return False + if _same(row, alone): + return True + replay, floor = _max_abs(row, alone), _max_abs(row, again) if again is not None else None + return replay is not None and floor is not None and floor > 0 and replay <= floor + + +def canvas_token(width: Any, height: Any, guidance: Any, steps: Any, layout: Any) -> str: + """The race's shape identity (canvas, guidance, steps, prompt layout): labels the batched graphs it records.""" + import json + return json.dumps( + { + "w": int(width), + "h": int(height), + "g": None if guidance is None else float(guidance), + "s": None if steps is None else int(steps), + "l": layout_token(layout), + }, + sort_keys = True, + ) + + +def batched_graph_canvas(state: Any, size: int, canvas: Optional[str]) -> bool: + """Every step-graph handle holds a batch-``size`` graph labelled with ``canvas`` now (GraphedForward keys on tensor + shapes: a same-size graph of another canvas replays nothing for this one).""" + if canvas is None: + return False + for handle in getattr(state, "cuda_graphs", ()) or (): + if not hasattr(handle, "_batched"): + continue + batched = getattr(handle, "_batched", None) or {} + cache = getattr(handle, "cache", None) or {} + labels = getattr(handle, "_batched_canvas", None) or {} + if not any( + k in cache and int(v) == int(size) and canvas in (labels.get(k) or ()) + for k, v in batched.items() + ): + return False + return True + + +def batched_graph_sizes(state: Any) -> Optional[set]: + """Batch sizes every step-graph handle of this load holds a graph for now; None when no handle constrains it. + + Only handles that label their batch-size graphs (GraphedForward ``_batched``) count: they never record one on a + user's request. Block / segment graphs (BlockGraphSet, offloaded and layer-split loads) record each new layout on + demand, user calls included, so a size they raced graphed is never missing for them.""" + handles = [h for h in (getattr(state, "cuda_graphs", ()) or ()) if hasattr(h, "_batched")] + if not handles: + return None + held = None + for handle in handles: + batched = getattr(handle, "_batched", None) or {} + cache = getattr(handle, "cache", None) or {} + sizes = {int(v) for k, v in batched.items() if k in cache} + held = sizes if held is None else held & sizes + return held or set() + + +def layout_token(layout: Any) -> Optional[str]: + """A persistable token for a prompt layout key (coalesce_prompt_key: token bucket, chunk count), None if unknown.""" + if layout is None: + return None + try: + import json + return json.dumps(layout, sort_keys = True, default = str) + except Exception: # noqa: BLE001 + return repr(layout) + + +def _enforces_eager(handles: Sequence[Any]) -> bool: + """Whether batched calls of a size stay eager once that size's batched graphs are dropped: true only when every + graph handle can drop them. A handle that records on demand (block graphs) would replay graphs again.""" + return all(callable(getattr(handle, "drop_batched", None)) for handle in handles) + + +def _withhold_unenforceable_eager(verdict: Any, handles: Sequence[Any]) -> Any: + if ( + isinstance(verdict, dict) + and verdict.get("promoted") + and verdict.get("arm") == "batched_eager" + and not _enforces_eager(handles) + ): + return dict( + verdict, + promoted = False, + reason = "the eager arm won, but these graph handles cannot keep batched calls eager (no drop_batched)", + ) + return verdict + + +def effective_verdict( + verdict: dict, + size: int, + state: Any, + layout: Any = None, +) -> dict: + """``_effective_verdict``, withholding an eager win the load's graph handles could not enforce, or one a batch-size + graph recorded since (by a later race at another canvas or step count) could replay for these tensor shapes.""" + found = _withhold_unenforceable_eager( + _effective_verdict(verdict, size, state, layout = layout), + tuple(getattr(state, "cuda_graphs", ()) or ()), + ) + if isinstance(found, dict) and found.get("promoted") and found.get("arm") == "batched_eager": + held = batched_graph_sizes(state) + if held is not None and int(size) in held: + return dict( + found, + promoted = False, + reason = "the eager arm won, but a batch-size graph recorded since could replay this size", + ) + return found + + +def _effective_verdict( + verdict: dict, + size: int, + state: Any, + layout: Any = None, +) -> dict: + """The verdict as it applies now: one won on the graphed arm holds only while a batch-size graph recorded at its + own canvas exists (user calls never record one; graphs key on tensor shapes, so a same-size graph of another canvas + serves nothing here) and for the prompt layout it was raced at (another T5 bucket has no graph at the same canvas); + otherwise the size is admitted only if the eager arm passed on its own. An unknown ``layout`` cannot establish a + matching graph, nor can a verdict without ``graph_canvas``.""" + if not isinstance(verdict, dict) or verdict.get("arm") != "batched": + return verdict + held = batched_graph_sizes(state) + if held is None: + return verdict # no step graphs: the graphed arm ran eager, or on block graphs that record on demand + same_layout = verdict.get("layout") is not None and layout_token(layout) == verdict.get( + "layout" + ) + if ( + int(size) in held + and same_layout + and batched_graph_canvas(state, size, verdict.get("graph_canvas")) + ): + return verdict + eager = (verdict.get("arms") or {}).get("batched_eager") + if isinstance(eager, dict): + # The neighbour check ran on the graphed arm: it vouches for nothing here, so no seeded joins either. + return dict( + verdict, + promoted = bool(eager.get("promoted")), + arm = "batched_eager", + path = "eager", + graph_missing = True, + neighbour_exact = False, + replay_exact = False, + b_exact = False, + ) + return dict(verdict, promoted = False, graph_missing = True) + + +def seeded_join_ok(verdict: Optional[dict]) -> bool: + """A seeded request may join a batch of this size only when the measured path is neighbour-exact (G2a) and its + row 0 is batch-exact against its solo render on the same path (``b_exact``; a verdict from before the check needs + ``replay_exact``): otherwise the returned seed would not reproduce the image.""" + if not ( + isinstance(verdict, dict) and verdict.get("promoted") and verdict.get("neighbour_exact") + ): + return False + if "b_exact" in verdict: + return bool(verdict.get("b_exact")) + return bool(verdict.get("replay_exact")) diff --git a/studio/backend/core/inference/diffusion_batch_trace.py b/studio/backend/core/inference/diffusion_batch_trace.py new file mode 100644 index 000000000000..711c161e4e27 --- /dev/null +++ b/studio/backend/core/inference/diffusion_batch_trace.py @@ -0,0 +1,139 @@ +# SPDX-License-Identifier: AGPL-3.0-only +# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0 + +"""Counters for how image requests share pipeline calls, reported on status as ``batch_trace``. + +Always on and O(1) per request: admissions, the idle direct dispatch, joins, realized call sizes, why a request +rendered alone, and the rows of every pipe call. Denoiser-level counts (invocations, rows, block executions) need +forward hooks, so they run only with ``UNSLOTH_STUDIO_IMAGE_BATCH_TRACE=1``: a pipeline that loops over the rows of +one call shows up there as invocations and block executions that grow with the rows.""" + +from __future__ import annotations + +import os +import threading +from contextlib import contextmanager +from typing import Any, Iterator + +TRACE_ENV = "UNSLOTH_STUDIO_IMAGE_BATCH_TRACE" + +_LOCK = threading.Lock() +_COUNTS: dict[str, int] = {} +_CALL_SIZES: dict[int, int] = {} +_PIPE_ROWS: dict[int, int] = {} +_FALLBACKS: dict[str, int] = {} +_DENOISER: dict[str, int] = {} + + +def hooks_enabled() -> bool: + return (os.environ.get(TRACE_ENV) or "").strip().lower() in ("1", "true", "yes", "on") + + +def count(name: str, by: int = 1) -> None: + with _LOCK: + _COUNTS[name] = _COUNTS.get(name, 0) + int(by) + + +def fallback(reason: str) -> None: + """A request that could have shared a call rendered alone, and why.""" + with _LOCK: + _FALLBACKS[reason] = _FALLBACKS.get(reason, 0) + 1 + + +def coalesced_call(requests: int, images: int) -> None: + with _LOCK: + _COUNTS["coalesced_calls"] = _COUNTS.get("coalesced_calls", 0) + 1 + _COUNTS["coalesced_requests"] = _COUNTS.get("coalesced_requests", 0) + int(requests) + _CALL_SIZES[int(images)] = _CALL_SIZES.get(int(images), 0) + 1 + + +def pipe_call(rows: int) -> None: + with _LOCK: + _COUNTS["pipe_calls"] = _COUNTS.get("pipe_calls", 0) + 1 + _COUNTS["pipe_rows"] = _COUNTS.get("pipe_rows", 0) + int(rows) + _PIPE_ROWS[int(rows)] = _PIPE_ROWS.get(int(rows), 0) + 1 + + +def snapshot() -> dict[str, Any]: + with _LOCK: + return { + "counts": dict(_COUNTS), + "call_sizes": {str(k): v for k, v in sorted(_CALL_SIZES.items())}, + "pipe_rows": {str(k): v for k, v in sorted(_PIPE_ROWS.items())}, + "fallbacks": dict(_FALLBACKS), + "denoiser": dict(_DENOISER), + "hooks": hooks_enabled(), + } + + +def reset() -> None: + with _LOCK: + for table in (_COUNTS, _CALL_SIZES, _PIPE_ROWS, _FALLBACKS, _DENOISER): + table.clear() + + +def _rows_of(args: tuple, kwargs: dict) -> int: + for value in (kwargs.get("hidden_states"), kwargs.get("sample"), kwargs.get("x"), *args[:1]): + shape = getattr(value, "shape", None) + if shape is not None and len(shape) > 0: + return int(shape[0]) + return 0 + + +def _block_lists(module: Any) -> list: + """The repeated-block containers of a denoiser (``transformer_blocks``, ``single_transformer_blocks``, ...).""" + try: + import torch.nn as nn + except Exception: # noqa: BLE001 - no torch: nothing to hook + return [] + found = [] + for name, child in getattr(module, "_modules", {}).items(): + if isinstance(child, nn.ModuleList) and len(child) and "block" in name: + found.append(child) + return found + + +@contextmanager +def denoiser_calls(pipe: Any, rows: int) -> Iterator[None]: + """Count this pipe call (always) and, with the trace env set, its denoiser invocations / rows / block runs.""" + pipe_call(rows) + if not hooks_enabled(): + yield + return + handles = [] + local = {"invocations": 0, "rows": 0, "block_runs": 0} + + def on_denoiser(_module: Any, args: tuple, kwargs: dict) -> None: + local["invocations"] += 1 + local["rows"] += _rows_of(args, kwargs) + + def on_block(_module: Any, _args: tuple) -> None: + local["block_runs"] += 1 + + for name in ("transformer", "transformer_2", "unet"): + module = getattr(pipe, name, None) + if module is None or not hasattr(module, "register_forward_pre_hook"): + continue + try: + handles.append(module.register_forward_pre_hook(on_denoiser, with_kwargs = True)) + for blocks in _block_lists(module): + for block in blocks: + handles.append(block.register_forward_pre_hook(on_block)) + except Exception: # noqa: BLE001 - a module that refuses hooks is simply not traced + continue + try: + yield + finally: + for handle in handles: + try: + handle.remove() + except Exception: # noqa: BLE001 + pass + with _LOCK: + _DENOISER["pipe_calls"] = _DENOISER.get("pipe_calls", 0) + 1 + _DENOISER["requested_rows"] = _DENOISER.get("requested_rows", 0) + int(rows) + for key, value in local.items(): + _DENOISER[key] = _DENOISER.get(key, 0) + value + last = f"last_call_rows_{int(rows)}" + _DENOISER[last + "_invocations"] = local["invocations"] + _DENOISER[last + "_block_runs"] = local["block_runs"] diff --git a/studio/backend/core/inference/diffusion_cuda_graph.py b/studio/backend/core/inference/diffusion_cuda_graph.py index c02767a16bad..6afb607e4f93 100644 --- a/studio/backend/core/inference/diffusion_cuda_graph.py +++ b/studio/backend/core/inference/diffusion_cuda_graph.py @@ -7,6 +7,7 @@ import collections import contextlib +import contextvars import gc import inspect import os @@ -50,6 +51,104 @@ def _bg_planned_replay_enabled() -> bool: # Per module. Legitimate second keys exist, but each costs a pool-sized slice of VRAM. MAX_GRAPHS_PER_MODULE = 4 +# Calls that carry several requests' images (image_request_batching): only these sizes record a graph of their own, +# next to the size-1 graphs, at most MAX_BATCHED_GRAPHS per module, and only where the caller allows a recording (an +# idle warm-up, never a user's request). A full cache never evicts for them; an OOM recording one drops only them. +BATCH_GRAPH_SIZES = (2, 4) +MAX_BATCHED_GRAPHS = 2 +# Extra pool a batched graph may take, in MiB; unset = what the card has free beyond BATCH_GRAPH_MARGIN_MB. +BATCH_GRAPH_POOL_ENV = "UNSLOTH_DIFFUSION_BATCH_GRAPH_POOL_MB" +BATCH_GRAPH_MARGIN_MB = 1024 +_BATCH_ROWS: "contextvars.ContextVar[Optional[tuple]]" = contextvars.ContextVar( + "unsloth_graph_batch_rows", default = None +) + + +_BATCH_CANVAS: "contextvars.ContextVar[Optional[str]]" = contextvars.ContextVar( + "unsloth_graph_batch_canvas", default = None +) + + +@contextlib.contextmanager +def batch_rows( + rows: int, + *, + capture: bool = False, + canvas: Optional[str] = None, +): + """Calls in this context carry ``rows`` requests; ``capture`` allows a new batched graph to record. ``canvas`` (the + batch race's shape token) labels every batched graph this context records or replays, so a verdict raced at one + canvas is never satisfied by a same-size graph of another (graphs key on tensor shapes).""" + token = _BATCH_ROWS.set((int(rows), bool(capture))) + canvas_token = _BATCH_CANVAS.set(None if canvas is None else str(canvas)) + try: + yield + finally: + _BATCH_CANVAS.reset(canvas_token) + _BATCH_ROWS.reset(token) + + +def current_batch_rows() -> Optional[tuple]: + return _BATCH_ROWS.get() + + +_FORCED_EAGER: "contextvars.ContextVar[bool]" = contextvars.ContextVar( + "unsloth_graph_forced_eager", default = False +) + + +@contextlib.contextmanager +def forced_eager(): + """Every graph handle runs eager in this context, whatever a caller's ``set_bypass(False)`` says (the batch race's + eager arm: generate() re-arms the graphs before each chunk).""" + token = _FORCED_EAGER.set(True) + try: + yield + finally: + _FORCED_EAGER.reset(token) + + +def eager_forced() -> bool: + return bool(_FORCED_EAGER.get()) + + +def _batch_pool_budget_bytes() -> Optional[int]: + raw = (os.environ.get(BATCH_GRAPH_POOL_ENV) or "").strip() + if not raw: + return None + try: + return max(0, int(float(raw) * 2**20)) + except ValueError: + return None + + +def _free_device_bytes(index: Optional[int] = None) -> Optional[int]: + """Free bytes on card ``index`` (the call's operands), else the current card.""" + try: + torch = _torch() + free, _total = ( + torch.cuda.mem_get_info() if index is None else torch.cuda.mem_get_info(index) + ) + return int(free) + except Exception: # noqa: BLE001 - unreadable: the recording's own OOM path still guards + return None + + +def _has_reference(kwargs: Any) -> bool: + """A call carrying edit reference states (an edit's image scope), as opposed to plain text-to-image.""" + return isinstance(kwargs, dict) and any( + kwargs.get(name) is not None for name in _REFERENCE_KWARGS + ) + + +def _is_oom(exc: BaseException) -> bool: + try: + from .diffusion_batched import is_oom_error + return bool(is_oom_error(exc)) + except Exception: # noqa: BLE001 + return "out of memory" in str(exc).lower() + + # Three per the PyTorch docs. The warmup forces lazy allocations OUTSIDE the capture. WARMUP_ITERS = 3 # A resident key's first real steps are its warm-ups, so no forward is run and thrown away before the recording (three @@ -827,24 +926,45 @@ def _has_float(key: tuple) -> bool: # Private pools per graph OOM a dual-DiT family; the graphs never replay concurrently, so share. _POOL_BOX: list = [None] +# Batch-size graphs (batch_rows > 1) record into their own pool, shared by every batched graph (both DiTs of a dual-DiT +# family included): torch frees a pool's blocks only once no graph uses it, so in the size-1 graphs' pool dropping the +# batched graphs would give back nothing. "shared" (env) records them beside the size-1 graphs instead. +BATCH_POOL_ENV = "UNSLOTH_DIFFUSION_BATCH_GRAPH_POOL" +_BATCH_POOL_BOX: list = [None] + + +def _batch_pool_split() -> bool: + return (os.environ.get(BATCH_POOL_ENV) or "split").strip().lower() != "shared" + + +def _pool_box() -> list: + """The pool box a capture in this context records into.""" + rows = _BATCH_ROWS.get() + if rows is not None and rows[0] > 1 and _batch_pool_split(): + return _BATCH_POOL_BOX + return _POOL_BOX + # A pool id handed to a capture after the last graph recorded into it died is a dangling pointer. _LIVE_WRAPPERS: "weakref.WeakSet" = weakref.WeakSet() def _drop_pool_if_unused() -> None: - """Drop shared pool id once no live graph uses it (else use_count assert); check per graph.""" - try: - pool = _POOL_BOX[0] - if pool is None: - return - for wrapper in tuple(_LIVE_WRAPPERS): - for entry in tuple(wrapper.cache.values()): - if getattr(entry, "pool_token", pool) == pool: # handles are fresh tuples per call - return - _POOL_BOX[0] = None - except Exception: # noqa: BLE001 - pass + """Drop each shared pool id once no live graph uses it (else use_count assert); check per graph.""" + for box in (_POOL_BOX, _BATCH_POOL_BOX): + try: + pool = box[0] + if pool is None: + continue + if any( + getattr(entry, "pool_token", pool) == pool # handles are fresh tuples per call + for wrapper in tuple(_LIVE_WRAPPERS) + for entry in tuple(wrapper.cache.values()) + ): + continue + box[0] = None + except Exception: # noqa: BLE001 + pass # A failed capture (torch >= 2.11) pins its graph and pool forever via the host allocator. @@ -940,8 +1060,9 @@ def retire_failed_capture( with _FAILED_LOCK: # A collision with another recording left nothing behind: kept alive, but not a failure the budget counts. (_COLLIDED_GRAPHS if begun_elsewhere else _FAILED_GRAPHS).append(graph) - if pool is not None and _POOL_BOX[0] == pool: - _POOL_BOX[0] = None + for box in (_POOL_BOX, _BATCH_POOL_BOX): + if pool is not None and box[0] == pool: + box[0] = None if not begun_elsewhere: note_pool_retired() # whatever the failed recording took stays cached until the next capture's entry flush @@ -1012,6 +1133,34 @@ def _allocator_segments() -> list: return snapshot["segments"] +def _pool_id_bytes(pool: Any) -> int: + """Device bytes pool id ``pool`` holds now, 0 if unreadable or None.""" + if pool is None: + return 0 + try: + want = tuple(pool) + return sum( + int(seg.get("total_size", 0)) + for seg in _allocator_segments() + if tuple(seg.get("segment_pool_id") or ()) == want + ) + except Exception: # noqa: BLE001 + return 0 + + +def _first_device_index(args: tuple, kwargs: dict) -> Optional[int]: + torch = _torch() + for value in (*args, *kwargs.values()): + index = ( + getattr(getattr(value, "device", None), "index", None) + if torch.is_tensor(value) + else None + ) + if index is not None: # a CPU operand says nothing about the card + return index + return None + + def _pool_bytes(graph: Any) -> int: """Device bytes the graph's private pool holds (shared by every graph of the load), 0 if unreadable.""" try: @@ -1358,7 +1507,16 @@ def __init__( "evictions": 0, "speed_eager": 0, "length_eager": 0, + "batch_captures": 0, + "batch_eager": 0, + "batch_capture_failures": 0, } + # Graph keys recorded inside a coalesced call -> its request count (batch_rows); every other key is size 1. + self._batched: dict = {} + # Batched graph key -> the race canvas tokens it served (batch_rows ``canvas``); read only beside _batched. + self._batched_canvas: dict = {} + # Why this load records no more batched graphs (an OOM recording one), else None. + self._batched_off: Optional[str] = None self.valid_token: Any = None # A text-length-keyed denoiser would record a graph per prompt; each image scope records # lengths only in its first render, sealed once a graph replays or the render ends, then @@ -1470,10 +1628,96 @@ def _release(self) -> None: # the recordings ran on their own capture stream, whose cuBLAS workspace outlives them release_cached_outside_capture(clear_cublas = getattr(self, "placement", None) is not None) + def _invalidate_for_placement(self, token: Any) -> None: + """The recorded graphs replay the weight addresses of the placement they saw; a new placement records anew.""" + if self.cache: + self.stats["invalidations"] += 1 + # Not reset(): empty_cache re-pays cudaMallocs; pool stays with allocator. + dropped = [getattr(e, "pool_token", None) for e in self.cache.values()] + self.cache.clear() + _note_dropped_pools(dropped) # the next capture flushes it before it records + _drop_pool_if_unused() # the next capture must not record into a pool no graph holds + getattr(self, "_batched", {}).clear() + getattr(self, "_edit_keys", set()).clear() + self._warmed.clear() + self.valid_token = token + + def _unbatched_count(self) -> int: + batched = getattr(self, "_batched", {}) + return sum(1 for k in self.cache if k not in batched) + + def _eviction_victim(self, incoming_edit: bool) -> Any: + """The least recently replayed size-1 graph a full planned cache may drop for a new size-1 key, else None: an + edit's first; an edit never drops a text-to-image graph. Batched graphs have their own budget.""" + batched = getattr(self, "_batched", {}) + edits = getattr(self, "_edit_keys", set()) + victim = next((k for k in self.cache if k in edits and k not in batched), None) + if victim is not None or incoming_edit: + return victim + return next((k for k in self.cache if k not in batched), None) + + def _batched_refusal( + self, + rows: tuple, + device: Optional[int] = None, + ) -> Optional[str]: + """Why a call carrying ``rows`` requests may not record a new graph here, else None.""" + count, capture = rows + if getattr(self, "_batched_off", None): + return self._batched_off + if not capture: + return "no recording on a user's request" + if getattr(self, "placement", None) is not None: + # A failed recording under an offload placement poisons the whole load; only resident loads record them. + return "offloaded denoiser: batched calls run eager" + if count not in BATCH_GRAPH_SIZES: + return f"batch size {count} has no graph" + batched = getattr(self, "_batched", {}) + if sum(1 for k in batched if k in self.cache) >= MAX_BATCHED_GRAPHS: + return "batched graph cap reached" + # Priced from the size-1 graph's own pool growth, not the whole shared pool. + need = int(self.stats.get("size1_graph_bytes", 0) or 0) * count + budget = _batch_pool_budget_bytes() + if budget is not None and need > budget: + return "over the batched graph pool budget" + free = _free_device_bytes(device) + if free is not None and need and need > free - BATCH_GRAPH_MARGIN_MB * 2**20: + return "not enough free memory for a batched graph" + return None + + def drop_batched(self, size: Optional[int] = None) -> int: + """Drop the batched graphs (of ``size`` only, when given); the size-1 graphs stay. Returns how many. Their memory + goes back only from their own pool (the default): with ``BATCH_POOL_ENV=shared`` the size-1 graphs keep the one + pool alive and nothing returns to the card.""" + batched = getattr(self, "_batched", {}) + keys = [k for k, v in batched.items() if size is None or v == int(size)] + gone = [getattr(self.cache.pop(k), "pool_token", None) for k in keys if k in self.cache] + for k in keys: + batched.pop(k, None) + if gone: + _note_dropped_pools(gone) + _drop_pool_if_unused() + self._release() + return len(gone) + + def _drop_batched(self, reason: Optional[str] = None) -> None: + batched = getattr(self, "_batched", {}) + gone = [ + getattr(self.cache.pop(k), "pool_token", None) for k in list(batched) if k in self.cache + ] + batched.clear() + if reason is not None: + self._batched_off = reason + if gone: + _note_dropped_pools(gone) + _drop_pool_if_unused() + def reset(self) -> "GraphedForward": """Drop every captured graph (weights changed under us: LoRA load, unload, adapter switch).""" dropped = bool(self.cache) self.cache.clear() + getattr(self, "_batched", {}).clear() + getattr(self, "_edit_keys", set()).clear() if dropped: note_pool_retired() # counted where it drops; the _release below flushes and acknowledges it self._recorded.clear() @@ -1511,6 +1755,7 @@ def poison(self, exc: BaseException) -> "GraphedForward": # pool slices; caller's _release frees both once the failed capture's frames are gone. dropped = [getattr(e, "pool_token", None) for e in self.cache.values()] self.cache.clear() + getattr(self, "_batched", {}).clear() _note_dropped_pools(dropped) _drop_pool_if_unused() return self @@ -1545,6 +1790,10 @@ def describe(self) -> dict: "max_graphs": int(self.max_graphs), "cap_hit": bool(self.cap_hit), "length_sealed": bool(getattr(self, "length_sealed", False)), + "batched_graphs": sorted( + v for k, v in getattr(self, "_batched", {}).items() if k in self.cache + ), + "batched_off": getattr(self, "_batched_off", None), "placement": None if self.placement is None else self.placement.mode, "stats": dict(self.stats), "fallback": None @@ -1771,6 +2020,7 @@ def __call__(self, *args, **kwargs): not self.enabled or _bg_eager_forced() or self.bypassed + or _FORCED_EAGER.get() or self.poisoned # Belt to the caller's per-chunk bypass: one step's cond and uncond share a key. or getattr(self.module, "_unsloth_step_cache", None) @@ -1786,15 +2036,7 @@ def __call__(self, *args, **kwargs): # The recorded graphs replay the weight addresses of the placement they saw; a new placement records anew. token = self.placement.token() if token != self.valid_token: - if self.cache: - self.stats["invalidations"] += 1 - # Not reset(): empty_cache re-pays cudaMallocs; pool stays with allocator. - dropped = [getattr(e, "pool_token", None) for e in self.cache.values()] - self.cache.clear() - _note_dropped_pools(dropped) # the next capture flushes it before it records - _drop_pool_if_unused() # the next capture must not record into a pool no graph holds - self._warmed.clear() - self.valid_token = token + self._invalidate_for_placement(token) refusal = self.placement.refusal(self.stats) if self._judge and speed_check_enabled(): self._judge_keys() @@ -1886,6 +2128,14 @@ def __call__(self, *args, **kwargs): # Outside the key handler: an error in the eager forward propagates instead of running it twice. return self._eager(eager_args, eager_kwargs) + rows = _BATCH_ROWS.get() if entry is None else None + if rows is not None and rows[0] > 1: + refusal = self._batched_refusal(rows, _first_device_index(eager_args, eager_kwargs)) + if refusal is not None: + self.stats["batch_eager"] += 1 + return self._eager_as_recorded(eager_args, eager_kwargs) + else: + rows = None if entry is None: if _uncapturable(key): self.stats["refused_object"] += 1 @@ -1945,6 +2195,23 @@ def __call__(self, *args, **kwargs): warm_args, warm_kwargs = _rebuild(spec, self._statics(live)) return call(*warm_args, **warm_kwargs) except Exception as exc: # noqa: BLE001 - like a failed capture: never fails the render + if rows is not None and _is_oom(exc): + # Out of memory warming a batched shape (as when recording one): drop only the batched + # graphs, keep the size-1 ones, and run this step eager like the other unrecorded shapes. + self._real_warm_closed.add(key) + exc.__traceback__ = None + warm_args = warm_kwargs = live = None + self._drop_batched(f"out of memory warming a batch of {rows[0]}") + self.stats["batch_capture_failures"] += 1 + if self.logger is not None: + self.logger.warning( + "diffusion.cuda_graph: no memory to warm a batch-%d graph on %s; batched calls run " + "eager, the size-1 graphs keep replaying", + rows[0], + type(self.module).__name__, + ) + self._release() + return self._eager_as_recorded(eager_args, eager_kwargs) # Copies can OOM or fail: this load runs eager like after a failed capture. self.poison(exc) self.stats["fallbacks"] += 1 @@ -1974,14 +2241,26 @@ def __call__(self, *args, **kwargs): spec = _flatten((args, kwargs), live) warm_args, warm_kwargs = _rebuild(spec, self._statics(live)) return call(*warm_args, **warm_kwargs) - if len(self.cache) >= self.max_graphs and self.plan is not None: - # A planned call keys on the prompt length, so evict the least recently replayed graph. - gone = getattr(self.cache.pop(next(iter(self.cache))), "pool_token", None) + # Batched graphs have their own budget (MAX_BATCHED_GRAPHS): they never take a size-1 key's slot. + batched_here = rows is not None + victim = ( + self._eviction_victim(_has_reference(kwargs)) + if not batched_here + and self.plan is not None + and self._unbatched_count() >= self.max_graphs + else None + ) + if victim is not None: + # A planned call keys on the prompt length, so evict the least recently replayed graph: a batched one + # first, then an edit's; an edit never evicts a text-to-image graph (it runs ungraphed instead). + self._batched.pop(victim, None) + getattr(self, "_edit_keys", set()).discard(victim) + gone = getattr(self.cache.pop(victim), "pool_token", None) self.stats["evictions"] += 1 _note_dropped_pools([gone]) # The last graph on the shared pool takes the pool with it; never hand its id to the next capture. _drop_pool_if_unused() - if len(self.cache) >= self.max_graphs: + if not batched_here and self._unbatched_count() >= self.max_graphs: # The recorded graphs keep replaying: one rare new key is no reason to drop them. self.stats["cap_skips"] += 1 if not self.cap_hit: @@ -2013,6 +2292,21 @@ def __call__(self, *args, **kwargs): _restore_stream(stream_before) if "already recording" not in str(exc): _heal_generators() # before anything eager draws from the CUDA RNG + if rows is not None and self.placement is None and _is_oom(exc): + # Out of memory recording a batched graph: drop only the batched graphs, keep the size-1 ones. + self._drop_batched(f"out of memory recording a batch of {rows[0]}") + self.stats["batch_capture_failures"] += 1 + if self.logger is not None: + self.logger.warning( + "diffusion.cuda_graph: no memory for a batch-%d graph on %s; batched calls run eager, " + "the size-1 graphs keep replaying", + rows[0], + type(self.module).__name__, + ) + exc.__traceback__ = None + self._release() + # The size-1 graphs keep replaying: run like the other unrecorded shapes beside them. + return self._eager_as_recorded(eager_args, eager_kwargs) if self.placement is not None: self.placement.recover() # the eager retry must not wait on the dead capture's copies self.placement.release_slots() # nothing will replay into the ring for this load @@ -2034,6 +2328,15 @@ def __call__(self, *args, **kwargs): return self._eager(eager_args, eager_kwargs) entry = captured self.cache[key] = entry + if rows is not None: + self._batched[key] = rows[0] + canvas = _BATCH_CANVAS.get() + self.__dict__.setdefault("_batched_canvas", {})[key] = ( + set() if canvas is None else {canvas} + ) + self.stats["batch_captures"] += 1 + if _has_reference(kwargs): + self.__dict__.setdefault("_edit_keys", set()).add(key) if scope is not None: self._scope_captures[scope] = self._scope_captures.get(scope, 0) + 1 self._unsloth_capture_device = capture_device() @@ -2054,6 +2357,17 @@ def __call__(self, *args, **kwargs): self._sealed_scopes.add(scope) if self.plan is not None: self.cache[key] = self.cache.pop(key) + if key in getattr(self, "_batched", {}): + now = _BATCH_ROWS.get() + if now is None or now[0] <= 1: + # A size-1 call (true CFG has two rows too) replays this graph: it is a size-1 graph now. + self._batched.pop(key, None) + getattr(self, "_batched_canvas", {}).pop(key, None) + elif _BATCH_CANVAS.get() is not None: + # Same shapes at another race canvas (steps, guidance): this graph serves that one too. + self.__dict__.setdefault("_batched_canvas", {}).setdefault(key, set()).add( + _BATCH_CANVAS.get() + ) live: list = [] _flatten((args, kwargs), live) @@ -2258,7 +2572,9 @@ def _capture( graph = torch.cuda.CUDAGraph() # An explicit pool id, never None: a capture that fails must hand its pool back (retire_failed_capture). - pool = _POOL_BOX[0] + box = _pool_box() + pool = box[0] + pool_before = _pool_id_bytes(pool) if pool is None and callable(getattr(torch.cuda, "graph_pool_handle", None)): pool = torch.cuda.graph_pool_handle() recorder = _graph_without_flush if recapture else _graph_with_flush @@ -2278,19 +2594,26 @@ def _capture( if skip_stats is not None: skip.stats = skip_stats self.stats["pool_bytes"] = _pool_bytes(graph) + if _BATCH_ROWS.get() is None or _BATCH_ROWS.get()[0] <= 1: + # This size-1 graph's own pool growth: what a batch-k graph of it is priced from (k times). + grown = max(0, int(self.stats["pool_bytes"]) - int(pool_before)) + self.stats["size1_graph_bytes"] = max( + int(self.stats.get("size1_graph_bytes", 0)), grown + ) if key is not None: self._recorded[key] = None while len(self._recorded) > 4 * self.max_graphs: self._recorded.pop(next(iter(self._recorded))) - if _POOL_BOX[0] is None: + box = _pool_box() + if box[0] is None: try: - _POOL_BOX[0] = graph.pool() + box[0] = graph.pool() except Exception: # noqa: BLE001 - a private pool per graph still works pass entry.graph = graph # The pool this graph recorded into (see _drop_pool_if_unused), not whatever the box holds by now. - entry.pool_token = pool if pool is not None else _POOL_BOX[0] + entry.pool_token = pool if pool is not None else box[0] out_tensors: list = [] entry.out_spec = _flatten(out, out_tensors) entry.out_tensors = out_tensors @@ -3183,7 +3506,8 @@ def seal_lengths(handles: Any) -> None: def set_bypass(handles: Any, on: bool) -> None: - """Run eager without dropping graphs, for every handle.""" + """Run eager without dropping graphs, for every handle; inside ``forced_eager`` they stay bypassed.""" + on = bool(on) or eager_forced() for handle in handles or (): try: handle.set_bypass(on) diff --git a/studio/backend/core/inference/diffusion_vae_single_frame.py b/studio/backend/core/inference/diffusion_vae_single_frame.py index 50ef411343fe..54be7688de73 100644 --- a/studio/backend/core/inference/diffusion_vae_single_frame.py +++ b/studio/backend/core/inference/diffusion_vae_single_frame.py @@ -81,6 +81,16 @@ def _tiles(vae: Any, z: Any) -> bool: return z.shape[-1] > w or z.shape[-2] > h +def _coalesced_call() -> bool: + """Inside a call carrying several requests (image_request_batching through diffusion_cuda_graph.batch_rows).""" + try: + from .diffusion_cuda_graph import current_batch_rows + except Exception: # noqa: BLE001 + return False + rows = current_batch_rows() + return rows is not None and rows[0] > 1 + + def _fast_decode( self: Any, z: Any, @@ -91,6 +101,16 @@ def _fast_decode( return stock(z, return_dict = return_dict) import torch + if getattr(z, "shape", (1,))[0] > 1 and _coalesced_call(): + # Several requests' images: decode one at a time, like the strip decoder, so the peak is one feature map and + # each image decodes exactly as its own request would. + out = torch.cat([_fast_decode(self, part, return_dict = False)[0] for part in z.split(1)]) + if not return_dict: + return (out,) + from diffusers.models.autoencoders.vae import DecoderOutput + + return DecoderOutput(sample = out) + gate = self._unsloth_sf_gate gate.on = True try: diff --git a/studio/backend/core/inference/image_request_batching.py b/studio/backend/core/inference/image_request_batching.py index 638d6ed562b9..c346a19afbea 100644 --- a/studio/backend/core/inference/image_request_batching.py +++ b/studio/backend/core/inference/image_request_batching.py @@ -14,6 +14,7 @@ from loggers import get_logger +from . import diffusion_batch_trace as trace from .diffusion_batched import SEED_MASK logger = get_logger(__name__) @@ -28,6 +29,12 @@ class _RunAlone(Exception): """Retry this request individually.""" +# A member a fired batch could not take (no admitted size): it may coalesce again, behind that batch. +_LEFT_OUT_MSG = "left out" +_LEFT_OUT = object() +REJOIN_ROUNDS = 3 + + @dataclass class _Member: prompt: str @@ -136,8 +143,10 @@ async def _render_group( splittable: Optional[Callable[[BaseException], bool]], salvage: Optional[Callable[[BaseException], Optional[dict[str, Any]]]], fits: Optional[Callable[[int], bool]] = None, + adapter: Any = None, ) -> dict[int, dict[str, Any]]: - """One call for ``group``; on failure keep finished images and split the rest by member. Sizes respect ``fits``.""" + """One call for ``group``; on failure keep finished images and split the rest by member. Sizes respect ``fits``. + ``adapter`` (diffusion_batch_adapters.BatchAdapter) runs the call and splits it; None = the list call.""" group = [member for member in group if not member.future.done()] if fits is not None: group = _fitting_prefix(group, fits) @@ -145,9 +154,16 @@ async def _render_group( return {} prompts = [member.prompt for member in group for _ in member.seeds] seeds = [s for member in group for s in member.seeds] + owners = [member.owner for member in group] 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))} + if adapter is not None: + result = await adapter.denoise_batched(run_batch, prompts, seeds, owners) + parts = adapter.split(result, group) + else: + result = await run_batch(prompts, seeds, owners = owners) + parts = _split(result, group) + trace.coalesced_call(len(group), len(seeds)) + return {id(m): part for m, part in zip(group, parts)} except Exception as exc: # noqa: BLE001 -- keep what finished, split what can be split if shared_outcome(exc): raise @@ -166,13 +182,28 @@ async def _render_group( 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) - ) + split = len(rest) > 1 and splittable is not None and splittable(exc) + # The traceback pins the failed call's frames and every tensor they hold (an OOM's activations): drop it + # before the halves run, or they start with that memory still allocated. + _drop_tracebacks(exc) + del exc + if not split: return done + 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, adapter) + ) + return done + + +def _drop_tracebacks(exc: BaseException) -> None: + seen: set = set() + cur: Optional[BaseException] = exc + while cur is not None and id(cur) not in seen: + seen.add(id(cur)) + cur.__traceback__ = None + cur = cur.__cause__ or cur.__context__ def _close(batch: _Batch) -> None: @@ -207,6 +238,29 @@ async def _await_member( async def generate( + key: Hashable, + prompt: str, + n: int, + seed: Optional[int], + *, + on_rejoin: Optional[Callable[[], None]] = None, + **kwargs: Any, +) -> Optional[dict[str, Any]]: + """None = render alone. A member that a fired batch left out (its size was not admitted) coalesces again behind + that batch, at most ``REJOIN_ROUNDS`` times; ``on_rejoin`` runs first (the caller's busy signal then waits for the + generation running now). Keyword arguments as ``_generate_once``.""" + for _ in range(REJOIN_ROUNDS + 1): + result = await _generate_once(key, prompt, n, seed, **kwargs) + if result is not _LEFT_OUT: + return result + trace.count("rejoined") + if on_rejoin is not None: + on_rejoin() + trace.fallback("left out of the call") + return None + + +async def _generate_once( key: Hashable, prompt: str, n: int, @@ -223,10 +277,21 @@ async def generate( salvage: Optional[Callable[[BaseException], Optional[dict[str, Any]]]] = None, on_lead: Optional[Callable[[], None]] = None, wait: Optional[Callable[[], Awaitable[None]]] = None, + seeded_ok: Optional[Callable[[], bool]] = None, + adapter: Any = None, ) -> Optional[dict[str, Any]]: - """None = render alone. ``check`` raises when a joined member must leave.""" + """None = render alone. ``check`` raises when a joined member must leave. ``seeded_ok``: an explicitly seeded + request may join (a measured neighbour-exact path); the env switch still opts every seeded request in.""" cap = batch_max() - if cap <= 1 or n >= cap or (seed is not None and not seeded_join_enabled()): + if cap <= 1 or n >= cap: + trace.fallback("over the batch cap") + return None + if ( + seed is not None + and not seeded_join_enabled() + and not (seeded_ok is not None and seeded_ok()) + ): + trace.fallback("explicit seed") return None loop = asyncio.get_running_loop() batch = _OPEN.get(key) @@ -235,20 +300,27 @@ async def generate( member = _Member(prompt, request_seeds(seed, n), loop.create_future(), owner) batch.members.append(member) batch.images += n + trace.count("joined") 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: + except _RunAlone as exc: + if exc.args == (_LEFT_OUT_MSG,): + return _LEFT_OUT + trace.fallback("render failed, retried alone") return None _close(batch) if not busy(): + trace.fallback("slot free") return None batch = _OPEN[key] = _Batch(key) batch.members.append(_Member(prompt, request_seeds(seed, n), loop.create_future(), owner)) batch.images = n + trace.count("led") + left_out: set = set() try: try: # Reserve the slot turn now so later arrivals cannot overtake the leader. @@ -268,11 +340,23 @@ async def generate( leader = batch.members[0] # A blank prompt fails the whole call: render it alone. if not leader.prompt.strip(): + trace.fallback("blank prompt") return None members = [member for member in batch.members if member.prompt.strip()] if fits is not None: members = _fitting_prefix(members, fits) + taken = {id(member) for member in members} if len(members) > 1 else set() + left_out = { + id(member) + for member in batch.members[1:] + if id(member) not in taken and member.prompt.strip() + } + # Told now, not after the call: they coalesce again behind it while it runs. + for member in batch.members[1:]: + if id(member) in left_out and not member.future.done(): + member.future.set_exception(_RunAlone(_LEFT_OUT_MSG)) if len(members) <= 1: + trace.fallback("no admitted batch size" if len(batch.members) > 1 else "nobody joined") return None logger.info( "images.batch: %d requests from %d accounts render as one call of %d images", @@ -282,7 +366,7 @@ async def generate( ) try: done = await _render_group( - members, run_batch, shared_outcome, splittable, salvage, fits + members, run_batch, shared_outcome, splittable, salvage, fits, adapter ) except Exception as exc: _share(exc, members[1:], owner) @@ -297,4 +381,6 @@ async def generate( batch.fired = True for member in batch.members[1:]: if not member.future.done(): - member.future.set_exception(_RunAlone()) + member.future.set_exception( + _RunAlone(_LEFT_OUT_MSG) if id(member) in left_out else _RunAlone() + ) diff --git a/studio/backend/models/inference.py b/studio/backend/models/inference.py index 10eb007ab840..7cb21148b82a 100644 --- a/studio/backend/models/inference.py +++ b/studio/backend/models/inference.py @@ -6577,8 +6577,15 @@ class DiffusionStatusResponse(BaseModel): 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.", + "'compiled_sizes' (static compile, only batch sizes already compiled), 'measured' (an idle race measured a faster " + "shared call on this card: only the winning batch sizes and shapes) or 'serial' (every request renders alone), " + "with the reason; null when nothing is loaded.", + ) + batch_trace: Optional[Dict[str, Any]] = Field( + None, + description = "Process counters for request batching: requests admitted, idle direct dispatches, joins, " + "realized call sizes, why requests rendered alone, rows per pipeline call, and (with " + "UNSLOTH_STUDIO_IMAGE_BATCH_TRACE=1) denoiser invocations, rows and block executions.", ) fp8_gemm: Optional[Dict[str, Any]] = Field( None, diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.py index 0f9e3c6daf75..656492037c0c 100644 --- a/studio/backend/routes/inference.py +++ b/studio/backend/routes/inference.py @@ -56593,6 +56593,15 @@ def _follow_up_pass(): _COALESCE_KEY_IGNORED = frozenset({"live_preview"}) +def _callable_takes(fn: Any, name: str) -> bool: + import inspect + try: + params = inspect.signature(fn).parameters + except (TypeError, ValueError): + return False + return name in params or any(p.kind is inspect.Parameter.VAR_KEYWORD for p in params.values()) + + async def _coalesced_image_generate( backend: Any, status: Optional[dict], @@ -56603,12 +56612,13 @@ async def _coalesced_image_generate( generate_kwargs: dict, ) -> Optional[dict]: """Join a batch while a render runs; None = render alone. ``generate_kwargs`` all go into the key.""" + from core.inference import diffusion_batch_trace as batch_trace 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_batch_adapters import admits_without_pipe + from core.inference.diffusion_cuda_graph import batch_rows from core.inference.diffusion_families import detect_family - from core.inference.diffusion_flux3 import FLUX3_FAMILY_NAMES from core.inference.generation_ticket import ( GenerationTicket, TicketStopEvent, @@ -56618,19 +56628,27 @@ async def _coalesced_image_generate( holder = getattr(backend, "generation_holder", None) if holder is None or active_engine_name() != ENGINE_DIFFUSERS: return None + batch_trace.count("admitted") if not image_request_batching.collecting(): try: if holder() is None: + # Idle: dispatch now, before any key, policy, status read or timer. + batch_trace.count("idle_direct") 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") - 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 family: + try: + fused = admits_without_pipe(detect_family("", family)) + except Exception: # noqa: BLE001 -- an unknown family renders alone + fused = False + if not fused: + # FLUX.3, Anima, layered and the other families that loop one image per forward, unless they say so. + batch_trace.fallback("family renders one image per forward") + return None if generate_kwargs.get("expected_load") is None: # Pin to the model read here, so a swapped model is refused rather than rendering every member. from core.inference.diffusion_families import load_identity @@ -56646,6 +56664,7 @@ async def _coalesced_image_generate( if plan is not None: decided = await asyncio.to_thread(plan, prompt, bool(loras)) if decided is None: + batch_trace.fallback("engine policy or prompt layout") return None prompt_key, private = decided else: @@ -56704,7 +56723,8 @@ async def run_batch( # Row 0 may be another account's image, so a cross-account batch 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")): + # A user's call never records a batch-size graph (only an idle race does): an unrecorded size runs eager. + with generation_ticket(ticket), _reserved_turn(lead.get("turn")), batch_rows(len(seeds)): try: return await runner( backend.generate, @@ -56760,16 +56780,62 @@ def salvage(exc: BaseException) -> Optional[dict]: } sizes_of = getattr(backend, "coalesce_batch_sizes", None) + shape_kwargs = {} + if sizes_of is not None and _callable_takes(sizes_of, "guidance"): + shape_kwargs["guidance"] = generate_kwargs.get("guidance") + if sizes_of is not None and _callable_takes(sizes_of, "steps"): + shape_kwargs["steps"] = generate_kwargs.get("steps") + if sizes_of is not None and _callable_takes(sizes_of, "layout"): + # A verdict won by graph replay holds only for the prompt layout it was raced at. + shape_kwargs["layout"] = prompt_key def fits(total: int) -> bool: if sizes_of is None: return True try: - sizes = sizes_of(generate_kwargs.get("width"), generate_kwargs.get("height")) + sizes = sizes_of( + generate_kwargs.get("width"), generate_kwargs.get("height"), **shape_kwargs + ) except Exception: # noqa: BLE001 -- unknown shapes: render alone return False return sizes is None or total in sizes + if sizes_of is not None: + try: + admitted = await asyncio.to_thread( + sizes_of, + generate_kwargs.get("width"), + generate_kwargs.get("height"), + **shape_kwargs, + ) + except Exception: # noqa: BLE001 -- unknown shapes: render alone + admitted = frozenset() + if admitted is not None and not any(size > n for size in admitted): + # No batch size this request could be part of at this shape: never wait to coalesce. + batch_trace.fallback("no admitted batch size at this shape") + return None + + seeded_of = getattr(backend, "coalesce_seeded_ok", None) + seeded_steps = seeded_of is not None and _callable_takes(seeded_of, "steps") + seeded_layout = seeded_of is not None and _callable_takes(seeded_of, "layout") + + def seeded_ok() -> bool: + if seeded_of is None: + return False + try: + return bool( + seeded_of( + generate_kwargs.get("width"), + generate_kwargs.get("height"), + generate_kwargs.get("guidance"), + n, + **({"steps": generate_kwargs.get("steps")} if seeded_steps else {}), + **({"layout": prompt_key} if seeded_layout else {}), + ) + ) + except Exception: # noqa: BLE001 -- unknown: a seeded request renders alone + return False + waiter = getattr(backend, "generation_waiter", None) rider = getattr(backend, "generation_rider", None) @@ -56790,6 +56856,9 @@ async def _coalesce_in_line() -> Optional[dict]: salvage = salvage, on_lead = on_lead, wait = wait, + seeded_ok = seeded_ok, + # Left out of a fired batch: coalesce again behind the generation running now. + on_rejoin = arrived_behind.clear, ) # 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(): @@ -56815,6 +56884,65 @@ async def _coalesce_in_line() -> Optional[dict]: backend.release_slot_turn(lead["turn"]) +class ImageBatchRaceRequest(BaseModel): + width: Optional[int] = None + height: Optional[int] = None + steps: Optional[int] = None + guidance: Optional[float] = None + sizes: Optional[list[int]] = None + repeats: int = 5 + accuracy: bool = True + + +@studio_router.post("/images/batching/race") +async def images_batching_race( + body: Optional[ImageBatchRaceRequest] = None, + current_subject: str = Depends(get_current_subject), +): + """Explicit warm-up: on an idle engine, race serial against batched calls for the loaded model at this shape and + persist the verdicts that decide whether concurrent requests share a call. Owner only; 409 when a request holds + or waits for the slot (the race never runs on a user's request).""" + from core.inference.diffusion_batch_race import RACE_SIZES, RaceRefused, invalid_race_sizes + from core.inference.diffusion_engine_router import ( + ENGINE_DIFFUSERS, + active_engine_name, + get_active_diffusion_engine, + ) + + if account_access.managed_account(): + raise HTTPException(status_code = 403, detail = "Only the owner can run the batching race.") + body = body or ImageBatchRaceRequest() + bad = invalid_race_sizes(body.sizes) + if bad: + raise HTTPException(status_code = 422, detail = bad) + backend = get_active_diffusion_engine() + race = getattr(backend, "batch_race", None) + if race is None or active_engine_name() != ENGINE_DIFFUSERS: + raise HTTPException( + status_code = 409, detail = "The active image engine does not batch requests." + ) + status = await asyncio.to_thread(backend.status) + if not status.get("loaded"): + raise HTTPException(status_code = 409, detail = "No image model is loaded.") + steps, guidance = await asyncio.to_thread(_image_generation_defaults, status) + try: + report = await asyncio.to_thread( + functools.partial( + race, + width = int(body.width or 1024), + height = int(body.height or 1024), + steps = int(body.steps or steps), + guidance = float(guidance if body.guidance is None else body.guidance), + sizes = tuple(body.sizes or RACE_SIZES), + repeats = max(1, min(int(body.repeats), 20)), + accuracy = bool(body.accuracy), + ) + ) + except RaceRefused as exc: + raise HTTPException(status_code = 409, detail = str(exc)) + return {"race": report, "request_batching": backend.request_batching()} + + async def _batched_openai_images( backend: Any, status: dict, diff --git a/studio/backend/tests/test_diffusion_cuda_graph.py b/studio/backend/tests/test_diffusion_cuda_graph.py index 56f603efd2e7..1a3c7f0fb3a2 100644 --- a/studio/backend/tests/test_diffusion_cuda_graph.py +++ b/studio/backend/tests/test_diffusion_cuda_graph.py @@ -206,6 +206,7 @@ def stub_torch(monkeypatch): def _clean_module_globals(): """The shared pool and the live-wrapper set are process-wide, so no test may inherit them.""" cg._POOL_BOX[0] = None + cg._BATCH_POOL_BOX[0] = None cg._LIVE_WRAPPERS.clear() cg._CAPTURE_STREAMS.clear() yield @@ -2478,3 +2479,418 @@ def forward( assert module.runs == steps + cg.WARMUP_ITERS + 1 finally: handle.disable() + + +# ---------------------------------------------------------------- batched (coalesced) graph keys + + +@side_stream +def test_a_users_coalesced_call_never_records_a_batched_graph(stub_torch): + handle = _armed() + with cg.batch_rows(2): + handle(_t((2, 4)), timestep = _t((2,)), return_dict = False) + assert handle.stats["captures"] == 0 + assert handle.stats["batch_eager"] == 1 + assert handle.cache == {} + + +@side_stream +def test_a_race_records_batch_sizes_two_and_four_next_to_size_one(stub_torch): + handle = _armed() + handle(_t((1, 4)), timestep = _t((1,)), return_dict = False) + with cg.batch_rows(2, capture = True): + handle(_t((2, 4)), timestep = _t((2,)), return_dict = False) + with cg.batch_rows(3, capture = True): + handle(_t((3, 4)), timestep = _t((3,)), return_dict = False) + with cg.batch_rows(4, capture = True): + handle(_t((4, 4)), timestep = _t((4,)), return_dict = False) + assert handle.stats["captures"] == 3 + assert handle.stats["batch_captures"] == 2 + assert sorted(handle._batched.values()) == [2, 4] + assert handle.describe()["batched_graphs"] == [2, 4] + # A recorded batch size replays inside a user's call (no recording needed). + before = handle.stats["replays"] + with cg.batch_rows(2): + handle(_t((2, 4)), timestep = _t((2,)), return_dict = False) + assert handle.stats["replays"] == before + 1 + + +@side_stream +def test_batched_graphs_have_their_own_budget_beside_the_size_one_graphs(stub_torch): + """A full size-1 cache neither blocks a batch-size graph nor loses a slot to one, and the other way round: batch + graphs never take a size-1 prompt-length variant's slot.""" + handle = cg.GraphedForward(_FakeDiT(), max_graphs = 2).enable() + handle(_t((1, 4)), timestep = _t((1,)), return_dict = False) + handle(_t((1, 8)), timestep = _t((1,)), return_dict = False) + keys = set(handle.cache) + for rows in (4, 2): + with cg.batch_rows(rows, capture = True): + handle(_t((rows, 4)), timestep = _t((rows,)), return_dict = False) + assert keys <= set(handle.cache) and len(handle.cache) == 4 + assert handle.stats["batch_captures"] == 2 and handle.stats["evictions"] == 0 + # A third size-1 shape: the size-1 budget is full (cap skip), the batched graphs are not taken. + handle(_t((1, 16)), timestep = _t((1,)), return_dict = False) + assert handle.stats["cap_skips"] == 1 and len(handle.cache) == 4 + with cg.batch_rows(2, capture = True): + handle(_t((2, 8)), timestep = _t((2,)), return_dict = False) + assert handle.stats["batch_eager"] == 1, "the batched budget is full" + + +@side_stream +def test_batched_graphs_record_into_their_own_pool_unless_shared(stub_torch, monkeypatch): + """torch frees a pool's blocks only once no graph uses it: in the size-1 graphs' pool, dropping the batched graphs + would give nothing back.""" + cg._BATCH_POOL_BOX[0] = None + handle = _armed() + handle(_t((1, 4)), timestep = _t((1,)), return_dict = False) + with cg.batch_rows(2, capture = True): + handle(_t((2, 4)), timestep = _t((2,)), return_dict = False) + with cg.batch_rows(4, capture = True): + handle(_t((4, 4)), timestep = _t((4,)), return_dict = False) + single = [e.pool_token for k, e in handle.cache.items() if k not in handle._batched] + batched = {e.pool_token for k, e in handle.cache.items() if k in handle._batched} + assert ( + len(batched) == 1 and single[0] not in batched + ), "one pool for every batched graph, apart from size 1" + handle.drop_batched() + assert cg._BATCH_POOL_BOX[0] is None and cg._POOL_BOX[0] is not None + cg._BATCH_POOL_BOX[0] = None + monkeypatch.setenv(cg.BATCH_POOL_ENV, "shared") + other = _armed() + other(_t((1, 4)), timestep = _t((1,)), return_dict = False) + with cg.batch_rows(2, capture = True): + other(_t((2, 4)), timestep = _t((2,)), return_dict = False) + assert len({e.pool_token for e in other.cache.values()}) == 1 + cg._BATCH_POOL_BOX[0] = None + + +@side_stream +def test_out_of_memory_recording_a_batch_drops_only_the_batched_graphs(stub_torch): + module = _FakeDiT() + handle = _armed(module) + handle(_t((1, 4)), timestep = _t((1,)), return_dict = False) + with cg.batch_rows(2, capture = True): + handle(_t((2, 4)), timestep = _t((2,)), return_dict = False) + assert handle.stats["batch_captures"] == 1 + stub_torch._records["graph_error"] = RuntimeError( + "CUDA out of memory. Tried to allocate 2.00 GiB" + ) + with cg.batch_rows(4, capture = True): + out = handle(_t((4, 4)), timestep = _t((4,)), return_dict = False) + assert out[0].value[0] == "out" + assert handle.poisoned is False + assert handle.stats["batch_capture_failures"] == 1 + assert len(handle.cache) == 1 and not handle._batched, "only the size-1 graph is left" + assert handle._batched_off + replays = handle.stats["replays"] + handle(_t((1, 4)), timestep = _t((1,)), return_dict = False) + assert handle.stats["replays"] == replays + 1, "the size-1 graph still replays" + with cg.batch_rows(2, capture = True): + handle(_t((2, 4)), timestep = _t((2,)), return_dict = False) + assert handle.stats["batch_eager"] == 1, "no more batched recordings on this load" + + +@side_stream +def test_a_size_one_capture_failure_still_poisons(stub_torch): + stub_torch._records["graph_error"] = RuntimeError("CUDA out of memory") + handle = _armed() + handle(_t((1, 4)), timestep = _t((1,)), return_dict = False) + assert handle.poisoned is True + + +@side_stream +def test_the_batched_pool_budget_refuses_a_recording(stub_torch, monkeypatch): + handle = _armed() + handle(_t((1, 4)), timestep = _t((1,)), return_dict = False) + handle.stats["size1_graph_bytes"] = 512 * 2**20 + monkeypatch.setenv(cg.BATCH_GRAPH_POOL_ENV, "600") + with cg.batch_rows(2, capture = True): + handle(_t((2, 4)), timestep = _t((2,)), return_dict = False) + assert handle.stats["batch_captures"] == 0 and handle.stats["batch_eager"] == 1 + monkeypatch.setenv(cg.BATCH_GRAPH_POOL_ENV, "2048") + with cg.batch_rows(2, capture = True): + handle(_t((2, 4)), timestep = _t((2,)), return_dict = False) + assert handle.stats["batch_captures"] == 1 + + +@side_stream +def test_a_plain_multi_image_request_keeps_todays_graph_rules(stub_torch): + """No batch_rows context (one user's batch_size=2): records as before.""" + handle = _armed() + handle(_t((2, 4)), timestep = _t((2,)), return_dict = False) + assert handle.stats["captures"] == 1 and handle.stats["batch_captures"] == 0 + + +@side_stream +def test_dropping_one_batch_size_keeps_the_others_and_size_one(stub_torch): + handle = _armed() + handle(_t((1, 4)), timestep = _t((1,)), return_dict = False) + for rows in (2, 4): + with cg.batch_rows(rows, capture = True): + handle(_t((rows, 4)), timestep = _t((rows,)), return_dict = False) + assert handle.drop_batched(2) == 1 + assert sorted(handle._batched.values()) == [4] and len(handle.cache) == 2 + assert handle.drop_batched() == 1 and len(handle.cache) == 1 + + +class _EditRefDiT(_LenDiT): + """A planned (Qwen-Image-2.1-style) step that also takes edit reference states.""" + + def forward( + self, + hidden_states, + encoder_hidden_states = None, + image_cond_hidden_states = None, + return_dict = True, + ): + self.calls += 1 + return (_FakeTensor((1, 64), value = ("out", hidden_states.value), tag = "out"),) + + +def _t2i_step( + handle, + rows = 1, + value = 0.0, +): + return handle( + _t((rows, 64), value = value), encoder_hidden_states = _t((rows, 3)), return_dict = False + ) + + +def _edit_step( + handle, + ref_len, + value = 0.0, +): + return handle( + _t((1, 64), value = value), + encoder_hidden_states = _t((1, 3)), + image_cond_hidden_states = _t((1, ref_len)), + return_dict = False, + ) + + +@side_stream +def test_edits_at_new_reference_sizes_never_evict_the_text_to_image_graphs(stub_torch, monkeypatch): + """Warm text-to-image at sizes 1, 2 and 4 (2 and 4 recorded by the race), then edits at three new reference sizes, + then text-to-image again: the edits take the batched graphs' slots and then run ungraphed, never the size-1 + text-to-image graph, so the next plain render replays instead of warming and recording again.""" + import contextlib + + monkeypatch.delenv(cg.EVERY_LENGTH_ENV, raising = False) + module = type("QwenImage21Transformer2DModel", (_EditRefDiT,), {})() + handle = _armed(module) + orig = handle.orig + handle.plan = lambda mod, args, kwargs: (orig, {"hidden_states": args[0], **kwargs}) + monkeypatch.setattr(_FakeTensor, "is_inference", lambda self: False, raising = False) + monkeypatch.setattr( + stub_torch, "inference_mode", lambda *a, **k: contextlib.nullcontext(), raising = False + ) + monkeypatch.setattr(cg, "_graph_without_flush", stub_torch.cuda.graph) + + for i in range(3): + _t2i_step(handle, 1, value = float(i)) + for rows in (2, 4): + with cg.batch_rows(rows, capture = True): + for i in range(3): + _t2i_step(handle, rows, value = float(i)) + assert len(handle.cache) == 3 and sorted(handle._batched.values()) == [2, 4] + plain = next(k for k in handle.cache if k not in handle._batched) + for ref_len in (16, 24, 32): + for i in range(3): + _edit_step(handle, ref_len, value = float(i)) + print("captures", handle.stats["captures"], "evictions", handle.stats["evictions"]) + assert plain in handle.cache, "an edit evicted the size-1 text-to-image graph" + replays = handle.stats["replays"] + captures = handle.stats["captures"] + _t2i_step(handle, 1, value = 9.0) + assert handle.stats["replays"] == replays + 1 and handle.stats["captures"] == captures + + +@side_stream +def test_true_cfg_edits_at_new_reference_sizes_never_evict_the_text_to_image_graphs( + stub_torch, monkeypatch +): + """The same with true CFG (a prompt and a negative key per render): three edit reference sizes are six new keys.""" + import contextlib + + monkeypatch.delenv(cg.EVERY_LENGTH_ENV, raising = False) + module = type("QwenImage21Transformer2DModel", (_EditRefDiT,), {})() + handle = _armed(module) + orig = handle.orig + handle.plan = lambda mod, args, kwargs: (orig, {"hidden_states": args[0], **kwargs}) + monkeypatch.setattr(_FakeTensor, "is_inference", lambda self: False, raising = False) + monkeypatch.setattr( + stub_torch, "inference_mode", lambda *a, **k: contextlib.nullcontext(), raising = False + ) + monkeypatch.setattr(cg, "_graph_without_flush", stub_torch.cuda.graph) + + def t2i(value): + handle(_t((1, 64), value = value), encoder_hidden_states = _t((1, 3)), return_dict = False) + handle(_t((1, 64), value = value), encoder_hidden_states = _t((1, 7)), return_dict = False) + + def edit(ref_len, value): + for text in (3, 7): + handle( + _t((1, 64), value = value), + encoder_hidden_states = _t((1, text)), + image_cond_hidden_states = _t((1, ref_len)), + return_dict = False, + ) + + for i in range(3): + t2i(float(i)) + plain = set(handle.cache) + assert len(plain) == 2 + for ref_len in (16, 24, 32): + for i in range(3): + edit(ref_len, float(i)) + print( + "captures", + handle.stats["captures"], + "evictions", + handle.stats["evictions"], + "cap_skips", + handle.stats["cap_skips"], + ) + assert plain <= set(handle.cache), "an edit evicted a text-to-image graph" + replays, captures = handle.stats["replays"], handle.stats["captures"] + t2i(9.0) + assert handle.stats["replays"] == replays + 2 and handle.stats["captures"] == captures + + +# ---------------------------------------------------------------- kernel / graph rule review (#19837) + + +@side_stream +def test_a_placement_change_forgets_the_batched_labels(stub_torch): + """A placement token change clears every graph: the batched labels go with them (no stale size-k bookkeeping).""" + handle = _armed() + handle(_t((1, 4)), timestep = _t((1,)), return_dict = False) + with cg.batch_rows(2, capture = True): + handle(_t((2, 4)), timestep = _t((2,)), return_dict = False) + assert handle._batched + handle.placement = types.SimpleNamespace( + token = lambda: "moved", refusal = lambda stats: None, mode = "model" + ) + handle.valid_token = "before" + handle._invalidate_for_placement("moved") + assert handle.cache == {} and handle._batched == {} + + +@side_stream +def test_a_graph_a_size_one_call_also_replays_is_not_a_batched_graph(stub_torch): + """Two requests without CFG and one request with true CFG can share a graph key (two rows either way): once a + size-1 call replays it, dropping the batched graphs (a lost race) must not take it away.""" + handle = _armed() + with cg.batch_rows(2, capture = True): + handle(_t((2, 4)), timestep = _t((2,)), return_dict = False) + assert sorted(handle._batched.values()) == [2] + handle(_t((2, 4)), timestep = _t((2,)), return_dict = False) # a size-1 true-CFG step, same shapes + assert handle.drop_batched(2) == 0 and len(handle.cache) == 1 + + +@side_stream +def test_batched_admission_prices_the_size_one_graph_not_the_whole_pool(stub_torch, monkeypatch): + """need = the size-1 graph's own pool growth x k: a pool already holding other graphs does not make batch 4 + look unaffordable.""" + # The shared pool holds 5 GiB before the size-1 capture and 5 GiB + 256 MiB after it. + monkeypatch.setattr(cg, "_pool_bytes", lambda graph: 5 * 2**30 + 256 * 2**20) + monkeypatch.setattr(cg, "_pool_id_bytes", lambda pool: 5 * 2**30) + handle = _armed() + handle(_t((1, 4)), timestep = _t((1,)), return_dict = False) + assert handle.stats["size1_graph_bytes"] == 256 * 2**20 + seen = [] + monkeypatch.setattr( + cg, "_free_device_bytes", lambda index = None: seen.append(index) or 4 * 2**30 + ) + monkeypatch.setenv(cg.BATCH_GRAPH_POOL_ENV, "2048") + with cg.batch_rows(4, capture = True): + handle(_t((4, 4), device_index = 1), timestep = _t((4,), device_index = 1), return_dict = False) + assert ( + handle.stats["batch_captures"] == 1 + ), "1 GiB for batch 4 fits a 2 GiB budget and 4 GiB free" + assert seen == [1], "free memory is read on the card the call runs on" + + +@side_stream +def test_a_placed_load_records_no_batched_graph(stub_torch): + """Under an offload placement a failed batched recording would poison the whole load: no batched graphs there.""" + handle = _armed() + handle.placement = types.SimpleNamespace(mode = "group") + assert handle._batched_refusal((2, True)) is not None + + +@side_stream +def test_out_of_memory_recording_a_batch_falls_back_like_the_other_recorded_shapes( + stub_torch, monkeypatch +): + handle = _armed() + handle(_t((1, 4)), timestep = _t((1,)), return_dict = False) + used = [] + real = handle._eager_as_recorded + monkeypatch.setattr(handle, "_eager_as_recorded", lambda a, k: used.append(1) or real(a, k)) + stub_torch._records["graph_error"] = RuntimeError("CUDA out of memory") + with cg.batch_rows(2, capture = True): + handle(_t((2, 4)), timestep = _t((2,)), return_dict = False) + assert used == [1] and handle.poisoned is False + + +@side_stream +def test_a_batched_graph_carries_the_race_canvas_it_recorded_and_replayed_at(stub_torch): + """The batch race labels its batched graphs with its canvas token; a same-shape replay under another race canvas + adds that label, a size-1 replay clears it with the batched mark, and a user's call never labels.""" + handle = _armed() + with cg.batch_rows(2, capture = True, canvas = "c512"): + handle(_t((2, 4)), timestep = _t((2,)), return_dict = False) + [key] = list(handle._batched) + assert handle._batched_canvas[key] == {"c512"} + with cg.batch_rows(2): + handle(_t((2, 4)), timestep = _t((2,)), return_dict = False) + assert handle._batched_canvas[key] == {"c512"} + with cg.batch_rows(2, capture = True, canvas = "c512-steps8"): + handle(_t((2, 4)), timestep = _t((2,)), return_dict = False) + assert handle._batched_canvas[key] == {"c512", "c512-steps8"} + handle(_t((2, 4)), timestep = _t((2,)), return_dict = False) + assert key not in handle._batched and key not in handle._batched_canvas + + +def test_out_of_memory_in_a_batched_real_warmup_keeps_the_size_one_graphs(stub_torch, monkeypatch): + """With real warm-ups (the default) a new batch shape warms on copies first; an OOM there must not poison the + load: only the batched graphs go, the size-1 graph keeps replaying (an optional batching race never slows solo + requests for the rest of the load).""" + monkeypatch.delenv(cg.REAL_WARMUP_ENV, raising = False) + module = _FakeDiT() + handle = _armed(module) + cg.note_render_steps((handle,), 8) + for i in range(cg.WARMUP_ITERS + 1): + handle(_t(value = float(i)), timestep = _t((1,), value = 10.0), return_dict = False) + assert handle.stats["captures"] == 1 and len(handle.cache) == 1 + statics = handle._statics + + def oom_for_a_batch(live): + if any(getattr(t, "shape", (1,))[0] == 4 for t in live): + raise RuntimeError("CUDA out of memory. Tried to allocate 2.00 GiB") + return statics(live) + + monkeypatch.setattr(handle, "_statics", oom_for_a_batch) + with cg.batch_rows(4, capture = True): + out = handle(_t((4, 4), value = 3.0), timestep = _t((4,), value = 10.0), return_dict = False) + assert out[0].value[0] == "out", "the batched step still renders (eager)" + assert handle.poisoned is False + assert len(handle.cache) == 1 and not handle._batched, "the size-1 graph is kept" + assert handle.stats["batch_capture_failures"] == 1 and handle._batched_off + replays = handle.stats["replays"] + handle(_t(value = 7.0), timestep = _t((1,), value = 10.0), return_dict = False) + assert handle.stats["replays"] == replays + 1, "the size-1 graph still replays" + + +def test_out_of_memory_in_a_size_one_real_warmup_still_poisons(stub_torch, monkeypatch): + monkeypatch.delenv(cg.REAL_WARMUP_ENV, raising = False) + handle = _armed() + cg.note_render_steps((handle,), 8) + monkeypatch.setattr( + handle, "_statics", lambda live: (_ for _ in ()).throw(RuntimeError("CUDA out of memory")) + ) + handle(_t(value = 1.0), timestep = _t((1,), value = 10.0), return_dict = False) + assert handle.poisoned is True diff --git a/studio/backend/tests/test_diffusion_cuda_graph_batch_gpu.py b/studio/backend/tests/test_diffusion_cuda_graph_batch_gpu.py new file mode 100644 index 000000000000..21735f7aa705 --- /dev/null +++ b/studio/backend/tests/test_diffusion_cuda_graph_batch_gpu.py @@ -0,0 +1,94 @@ +# SPDX-License-Identifier: AGPL-3.0-only +# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0 + +"""Batch-size graphs on a real card: a size-2 graph recorded next to the size-1 one replays with no host sync +(torch.cuda.set_sync_debug_mode("error") after the warm-ups), in the batched graphs' own pool, matching the eager +step.""" + +from __future__ import annotations + +import pytest + +torch = pytest.importorskip("torch") + +pytestmark = [ + pytest.mark.gpu, + pytest.mark.skipif(not torch.cuda.is_available(), reason = "needs a CUDA card"), +] + +from core.inference import diffusion_cuda_graph as cg # noqa: E402 + + +class _TinyDiT(torch.nn.Module): + def __init__(self): + super().__init__() + self.proj = torch.nn.Linear(64, 64) + self.out = torch.nn.Linear(64, 64) + + def forward( + self, + hidden_states, + timestep = None, + return_dict = True, + ): + h = torch.nn.functional.gelu(self.proj(hidden_states)) + timestep[:, None, None] + return (self.out(h),) + + +@pytest.fixture(autouse = True) +def _clean(): + cg._POOL_BOX[0] = None + cg._BATCH_POOL_BOX[0] = None + cg._LIVE_WRAPPERS.clear() + cg._CAPTURE_STREAMS.clear() + yield + torch.cuda.set_sync_debug_mode(0) + cg._POOL_BOX[0] = None + cg._BATCH_POOL_BOX[0] = None + cg._LIVE_WRAPPERS.clear() + cg._CAPTURE_STREAMS.clear() + + +def _inputs(rows: int, seed: int): + g = torch.Generator(device = "cuda").manual_seed(seed) + x = torch.randn(rows, 16, 64, device = "cuda", generator = g) + t = torch.rand(rows, device = "cuda", generator = g) + return x, t + + +@torch.no_grad() +def test_size_two_graph_replays_without_a_host_sync_next_to_size_one(monkeypatch): + monkeypatch.setenv(cg.REAL_WARMUP_ENV, "0") + module = _TinyDiT().cuda().eval() + handle = cg.GraphedForward(module).enable() + # Warm-ups and recordings (the race's idle warm-up for size 2). + for seed in range(cg.WARMUP_ITERS + 2): + x, t = _inputs(1, seed) + handle(x, timestep = t, return_dict = False) + with cg.batch_rows(2, capture = True): + x2, t2 = _inputs(2, 100 + seed) + handle(x2, timestep = t2, return_dict = False) + torch.cuda.synchronize() + assert handle.stats["batch_captures"] == 1 and len(handle.cache) == 2 + assert not handle.poisoned + single = {e.pool_token for k, e in handle.cache.items() if k not in handle._batched} + batched = {e.pool_token for k, e in handle.cache.items() if k in handle._batched} + assert ( + len(single) == 1 and len(batched) == 1 and not single & batched + ), "batched graphs have their own pool" + + x1, t1 = _inputs(1, 7) + x2, t2 = _inputs(2, 8) + want1 = module(x1, timestep = t1, return_dict = False)[0] + want2 = module(x2, timestep = t2, return_dict = False)[0] + torch.cuda.synchronize() + replays = handle.stats["replays"] + torch.cuda.set_sync_debug_mode("error") + got1 = handle(x1, timestep = t1, return_dict = False)[0] + with cg.batch_rows(2): + got2 = handle(x2, timestep = t2, return_dict = False)[0] + torch.cuda.set_sync_debug_mode(0) + torch.cuda.synchronize() + assert handle.stats["replays"] == replays + 2 + assert torch.allclose(got1, want1, rtol = 1e-4, atol = 1e-5) + assert torch.allclose(got2, want2, rtol = 1e-4, atol = 1e-5) diff --git a/studio/backend/tests/test_diffusion_static_skip.py b/studio/backend/tests/test_diffusion_static_skip.py index 9a8329c44d86..031882f3f57c 100644 --- a/studio/backend/tests/test_diffusion_static_skip.py +++ b/studio/backend/tests/test_diffusion_static_skip.py @@ -961,3 +961,26 @@ def test_planned_skips_survive_the_post_render_reset(): ss.reset_static_step_skip(pipe, None) stats = ss.static_skip_stats(pipe) assert stats["stats"]["skipped"] == stats["planned_skips"] == 9 + + +def test_a_forced_eager_scope_survives_the_per_chunk_graph_reset( + fake_runtime, tmp_path, monkeypatch +): + """generate() re-arms the graphs before every chunk (set_bypass False without a step cache): the race's eager arm + must still run eager through the real chunk path.""" + from core.inference import diffusion as dmod + + (tmp_path / "model.gguf").write_bytes(b"weights") + backend = dmod.DiffusionBackend() + _load_into(backend, tmp_path) + seen = [] + handle = types.SimpleNamespace(set_bypass = lambda on: seen.append(bool(on))) + object.__setattr__(backend._state, "cuda_graphs", (handle,)) + monkeypatch.setattr(dmod.cuda_graph, "note_render_steps", lambda *a, **k: None) + with cg.forced_eager(): + backend.generate(prompt = "a sloth", steps = 25) + assert seen and all(seen), seen + seen.clear() + backend.generate(prompt = "a sloth", steps = 25) + assert seen == [False] + backend.unload() diff --git a/studio/backend/tests/test_diffusion_vae_single_frame.py b/studio/backend/tests/test_diffusion_vae_single_frame.py index 221fa7aa2db6..616e404ca546 100644 --- a/studio/backend/tests/test_diffusion_vae_single_frame.py +++ b/studio/backend/tests/test_diffusion_vae_single_frame.py @@ -131,3 +131,27 @@ def test_compile_cache_key_matches_the_later_vae_compile(monkeypatch, single_fra applied = ds.apply_speed_optims(pipe, target, is_gguf = False, family = family, speed_mode = mode) assert applied["compiled_vae_decode"] is key, (mode, single_frame, compile_env) assert ds.vae_decode_compile_allowed(pipe, mode) is key + + +def test_a_coalesced_call_decodes_each_image_like_its_own_request(): + """Several requests in one call: one image per decoder pass (one feature map at a time), each bit-identical to the + image decoded alone; a single user's multi-image call keeps its one batched pass.""" + from core.inference import diffusion_cuda_graph as cg + + fast = _tiny_vae() + assert sf.install(fast) is True + passes = [] + real = fast.decoder.forward + fast.decoder.forward = lambda x, *a, **k: passes.append(x.shape[0]) or real(x, *a, **k) + z = torch.randn(3, 4, 1, 16, 16) + with torch.no_grad(): + alone = [fast._decode(z[i : i + 1]).sample for i in range(3)] + passes.clear() + with cg.batch_rows(3): + together = fast._decode(z).sample + assert passes == [1, 1, 1] + for i in range(3): + assert torch.equal(together[i : i + 1], alone[i]) + passes.clear() + fast._decode(z) + assert passes == [3] diff --git a/studio/backend/tests/test_image_batch_infra.py b/studio/backend/tests/test_image_batch_infra.py new file mode 100644 index 000000000000..b3ec72309856 --- /dev/null +++ b/studio/backend/tests/test_image_batch_infra.py @@ -0,0 +1,1325 @@ +# SPDX-License-Identifier: AGPL-3.0-only +# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0 + +"""Batching infrastructure: the per-family capability, the measured race verdicts that may lift today's serial rules, +the seeded-join gate, the trace counters and the idle direct dispatch.""" + +from __future__ import annotations + +import asyncio +import sys +import types +from pathlib import Path + +import httpx +import pytest + +from core.inference import diffusion_batch_adapters as adapters +from core.inference import diffusion_batch_race as race +from core.inference import diffusion_batch_trace as trace +from core.inference import image_request_batching as batching + +sys.path.insert(0, str(Path(__file__).resolve().parent)) +from test_image_batching_followups import ( # noqa: E402 + _alone, + _groups, + _interleaved, + _plan, + _qwen21_pipe, +) +from test_image_concurrency import ( # noqa: E402,F401 (fixture) + _batched_calls, + _post_while_rendering, + studio, +) + + +@pytest.fixture(autouse = True) +def _fresh_trace(): + trace.reset() + yield + trace.reset() + + +@pytest.fixture(autouse = True) +def _quality_passes(monkeypatch): + # These tests are about the speed race; the G2c quality gate has its own (test_image_batch_quality). + from core.inference import diffusion_batch_quality as quality + monkeypatch.setattr(quality, "quality_ok", lambda state, path: True) + monkeypatch.setattr(quality, "any_quality_ok", lambda state: True) + + +# ------------------------------------------------------------------------------------------- capability + + +@pytest.mark.parametrize( + "name", + ["flux.3-klein", "flux.3-klein-base", "anima", "minimax-h3-image", "moss-image"], +) +def test_families_that_loop_one_image_per_forward_default_to_serial(name): + from core.inference.diffusion_flux3 import FLUX3_FAMILY_NAMES + + if name.startswith("flux.3"): + name = FLUX3_FAMILY_NAMES[0 if name == "flux.3-klein" else 1] + family = types.SimpleNamespace(name = name) + assert adapters.batched_forward(family) is False + assert adapters.adapter_for(family) is None + # The family saying so lifts the refusal (angle B's batched forward). + assert adapters.batched_forward(types.SimpleNamespace(name = name, batched_forward = True)) is True + + +def test_layered_and_qwen21_default_to_serial_and_others_batch(): + assert ( + adapters.batched_forward(types.SimpleNamespace(name = "qwen-image-layered", layer_count = 2)) + is False + ) + assert ( + adapters.batched_forward(types.SimpleNamespace(name = "qwen-image"), _qwen21_pipe()) is False + ) + assert adapters.batched_forward(types.SimpleNamespace(name = "qwen-image"), None) is True + assert adapters.batched_forward(types.SimpleNamespace(name = "z-image")) is True + # A family can also opt out. + assert ( + adapters.batched_forward(types.SimpleNamespace(name = "z-image", batched_forward = False)) + is False + ) + assert adapters.adapter_for(types.SimpleNamespace(name = "z-image")) is adapters.DEFAULT_ADAPTER + + +def test_the_key_refusal_follows_the_capability(): + from core.inference.diffusion import coalesce_prompt_key + + assert ( + coalesce_prompt_key(types.SimpleNamespace(name = "minimax-h3-image"), None, "a fox") is None + ) + assert coalesce_prompt_key(types.SimpleNamespace(name = "moss-image"), None, "a fox") is None + assert ( + coalesce_prompt_key(types.SimpleNamespace(name = "qwen-image"), _qwen21_pipe(), "a fox") + is None + ) + lifted = types.SimpleNamespace(name = "minimax-h3-image", batched_forward = True) + assert coalesce_prompt_key(lifted, None, "a fox") == () + q21 = types.SimpleNamespace(name = "qwen-image", batched_forward = True) + assert coalesce_prompt_key(q21, _qwen21_pipe(), "a fox") == () + + +def test_a_family_adapter_sets_its_own_layout_key(): + from core.inference.diffusion import coalesce_prompt_key + + class Lengths(adapters.BatchAdapter): + name = "lengths" + tokenizes = False + + def prepare(self, family, pipe, prompt): + return ("words", len(prompt.split())) + + family = types.SimpleNamespace(name = "qwen-image", batched_forward = True, batch_adapter = Lengths()) + assert coalesce_prompt_key(family, _qwen21_pipe(), "a red fox") == ("words", 3) + assert coalesce_prompt_key(family, _qwen21_pipe(), "a fox") != coalesce_prompt_key( + family, _qwen21_pipe(), "a red fox" + ) + + +def test_in_request_chunks_follow_the_capability(): + from core.inference.diffusion import _generation_chunks + from core.inference.diffusion_flux3 import FLUX3_FAMILY_NAMES + + jobs = [("a", 1), ("b", 2), ("c", 3)] + flux3 = types.SimpleNamespace(name = FLUX3_FAMILY_NAMES[0]) + assert _generation_chunks(flux3, jobs, 0) == [[j] for j in jobs] + fused = types.SimpleNamespace(name = FLUX3_FAMILY_NAMES[0], batched_forward = True) + assert _generation_chunks(fused, jobs, 0) == [jobs] + # MiniMax-H3 / MOSS keep one call per request (their lockstep / per-sample loops share the upload): unchanged. + for name in ("minimax-h3-image", "moss-image"): + assert _generation_chunks(types.SimpleNamespace(name = name), jobs, 0) == [jobs] + + +def test_a_family_that_says_it_fuses_batches_through_the_route(studio): + from core.inference.diffusion_flux3 import FLUX3_FAMILY_NAMES + + app, backend, _saved = studio + name = FLUX3_FAMILY_NAMES[0] + backend.status = lambda: { + "loaded": True, + "repo_id": "x/flux3", + "family": name, + "base_repo": None, + } + import core.inference.diffusion_families as families + + real = families.detect_family + family = types.SimpleNamespace(name = name, batched_forward = True) + families.detect_family = lambda *a, **k: family + try: + _plan(backend, family, None, offload_policy = "group") + responses = _post_while_rendering(app, backend, _interleaved("a fox", "a cat"), waiting = 2) + finally: + families.detect_family = real + assert all(r.status_code == 200 for r in responses) + assert _groups(backend) == [sorted(["a fox", "a cat"])] + + +def test_a_flux3_load_without_the_capability_renders_alone_and_says_why(studio): + from core.inference.diffusion_flux3 import FLUX3_FAMILY_NAMES + + app, backend, _saved = studio + name = FLUX3_FAMILY_NAMES[0] + backend.status = lambda: { + "loaded": True, + "repo_id": "x/flux3", + "family": name, + "base_repo": None, + } + _plan(backend, types.SimpleNamespace(name = name), None, offload_policy = "group") + + async def run(): + transport = httpx.ASGITransport(app = app) + async with httpx.AsyncClient(transport = transport, base_url = "http://studio") as client: + backend.rendering = True + out = [] + for path, account, body in _interleaved("a fox", "a cat"): + # Finishes while another render holds the slot: it never waited to join a batch. + out.append( + await asyncio.wait_for( + client.post(path, json = body, headers = {"x-test-account": account}), timeout = 5 + ) + ) + backend.rendering = False + return out + + responses = asyncio.run(run()) + assert all(r.status_code == 200 for r in responses) + assert _alone(backend) == ["a fox", "a cat"] + assert _batched_calls(backend) == [] + assert trace.snapshot()["fallbacks"].get("family renders one image per forward") == 2 + + +# ------------------------------------------------------------------------------------------- policy + + +def _engine(**state): + from core.inference.diffusion import DiffusionBackend + + engine = DiffusionBackend() + base = dict( + family = types.SimpleNamespace(name = "flux.2-klein"), + pipe = None, + speed_optims = (), + speed_mode = "off", + cuda_graphs = (), + compile_cache_ctx = None, + offload_policy = "none", + ) + base.update(state) + engine._state = types.SimpleNamespace(**base) + return engine + + +def _verdicts(monkeypatch, table): + monkeypatch.setattr( + race, + "lookup", + lambda state, w, h, g, sizes, steps = None: {k: v for k, v in table.items() if k in sizes}, + ) + monkeypatch.setattr( + race, "any_promoted", lambda state: any(v.get("promoted") for v in table.values()) + ) + + +def test_unmeasured_loads_keep_todays_rules(monkeypatch): + _verdicts(monkeypatch, {}) + resident = _engine() + assert resident.request_batching()["mode"] == "serial" + assert resident.coalesce_batch_sizes(1024, 1024) == frozenset() + graphs = _engine(offload_policy = "sequential", cuda_graphs = (object(),)) + assert graphs.request_batching()["mode"] == "serial" + streamed = _engine(offload_policy = "sequential") + assert streamed.request_batching()["mode"] == "any" + assert streamed.coalesce_batch_sizes(1024, 1024) is None + + +def test_a_measured_win_lifts_the_resident_and_graph_rules_to_the_winning_sizes(monkeypatch): + _verdicts(monkeypatch, {2: {"promoted": True}, 4: {"promoted": False}}) + for engine in (_engine(), _engine(offload_policy = "sequential", cuda_graphs = (object(),))): + policy = engine.request_batching() + assert policy["mode"] == "measured" and set(policy) == {"mode", "reason"} + assert engine.coalesce_batch_sizes(1024, 1024, 4.0) == frozenset({2}) + assert engine.coalesce_plan("a fox", False) == ((), False) + + +def test_a_measured_loss_drops_that_size_from_a_streamed_load(monkeypatch): + _verdicts(monkeypatch, {4: {"promoted": False}}) + engine = _engine(offload_policy = "sequential") + assert engine.request_batching()["mode"] == "any" + sizes = engine.coalesce_batch_sizes(1024, 1024) + assert 4 not in sizes and {2, 3, 5} <= sizes + + +def test_per_call_activation_scales_and_serial_families_stay_serial_whatever_was_measured( + monkeypatch, +): + import core.inference.diffusion as diffusion_module + + _verdicts(monkeypatch, {2: {"promoted": True}}) + monkeypatch.setattr( + diffusion_module, "_per_call_activation_scale", lambda state: "transformer.x" + ) + assert _engine().request_batching()["mode"] == "serial" + monkeypatch.setattr(diffusion_module, "_per_call_activation_scale", lambda state: None) + h3 = _engine(family = types.SimpleNamespace(name = "minimax-h3-image")) + assert h3.request_batching()["mode"] == "serial" + assert h3.coalesce_plan("a fox", False) is None + + +def test_seeded_requests_join_only_where_the_path_is_neighbour_and_replay_exact(monkeypatch): + engine = _engine() + _verdicts(monkeypatch, {2: {"promoted": True, "neighbour_exact": True, "replay_exact": False}}) + assert engine.coalesce_seeded_ok(1024, 1024, 4.0, 1) is False + _verdicts(monkeypatch, {2: {"promoted": True, "neighbour_exact": False, "replay_exact": True}}) + assert engine.coalesce_seeded_ok(1024, 1024, 4.0, 1) is False + _verdicts(monkeypatch, {2: {"promoted": True, "neighbour_exact": True, "replay_exact": True}}) + assert engine.coalesce_seeded_ok(1024, 1024, 4.0, 1) is True + _verdicts(monkeypatch, {}) + assert engine.coalesce_seeded_ok(1024, 1024, 4.0, 1) is False + + +def test_an_adapted_load_never_consumes_the_adapter_free_verdicts(monkeypatch): + _verdicts( + monkeypatch, + {2: {"promoted": True, "neighbour_exact": True, "replay_exact": True}}, + ) + applied = types.SimpleNamespace(_unsloth_loras = [("style", "default", 0.8)]) + at_load = types.SimpleNamespace(_unsloth_load_lora_specs = (("style", 0.8),)) + zeroed = types.SimpleNamespace(_unsloth_loras = [("style", "default", 0.0)]) + assert _engine().coalesce_batch_sizes(1024, 1024, 4.0) == frozenset({2}) + assert _engine(pipe = zeroed).coalesce_batch_sizes(1024, 1024, 4.0) == frozenset({2}) + for pipe in (applied, at_load): + engine = _engine(pipe = pipe) + # Today's rule for a resident load: serial, and no seeded join on the base model's exactness. + assert engine.coalesce_batch_sizes(1024, 1024, 4.0) == frozenset() + assert engine.coalesce_seeded_ok(1024, 1024, 4.0, 1) is False + streamed = _engine(pipe = pipe, offload_policy = "sequential") + assert streamed.coalesce_batch_sizes(1024, 1024, 4.0) is None + assert streamed.coalesce_seeded_ok(1024, 1024, 4.0, 1) is False + + +def test_a_seeded_request_joins_when_the_engine_says_its_path_is_exact(): + rendering = {"on": True} + calls = [] + + async def run_batch( + prompts, + seeds, + owners = None, + ): + calls.append(list(seeds)) + return {"images": list(prompts), "seeds": list(seeds), "seed": seeds[0]} + + async def run(seeded_ok): + rendering["on"] = True + tasks = [ + asyncio.ensure_future( + batching.generate( + "k", + prompt, + 1, + seed, + busy = lambda: rendering["on"], + run_batch = run_batch, + seeded_ok = seeded_ok, + ) + ) + for prompt, seed in (("a", 11), ("b", 22)) + ] + for _ in range(100): + await asyncio.sleep(0.01) + rendering["on"] = False + return await asyncio.gather(*tasks) + + assert asyncio.run(run(None)) == [None, None] + assert trace.snapshot()["fallbacks"]["explicit seed"] == 2 + results = asyncio.run(run(lambda: True)) + assert calls == [[11, 22]] + assert [r["seeds"] for r in results] == [[11], [22]] + assert trace.snapshot()["call_sizes"] == {"2": 1} + + +# ------------------------------------------------------------------------------------------- verdicts + + +def test_promotion_needs_the_lower_bound_and_enough_repeats(): + fast = [([1.0, 1.0], 1.5), ([1.02, 0.98], 1.49), ([0.99, 1.01], 1.52), ([1.0, 1.0], 1.5)] + verdict = race.judge(fast) + assert verdict["promoted"] is True and verdict["speedup_lb"] >= race.PROMOTE_LB + marginal = [([1.0, 1.0], 1.92), ([1.0, 1.0], 1.9), ([1.0, 1.0], 1.93), ([1.0, 1.0], 1.91)] + assert race.judge(marginal)["promoted"] is False # about 1.04x + assert race.judge(fast[:2])["promoted"] is False # fewer than MIN_REPEATS + noisy = [([1.0, 1.0], 1.2), ([1.0, 1.0], 2.3), ([1.0, 1.0], 1.3), ([1.0, 1.0], 2.2)] + assert race.judge(noisy)["promoted"] is False # median speedup above 1.05, lower bound below + + +def test_burst_latencies_price_the_wait_behind_earlier_requests(): + serial, batched = race.burst_latencies([1.0, 1.0, 1.0, 1.0], 3.0) + assert serial == [1.0, 2.0, 3.0, 4.0] and batched == [3.0] * 4 + assert race.percentile(serial, 95) == 4.0 and race.percentile(serial, 50) == 2.0 + + +def test_verdicts_round_trip_through_the_probe_cache_losers_included(monkeypatch, tmp_path): + import core.inference.diffusion_probe_cache as probe_cache + + monkeypatch.setattr(probe_cache, "_cache_file", lambda: tmp_path / "diffusion_quant_probe.json") + monkeypatch.setattr(probe_cache, "fingerprint", lambda card: {"card": card, "torch": "x"}) + race._STORE.clear() + race._UNIDENTIFIED.clear() + state = types.SimpleNamespace( + device = "cuda", + gpu_ordinal = 0, + family = types.SimpleNamespace(name = "flux.2-klein"), + pipe = None, + repo_id = "black-forest-labs/FLUX.2-klein-4B", + offload_policy = "none", + cuda_graphs = (), + speed_optims = (), + ) + assert race.lookup(state, 1024, 1024, 1.0, (2, 4)) == {} + assert race.record(state, 1024, 1024, 1.0, 2, {"promoted": True, "speedup_lb": 1.2}) + assert race.record(state, 1024, 1024, 1.0, 4, {"promoted": False, "speedup_lb": 0.9}) + race._STORE.clear() # a new process reads the file + found = race.lookup(state, 1024, 1024, 1.0, (2, 3, 4)) + assert found == { + 2: {"promoted": True, "speedup_lb": 1.2}, + 4: {"promoted": False, "speedup_lb": 0.9}, + } + assert race.any_promoted(state) is True + assert race.lookup(state, 768, 1024, 1.0, (2, 4)) == {} + assert ( + race.lookup(state, 1024, 1024, 1.0, (2, 4), steps = 28) == {} + ), "another step count is another verdict" + assert race.record(state, 1024, 1024, 1.0, 2, {"promoted": False}, steps = 28) + assert race.lookup(state, 1024, 1024, 1.0, (2,), steps = 28) == {2: {"promoted": False}} + assert race.lookup(state, 1024, 1024, 1.0, (2,))[2]["promoted"] is True + other = types.SimpleNamespace(**{**vars(state), "transformer_quant": "int8"}) + assert race.lookup(other, 1024, 1024, 1.0, (2, 4)) == {}, "another precision is another load" + race._STORE.clear() + + +def test_a_card_without_a_fingerprint_is_not_reprobed_on_every_status_poll(monkeypatch, tmp_path): + import core.inference.diffusion_probe_cache as probe_cache + + probes = [] + monkeypatch.setattr(probe_cache, "_cache_file", lambda: tmp_path / "diffusion_quant_probe.json") + monkeypatch.setattr(probe_cache, "fingerprint", lambda card: probes.append(card)) + race._STORE.clear() + race._UNIDENTIFIED.clear() + state = types.SimpleNamespace( + device = "cuda", gpu_ordinal = 0, cuda_graphs = (), offload_policy = "none" + ) + for _ in range(5): + assert race.lookup(state, 1024, 1024, 1.0, (2,)) == {} + assert race.any_promoted(state) is False + assert probes == ["cuda:0"] + race._STORE.clear() + race._UNIDENTIFIED.clear() + + +class _Image: + def __init__(self, value): + self.value = value + + def convert(self, _mode): + import numpy as np + return np.full((2, 2, 3), self.value % 251, dtype = "uint8") + + +def _fake_generate(cost, *, leak = False): + """Time per call from ``cost(rows)``; each image derives from its own (prompt, seed) unless ``leak``.""" + clock = {"t": 0.0} + calls = [] + + def generate( + prompt = None, + prompts = None, + seeds = None, + seed = None, + batch_size = 1, + **kwargs, + ): + rows = list(prompts) if prompts else [prompt] + row_seeds = list(seeds) if seeds else [seed] + calls.append(len(rows)) + clock["t"] += cost(len(rows)) + noise = sum(len(p) for p in rows) if leak and len(rows) > 1 else 0 + return {"images": [_Image(hash((p, s)) + noise) for p, s in zip(rows, row_seeds)]} + + return generate, clock, calls + + +def test_the_race_promotes_a_real_win_and_reports_an_exact_path(monkeypatch): + stored = {} + monkeypatch.setattr( + race, "record", lambda state, w, h, g, k, v, steps = None: stored.setdefault(k, v) is v + ) + generate, clock, calls = _fake_generate(lambda rows: 1.0 + 0.5 * (rows - 1)) + report = race.run_race( + generate, + types.SimpleNamespace(cuda_graphs = ()), + idle = lambda: True, + width = 512, + height = 512, + sizes = (2, 4), + repeats = 4, + clock = lambda: clock["t"], + ) + two, four = report["sizes"]["2"], report["sizes"]["4"] + assert list(report["sizes"]) == ["4", "2"], "the largest batch size records first" + assert two["promoted"] and four["promoted"] + assert two["neighbour_exact"] is True and two["replay_exact"] is True + assert set(stored) == {2, 4} + + +def test_the_race_catches_a_neighbour_leak_and_persists_a_loss(monkeypatch): + stored = {} + monkeypatch.setattr( + race, "record", lambda state, w, h, g, k, v, steps = None: stored.setdefault(k, v) is v + ) + generate, clock, _ = _fake_generate(lambda rows: float(rows), leak = True) + report = race.run_race( + generate, + types.SimpleNamespace(cuda_graphs = ()), + idle = lambda: True, + width = 512, + height = 512, + sizes = (2,), + repeats = 4, + clock = lambda: clock["t"], + ) + verdict = report["sizes"]["2"] + assert verdict["promoted"] is False and verdict["neighbour_exact"] is False + assert verdict["batched_graphs_dropped"] == 0 + assert stored[2]["promoted"] is False, "losers are persisted too" + assert race.seeded_join_ok(verdict) is False + + +def test_the_race_never_runs_on_a_busy_engine_and_stops_when_a_request_waits(monkeypatch): + stored = {} + monkeypatch.setattr( + race, "record", lambda state, w, h, g, k, v, steps = None: stored.setdefault(k, v) is v + ) + generate, clock, calls = _fake_generate(lambda rows: 1.0) + with pytest.raises(race.RaceRefused): + race.run_race(generate, types.SimpleNamespace(), idle = lambda: False, width = 512, height = 512) + assert calls == [] + budget = {"left": 5} + + def idle(): + budget["left"] -= 1 + return budget["left"] > 0 + + report = race.run_race( + generate, + types.SimpleNamespace(cuda_graphs = ()), + idle = idle, + width = 512, + height = 512, + sizes = (2,), + clock = lambda: clock["t"], + ) + assert report["aborted"] and stored == {} + + +def test_the_race_skips_a_size_a_static_compile_would_have_to_compile(monkeypatch): + monkeypatch.setattr(race, "record", lambda *a: True) + generate, clock, calls = _fake_generate(lambda rows: 1.0) + report = race.run_race( + generate, + types.SimpleNamespace(cuda_graphs = ()), + idle = lambda: True, + width = 512, + height = 512, + sizes = (3,), + allowed_sizes = lambda k: k in (2, 4), + clock = lambda: clock["t"], + ) + assert "skipped" in report["sizes"]["3"] and calls == [] + + +def test_the_engine_refuses_a_race_while_a_request_waits(): + import threading + + engine = _engine() + engine._queued_generate_cancels.add(threading.Event()) + with pytest.raises(race.RaceRefused): + engine.batch_race(width = 512, height = 512) + + +def test_the_engine_refuses_to_race_a_family_that_loops_one_image_per_forward(): + engine = _engine(family = types.SimpleNamespace(name = "moss-image")) + with pytest.raises(race.RaceRefused): + engine.batch_race(width = 512, height = 512) + + +def test_the_engine_race_records_its_batched_graphs_under_batch_rows(monkeypatch): + from core.inference import diffusion_cuda_graph as cg + + seen = [] + engine = _engine() + + def generate( + prompt = None, + prompts = None, + seeds = None, + seed = None, + **kwargs, + ): + seen.append(cg.current_batch_rows()) + rows = list(prompts) if prompts else [prompt] + return {"images": [_Image(hash((p, s))) for p, s in zip(rows, list(seeds or [seed]))]} + + engine.generate = generate + monkeypatch.setattr(race, "record", lambda *a: True) + engine.batch_race(width = 512, height = 512, sizes = (2,), repeats = 3) + assert (2, True) in seen and None in seen + + +# ------------------------------------------------------------------------------------------- trace + + +def test_idle_dispatch_reads_no_key_policy_or_status(monkeypatch): + """G1: a free slot dispatches at once: no status read, no prompt key, no policy, no timer.""" + from routes.inference import _coalesced_image_generate + + import core.inference.diffusion_engine_router as router + + monkeypatch.setattr(router, "active_engine_name", lambda: router.ENGINE_DIFFUSERS) + + def boom(*_a, **_k): + raise AssertionError("the idle path touched it") + + backend = types.SimpleNamespace( + generation_holder = lambda: None, + status = boom, + coalesce_plan = boom, + coalesce_batch_sizes = boom, + request_batching = boom, + ) + real_sleep = asyncio.sleep + + async def no_sleep(*_a, **_k): + raise AssertionError("the idle path waited") + + monkeypatch.setattr(asyncio, "sleep", no_sleep) + try: + result = asyncio.run( + _coalesced_image_generate( + backend, None, prompt = "a fox", n = 1, seed = None, generate_kwargs = {} + ) + ) + finally: + monkeypatch.setattr(asyncio, "sleep", real_sleep) + assert result is None + counts = trace.snapshot()["counts"] + assert counts["admitted"] == 1 and counts["idle_direct"] == 1 + + +def test_the_trace_counts_coalesced_calls_and_the_status_carries_it(studio): + app, backend, _saved = studio + _plan(backend, types.SimpleNamespace(name = "z-image"), None, offload_policy = "group") + responses = _post_while_rendering( + app, backend, _interleaved("a fox", "a cat", "an owl"), waiting = 3 + ) + assert all(r.status_code == 200 for r in responses) + snap = trace.snapshot() + assert snap["call_sizes"] == {"3": 1} + assert snap["counts"]["led"] == 1 and snap["counts"]["joined"] == 2 + assert snap["counts"]["coalesced_requests"] == 3 + from models.inference import DiffusionStatusResponse + + status = DiffusionStatusResponse(batch_trace = snap) + assert status.model_dump()["batch_trace"]["call_sizes"] == {"3": 1} + + +def _toy_pipe(looped: bool): + import torch + + class Block(torch.nn.Module): + def forward(self, x): + return x + 1 + + class DiT(torch.nn.Module): + def __init__(self): + super().__init__() + self.transformer_blocks = torch.nn.ModuleList([Block(), Block(), Block()]) + + def forward(self, hidden_states): + for block in self.transformer_blocks: + hidden_states = block(hidden_states) + return hidden_states + + class Pipe: + def __init__(self): + self.transformer = DiT() + + def __call__( + self, + rows: int, + steps: int = 2, + ): + x = torch.zeros(rows, 4) + for _ in range(steps): + if looped: + x = torch.cat( + [self.transformer(hidden_states = x[i : i + 1]) for i in range(rows)] + ) + else: + x = self.transformer(hidden_states = x) + return x + + return Pipe() + + +@pytest.mark.parametrize("looped", [False, True]) +def test_the_trace_tells_a_fused_call_from_a_pipeline_loop(monkeypatch, looped): + """G3: a list call that loops inside the pipeline shows invocations and block runs growing with the rows.""" + monkeypatch.setenv(trace.TRACE_ENV, "1") + pipe = _toy_pipe(looped) + with trace.denoiser_calls(pipe, 4): + pipe(4) + den = trace.snapshot()["denoiser"] + assert den["rows"] == 8 # 4 rows x 2 steps either way + per_step = den["invocations"] / 2 + assert per_step == (4 if looped else 1) + assert den["block_runs"] == (24 if looped else 6) + assert not pipe.transformer._forward_pre_hooks, "the hooks leave with the call" + + +def test_without_the_trace_env_no_hook_is_installed(monkeypatch): + monkeypatch.delenv(trace.TRACE_ENV, raising = False) + pipe = _toy_pipe(False) + seen = [] + real = pipe.transformer.register_forward_pre_hook + pipe.transformer.register_forward_pre_hook = lambda *a, **k: seen.append(1) or real(*a, **k) + with trace.denoiser_calls(pipe, 4): + pipe(4) + assert seen == [] + assert trace.snapshot()["pipe_rows"] == {"4": 1} + + +def test_a_losing_size_drops_its_batched_graphs(monkeypatch): + monkeypatch.setattr(race, "record", lambda *a: True) + dropped = [] + handle = types.SimpleNamespace( + drop_batched = lambda size: dropped.append(size) or 1, set_bypass = lambda on: None + ) + generate, clock, _ = _fake_generate(lambda rows: float(rows)) + report = race.run_race( + generate, + types.SimpleNamespace(cuda_graphs = (handle,)), + idle = lambda: True, + width = 512, + height = 512, + sizes = (2,), + repeats = 3, + accuracy = False, + clock = lambda: clock["t"], + ) + assert report["sizes"]["2"]["promoted"] is False + assert dropped == [2] and report["sizes"]["2"]["batched_graphs_dropped"] == 1 + + +def test_a_resident_load_with_a_measured_win_coalesces_at_the_winning_size_only( + studio, monkeypatch +): + """Three waiting requests and a promoted size of 2: one call of two, the third renders alone (2 + 1).""" + from core.inference.diffusion import DiffusionBackend + + app, backend, _saved = studio + _verdicts(monkeypatch, {2: {"promoted": True}, 4: {"promoted": False}}) + _plan(backend, types.SimpleNamespace(name = "z-image"), None, offload_policy = "none") + backend.coalesce_batch_sizes = types.MethodType(DiffusionBackend.coalesce_batch_sizes, backend) + responses = _post_while_rendering( + app, backend, _interleaved("a fox", "a cat", "an owl"), waiting = 3 + ) + assert all(r.status_code == 200 for r in responses) + assert [len(call["prompts"]) for call in _batched_calls(backend)] == [2] + assert len(_alone(backend)) == 1 + assert trace.snapshot()["call_sizes"] == {"2": 1} + + +def test_members_a_batch_left_out_coalesce_again_behind_it(): + """Admitted size 2, four requests waiting: two calls of two, nobody renders alone (the left-out pair waits for the + first call and then shares the next one).""" + state = {"blocker": True, "running": 0} + calls = [] + + async def run_batch( + prompts, + seeds, + owners = None, + ): + calls.append(list(prompts)) + state["running"] += 1 + try: + await asyncio.sleep(0.2) + finally: + state["running"] -= 1 + return {"images": list(prompts), "seeds": list(seeds), "seed": seeds[0]} + + def busy(): + return state["blocker"] or state["running"] > 0 + + async def run(): + tasks = [] + for prompt in ("a", "b", "c", "d"): + tasks.append( + asyncio.ensure_future( + batching.generate( + "k", + prompt, + 1, + None, + busy = busy, + run_batch = run_batch, + fits = lambda total: total == 2, + ) + ) + ) + await asyncio.sleep(0.02) + await asyncio.sleep(0.1) + state["blocker"] = False + return await asyncio.gather(*tasks) + + results = asyncio.run(run()) + assert sorted(map(sorted, calls)) == [["a", "b"], ["c", "d"]] + assert all(r is not None for r in results) + assert trace.snapshot()["counts"].get("rejoined", 0) >= 2 + + +def test_fbcache_decides_skips_from_the_whole_batch(): + """Why FBCache loads never coalesce: a row that alone would skip its blocks is computed because its neighbour + changed, so one request decides another's image. (Studio's length guard and counter may wrap the method; both + pass equal-shape calls through.)""" + torch = pytest.importorskip("torch") + fbc = pytest.importorskip("diffusers.hooks.first_block_cache") + + def decide(residual, previous): + state = types.SimpleNamespace(head_block_residual = previous, tail_block_residuals = None) + hook = types.SimpleNamespace( + threshold = 0.1, state_manager = types.SimpleNamespace(get_state = lambda: state) + ) + return bool(fbc.FBCHeadBlockHook._should_compute_remaining_blocks(hook, residual)) + + prev = torch.ones(2, 4, 8) + moved = prev.clone() + moved[1] *= 3.0 + assert decide(prev[:1].clone(), prev[:1]) is False # row 0 alone: skip + assert decide(moved, prev) is True # the same row 0 beside a changed neighbour: computed + + +@pytest.mark.parametrize("cache", ["fbcache", "static", None]) +def test_an_fbcache_load_serves_serially_and_a_static_schedule_still_batches(cache): + engine = _engine(offload_policy = "sequential", transformer_cache = cache, cache_auto = False) + policy = engine.request_batching() + if cache == "fbcache": + assert policy["mode"] == "serial" and "FBCache" in policy["reason"] + assert engine.coalesce_batch_sizes(1024, 1024) == frozenset() + with pytest.raises(race.RaceRefused): + engine.batch_race(width = 512, height = 512, steps = 8) + else: + assert policy["mode"] == "any" + assert engine.coalesce_batch_sizes(1024, 1024) is None + + +def test_an_auto_cache_batches_only_below_the_fbcache_step_count(): + from core.inference.diffusion_cache import FBCACHE_MIN_STEPS + + engine = _engine(offload_policy = "sequential", transformer_cache = None, cache_auto = True) + assert engine.request_batching()["mode"] == "any" + assert engine.coalesce_batch_sizes(1024, 1024, None, FBCACHE_MIN_STEPS - 1) is None + assert engine.coalesce_batch_sizes(1024, 1024, None, FBCACHE_MIN_STEPS) == frozenset() + assert engine.coalesce_batch_sizes(1024, 1024) == frozenset(), "unknown steps count as engaged" + + +def test_the_halved_retry_runs_after_the_failed_call_released_its_frames(): + """G5: an out-of-memory batch is split into halves only once the failed call's traceback (and every tensor its + frames hold) is gone; on a GPU the halves would otherwise start with the dead call's activations still allocated.""" + import gc + import weakref + + class Activations: + pass + + held: list = [] + alive_at_half: list = [] + + async def run_batch( + prompts, + seeds, + owners = None, + ): + if len(seeds) == 4: + big = Activations() # what the failed call's frame pins (latents, activations) + held.append(weakref.ref(big)) + raise RuntimeError("CUDA out of memory. Tried to allocate 8.00 GiB") + gc.collect() + alive_at_half.append(held[0]() is not None) + return {"images": list(prompts), "seeds": list(seeds), "seed": seeds[0]} + + results = _queue_four(run_batch) + assert all(r is not None for r in results) + assert alive_at_half == [ + False, + False, + ], "the failed call's frame was still alive during the halved retry" + + +def _queue_four(run_batch): + state = {"blocker": True} + + async def run(): + tasks = [] + for prompt in ("a", "b", "c", "d"): + tasks.append( + asyncio.ensure_future( + batching.generate( + "k", + prompt, + 1, + None, + busy = lambda: state["blocker"], + run_batch = run_batch, + splittable = lambda exc: "out of memory" in str(exc), + ) + ) + ) + await asyncio.sleep(0.02) + await asyncio.sleep(0.1) + state["blocker"] = False + return await asyncio.gather(*tasks) + + return asyncio.run(run()) + + +def test_the_batched_eager_arm_really_runs_eager(monkeypatch): + """The eager arm flips every graph handle's set_bypass around its calls (and only its calls).""" + monkeypatch.setattr(race, "record", lambda *a, **k: True) + seen = [] + state_flag = {"bypassed": False} + handle = types.SimpleNamespace( + set_bypass = lambda on: state_flag.update(bypassed = bool(on)), drop_batched = lambda size: 0 + ) + generate, clock, _ = _fake_generate(lambda rows: 1.0) + + def recording(**kw): + seen.append((len(kw.get("prompts") or [None]), state_flag["bypassed"])) + return generate(**kw) + + race.run_race( + recording, + types.SimpleNamespace(cuda_graphs = (handle,)), + idle = lambda: True, + width = 512, + height = 512, + sizes = (2,), + repeats = 3, + accuracy = False, + clock = lambda: clock["t"], + ) + assert (2, True) in seen and (2, False) in seen + assert all( + not bypassed for rows, bypassed in seen if rows == 1 + ), "serial renders keep their graphs" + assert state_flag["bypassed"] is False + + +def test_a_verdict_is_keyed_by_the_card_topology(monkeypatch): + """A verdict on one card says nothing about a two-card split of the same load (or a CFG replica).""" + import core.inference.diffusion_multigpu as mg + + pipe = types.SimpleNamespace() + state = types.SimpleNamespace(pipe = pipe, offload_policy = "none", cuda_graphs = ()) + one = race.topology(state) + monkeypatch.setattr(mg, "_PLACEMENTS", {id(pipe): None}) + split = {"primary": "cuda:0", "secondary": "cuda:1", "moved": ["text_encoder"]} + + class Box(dict): + def get( + self, + key, + default = None, + ): + return split if key is pipe else default + + monkeypatch.setattr(mg, "_PLACEMENTS", Box()) + two = race.topology(state) + assert one != two and "split:cuda:0>cuda:1:text_encoder" in two + assert race.load_key(state).endswith(two) + + +def test_a_graphed_verdict_admits_a_size_only_while_its_graph_exists(monkeypatch): + """A verdict won on the graphed arm says nothing once that batch-size graph is gone (restart, LoRA reset, OOM): + the size is then admitted only if the eager arm passed on its own.""" + graphed_win = { + "promoted": True, + "arm": "batched", + "layout": race.layout_token(()), + "graph_canvas": "c", + "arms": {"batched": {"promoted": True}, "batched_eager": {"promoted": False}}, + } + both_win = { + "promoted": True, + "arm": "batched", + "layout": race.layout_token(()), + "arms": {"batched": {"promoted": True}, "batched_eager": {"promoted": True}}, + } + handle = types.SimpleNamespace( + cache = {"k2": object()}, _batched = {"k2": 2}, _batched_canvas = {"k2": {"c"}} + ) + with_graph = types.SimpleNamespace(cuda_graphs = (handle,)) + # step-graph handles (GraphedForward) can drop their batched graphs, so an eager fallback is enforceable + without = types.SimpleNamespace( + cuda_graphs = ( + types.SimpleNamespace(cache = {"k1": 1}, _batched = {}, drop_batched = lambda size: 0), + ) + ) + assert race.effective_verdict(graphed_win, 2, with_graph, layout = ())["promoted"] is True + assert race.effective_verdict(graphed_win, 2, without)["promoted"] is False + assert race.effective_verdict(both_win, 2, without)["promoted"] is True + assert not race.seeded_join_ok( + race.effective_verdict(dict(both_win, neighbour_exact = True), 2, without) + ) + restarted = types.SimpleNamespace(cuda_graphs = (types.SimpleNamespace(cache = {}, _batched = {}),)) + assert race.effective_verdict(graphed_win, 2, restarted)["promoted"] is False + no_graphs = types.SimpleNamespace(cuda_graphs = ()) + assert race.effective_verdict(graphed_win, 2, no_graphs)["promoted"] is True + + +def test_an_eager_win_is_withheld_once_a_later_race_records_a_graph_of_that_size(): + """An eager-arm win at one canvas stands only while no batch-size graph of its size exists: a later race at another + canvas or step count can record one with the same tensor shapes, which GraphedForward would replay for it.""" + eager_win = {"promoted": True, "arm": "batched_eager", "neighbour_exact": True, "b_exact": True} + graphed_elsewhere = { + "promoted": True, + "arm": "batched", + "layout": race.layout_token(()), + "graph_canvas": "other", + "arms": {"batched": {"promoted": True}, "batched_eager": {"promoted": True}}, + } + dropped = types.SimpleNamespace(cache = {"k1": 1}, _batched = {}, drop_batched = lambda size: 0) + assert race.effective_verdict(eager_win, 2, types.SimpleNamespace(cuda_graphs = (dropped,)))[ + "promoted" + ] + recorded = types.SimpleNamespace( + cache = {"k2": object()}, + _batched = {"k2": 2}, + _batched_canvas = {"k2": {"other"}}, + drop_batched = lambda size: 0, + ) + later = types.SimpleNamespace(cuda_graphs = (recorded,)) + for verdict in (eager_win, graphed_elsewhere): + got = race.effective_verdict(verdict, 2, later, layout = ("bucket", 2)) + assert got["promoted"] is False and not race.seeded_join_ok(got) + # Another size's graph replays nothing for size 2; a graphed win at its own canvas still holds. + assert race.effective_verdict(eager_win, 4, later)["promoted"] is True + assert race.effective_verdict(graphed_elsewhere, 2, later, layout = ())["promoted"] is True + + +def test_a_seeded_request_joins_only_when_every_size_it_could_render_at_is_exact(monkeypatch): + """A streamed load (policy any) still admits the unmeasured sizes: one exact size 2 says nothing about 3-8.""" + from core.inference.image_request_batching import batch_max + + exact = {"promoted": True, "neighbour_exact": True, "replay_exact": True} + streamed = _engine(offload_policy = "sequential") + _verdicts(monkeypatch, {2: exact}) + assert streamed.coalesce_seeded_ok(1024, 1024, 4.0, 1) is False + _verdicts(monkeypatch, {k: exact for k in range(2, batch_max() + 1)}) + assert streamed.coalesce_seeded_ok(1024, 1024, 4.0, 1) is True + # A measured (resident) load admits only the winners: one exact size is enough there. + _verdicts(monkeypatch, {2: exact, 4: {"promoted": False}}) + assert _engine().coalesce_seeded_ok(1024, 1024, 4.0, 1) is True + + +def test_an_eager_win_drops_the_graphs_dispatch_would_otherwise_replay(monkeypatch): + """Dispatch never bypasses graphs: when the eager arm wins, the size's race-recorded graphs go, so requests run the + arm that was measured.""" + monkeypatch.setattr(race, "record", lambda *a, **k: True) + dropped = [] + flag = {"bypassed": False} + handle = types.SimpleNamespace( + set_bypass = lambda on: flag.update(bypassed = bool(on)), + drop_batched = lambda size: dropped.append(size) or 1, + ) + generate, clock, _ = _fake_generate( + lambda rows: 1.0 if rows == 1 else (0.3 if flag["bypassed"] else 0.9) * rows + ) + report = race.run_race( + generate, + types.SimpleNamespace(cuda_graphs = (handle,)), + idle = lambda: True, + width = 512, + height = 512, + sizes = (2,), + repeats = 3, + accuracy = False, + clock = lambda: clock["t"], + ) + verdict = report["sizes"]["2"] + assert verdict["promoted"] is True and verdict["arm"] == "batched_eager" + assert dropped == [2] + + +def test_a_static_compile_limits_the_race_on_a_resident_or_graphed_load(monkeypatch): + """Resident weights return serial (measurable) before the static-compile rule: the race must still skip sizes the + compile cache lacks.""" + import core.inference.diffusion as diffusion_module + + monkeypatch.setattr(diffusion_module, "compiled_shapes_are_static", lambda pipe, mode: True) + seen = {} + monkeypatch.setattr(race, "run_race", lambda *a, **k: seen.update(k) or {}) + for extra in ({}, {"offload_policy": "sequential", "cuda_graphs": (object(),)}): + engine = _engine( + speed_optims = ("compiled",), + compile_cache_ctx = types.SimpleNamespace(shapes = [(512, 512, 2)]), + **extra, + ) + seen.clear() + engine.batch_race(width = 512, height = 512) + allowed = seen["allowed_sizes"] + assert allowed is not None and allowed(2) and not allowed(4) + + +def test_the_eager_arm_holds_a_forced_eager_scope_through_generate(monkeypatch): + """The per-chunk set_bypass(False) in generate() cannot undo it: the arm runs under cuda_graph.forced_eager().""" + from core.inference import diffusion_cuda_graph as cg + + monkeypatch.setattr(race, "record", lambda *a, **k: True) + seen = [] + handle = types.SimpleNamespace(set_bypass = lambda on: None, drop_batched = lambda size: 0) + generate, clock, _ = _fake_generate(lambda rows: 1.0) + + def recording(**kw): + seen.append((len(kw.get("prompts") or [None]), cg.eager_forced())) + return generate(**kw) + + race.run_race( + recording, + types.SimpleNamespace(cuda_graphs = (handle,)), + idle = lambda: True, + width = 512, + height = 512, + sizes = (2,), + repeats = 3, + accuracy = False, + clock = lambda: clock["t"], + ) + assert (2, True) in seen and (2, False) in seen and (1, True) not in seen + assert cg.eager_forced() is False + + +def test_a_graphed_verdict_holds_only_for_the_prompt_layout_it_was_raced_at(monkeypatch): + """A FLUX.1 prompt in another T5 bucket runs the same canvas through other shapes: no graph of the race's layout + serves it, so only the eager arm's verdict applies there (and when the layout is unknown).""" + graphed_win = { + "promoted": True, + "arm": "batched", + "layout": race.layout_token(("t5", 256)), + "graph_canvas": "c", + "arms": {"batched": {"promoted": True}, "batched_eager": {"promoted": False}}, + } + handle = types.SimpleNamespace( + cache = {"k2": object()}, _batched = {"k2": 2}, _batched_canvas = {"k2": {"c"}} + ) + state = types.SimpleNamespace(cuda_graphs = (handle,)) + assert race.effective_verdict(graphed_win, 2, state, layout = ("t5", 256))["promoted"] is True + assert race.effective_verdict(graphed_win, 2, state, layout = ("t5", 512))["promoted"] is False + assert race.effective_verdict(graphed_win, 2, state)["promoted"] is False + # The engine threads the request's layout through to the verdict. + _verdicts(monkeypatch, {2: graphed_win}) + engine = _engine(cuda_graphs = (handle,)) + assert engine.coalesce_batch_sizes(1024, 1024, 4.0, layout = ("t5", 256)) == frozenset({2}) + assert engine.coalesce_batch_sizes(1024, 1024, 4.0, layout = ("t5", 512)) == frozenset() + + +def test_the_race_records_the_layout_of_its_prompts(monkeypatch): + monkeypatch.setattr(race, "record", lambda *a, **k: True) + generate, clock, _ = _fake_generate(lambda rows: 1.0 if rows == 1 else 0.4 * rows) + report = race.run_race( + generate, + types.SimpleNamespace(cuda_graphs = ()), + idle = lambda: True, + width = 512, + height = 512, + sizes = (2,), + repeats = 3, + accuracy = False, + layout = ("t5", 256), + clock = lambda: clock["t"], + ) + assert report["sizes"]["2"]["layout"] == race.layout_token(("t5", 256)) + + +def test_an_out_of_memory_size_is_a_persisted_loss_and_the_race_goes_on(monkeypatch): + stored = {} + monkeypatch.setattr( + race, + "record", + lambda state, w, h, g, size, verdict, steps = None: stored.update({size: verdict}) or True, + ) + dropped = [] + handle = types.SimpleNamespace( + set_bypass = lambda on: None, drop_batched = lambda size: dropped.append(size) or 1 + ) + generate, clock, _ = _fake_generate(lambda rows: 1.0 if rows == 1 else 0.4 * rows) + + def oom_at_four(**kw): + if len(kw.get("prompts") or [None]) == 4: + raise RuntimeError("CUDA out of memory. Tried to allocate 2.00 GiB") + return generate(**kw) + + report = race.run_race( + oom_at_four, + types.SimpleNamespace(cuda_graphs = (handle,)), + idle = lambda: True, + width = 512, + height = 512, + sizes = (2, 4), + repeats = 3, + accuracy = False, + clock = lambda: clock["t"], + ) + four = report["sizes"]["4"] + assert four["promoted"] is False and "out of memory" in four["failed"] + assert stored[4]["promoted"] is False and 4 in dropped + assert "2" in report["sizes"] and stored[2]["promoted"] is True + + +def test_a_failure_that_is_not_capacity_still_raises(monkeypatch): + monkeypatch.setattr(race, "record", lambda *a, **k: True) + + def broken(**kw): + raise KeyError("bug") + + with pytest.raises(KeyError): + race.run_race( + broken, + types.SimpleNamespace(cuda_graphs = ()), + idle = lambda: True, + width = 512, + height = 512, + sizes = (2,), + repeats = 3, + accuracy = False, + ) + + +def test_an_aborted_size_drops_the_batched_graphs_its_warm_up_recorded(monkeypatch): + """A request arriving after the batched warm-up (calls [1, 4]) aborts the size with no verdict: an otherwise serial + load can never use the graph that warm-up recorded, so it goes before the aborted report returns.""" + monkeypatch.setattr(race, "record", lambda *a, **k: True) + dropped = [] + handle = types.SimpleNamespace( + set_bypass = lambda on: None, drop_batched = lambda size: dropped.append(size) or 1 + ) + generate, clock, calls = _fake_generate(lambda rows: 1.0) + report = race.run_race( + generate, + types.SimpleNamespace(cuda_graphs = (handle,)), + idle = lambda: len(calls) < 2, + width = 512, + height = 512, + sizes = (4,), + repeats = 3, + accuracy = False, + clock = lambda: clock["t"], + ) + assert calls == [1, 4] and report["aborted"] is True + assert dropped == [4] and report["sizes"]["4"]["batched_graphs_dropped"] == 1 + + +def test_block_graph_handles_never_count_a_graphed_winner_as_missing(): + """BlockGraphSet (offloaded / layer-split loads) records each layout on demand, user calls included, and keeps no + per-batch-size labels: only handles that refuse to record on a user's request (GraphedForward) decide.""" + import inspect + + from core.inference.diffusion_block_graph import BlockGraphSet + + assert "_batched" not in inspect.getsource(BlockGraphSet) + graphed_win = { + "promoted": True, + "arm": "batched", + "layout": race.layout_token(()), + "arms": {"batched": {"promoted": True}, "batched_eager": {"promoted": False}}, + } + blocks = types.SimpleNamespace(cache = {(0, "k4"): object()}) + assert ( + race.effective_verdict( + graphed_win, 4, types.SimpleNamespace(cuda_graphs = (blocks,)), layout = () + )["promoted"] + is True + ) + # Beside a step-graph handle, that handle still decides. + step = types.SimpleNamespace(cache = {"k1": object()}, _batched = {}) + mixed = types.SimpleNamespace(cuda_graphs = (blocks, step)) + assert race.effective_verdict(graphed_win, 4, mixed, layout = ())["promoted"] is False + + +def test_a_live_graph_at_one_canvas_never_admits_a_graphed_verdict_raced_at_another(): + """After a restart, racing 512x512 records a live batch-2 graph; a persisted batch-2 verdict for 1024x1024 that won + only on the graphed arm must not ride it (graphs key on tensor shapes, so the 1024 batch runs eager): it falls back + to its own eager arm, which lost, and seeded joins stay off.""" + layout = ("t5", 256) + small = race.canvas_token(512, 512, None, None, layout) + large = race.canvas_token(1024, 1024, None, None, layout) + assert small != large + graphed_win_large = { + "promoted": True, + "arm": "batched", + "layout": race.layout_token(layout), + "graph_canvas": large, + "neighbour_exact": True, + "replay_exact": True, + "arms": {"batched": {"promoted": True}, "batched_eager": {"promoted": False}}, + } + live_small = types.SimpleNamespace( + cache = {"k512": object()}, _batched = {"k512": 2}, _batched_canvas = {"k512": {small}} + ) + state = types.SimpleNamespace(cuda_graphs = (live_small,)) + applied = race.effective_verdict(graphed_win_large, 2, state, layout = layout) + assert applied["promoted"] is False and applied["graph_missing"] is True + assert not race.seeded_join_ok(applied) + # The same verdict holds once a live batch-2 graph of its own canvas exists. + live_small._batched_canvas["k512"].add(large) + assert race.effective_verdict(graphed_win_large, 2, state, layout = layout)["promoted"] is True + # A verdict persisted before canvases were tracked proves no graph shape: only its eager arm counts. + legacy = {k: v for k, v in graphed_win_large.items() if k != "graph_canvas"} + assert race.effective_verdict(legacy, 2, state, layout = layout)["promoted"] is False + + +def test_the_race_labels_its_batched_calls_and_verdicts_with_its_canvas(monkeypatch): + from core.inference import diffusion_cuda_graph as cg + + monkeypatch.setattr(race, "record", lambda *a, **k: True) + generate, clock, _ = _fake_generate(lambda rows: 1.0 if rows == 1 else 0.4 * rows) + seen = [] + + def traced(**kwargs): + seen.append(cg._BATCH_CANVAS.get()) + return generate(**kwargs) + + report = race.run_race( + traced, + types.SimpleNamespace(cuda_graphs = ()), + idle = lambda: True, + width = 1024, + height = 768, + guidance = 3.5, + steps = 4, + sizes = (2,), + repeats = 3, + accuracy = False, + layout = ("t5", 256), + clock = lambda: clock["t"], + ) + want = race.canvas_token(1024, 768, 3.5, 4, ("t5", 256)) + assert report["sizes"]["2"]["graph_canvas"] == want + assert want in seen and None in seen # solo renders carry no canvas label + assert cg._BATCH_CANVAS.get() is None diff --git a/studio/backend/tests/test_image_batch_quality.py b/studio/backend/tests/test_image_batch_quality.py new file mode 100644 index 000000000000..e6d7465c62a7 --- /dev/null +++ b/studio/backend/tests/test_image_batch_quality.py @@ -0,0 +1,629 @@ +# SPDX-License-Identifier: AGPL-3.0-only +# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0 + +"""A measured batching win serves only where an offline G2c verdict passes for the family, card and execution path; +a missing or failing verdict keeps today's serial rules.""" + +from __future__ import annotations + +import asyncio +import sys +import types +from pathlib import Path + +import httpx +import pytest + +from core.inference import diffusion_batch_quality as quality +from core.inference import diffusion_batch_race as race + +sys.path.insert(0, str(Path(__file__).resolve().parent)) +from test_image_batch_infra import _engine, _fake_generate, _verdicts # noqa: E402 +from test_image_concurrency import studio # noqa: E402,F401 (fixture) + +CARD = "NVIDIA RTX PRO 6000 Blackwell Server Edition" +PASS = {"verdict": "PASS", "n": 24, "upper": 0.006} + + +@pytest.fixture(autouse = True) +def _local_file(monkeypatch, tmp_path): + monkeypatch.setattr(quality, "_file", lambda: tmp_path / quality.FILE_NAME) + monkeypatch.setattr(quality, "SHIPPED", {}) + + +def test_a_speed_winning_race_with_no_g2c_pass_stays_serial(monkeypatch): + _verdicts(monkeypatch, {2: {"promoted": True, "arm": "batched"}, 4: {"promoted": False}}) + for engine in (_engine(device_name = CARD), _engine(device_name = CARD, cuda_graphs = (object(),))): + assert engine.request_batching()["mode"] == "serial" + assert engine.coalesce_batch_sizes(1024, 1024, 4.0) == frozenset() + + +@pytest.mark.parametrize( + "stored", + [ + {"verdict": "FAIL", "n": 24, "upper": 0.0136}, + {"verdict": "PASS", "n": 8, "upper": 0.004}, # too few pairs + {"verdict": "PASS", "n": 24, "upper": 0.02}, # bound over eps whatever the label says + ], +) +def test_a_failing_or_underpowered_verdict_stays_serial(monkeypatch, stored): + _verdicts(monkeypatch, {2: {"promoted": True, "arm": "batched"}}) + assert quality.record("flux.2-klein", CARD, "graph", stored) + engine = _engine(device_name = CARD) + assert engine.request_batching()["mode"] == "serial" + assert engine.coalesce_batch_sizes(1024, 1024, 4.0) == frozenset() + + +def test_a_pass_on_the_raced_path_lifts_the_serial_rule(monkeypatch): + _verdicts(monkeypatch, {2: {"promoted": True, "arm": "batched"}, 4: {"promoted": False}}) + assert quality.record("flux.2-klein", CARD, "graph", PASS) + engine = _engine(device_name = CARD) + assert engine.request_batching()["mode"] == "measured" + assert engine.coalesce_batch_sizes(1024, 1024, 4.0) == frozenset({2}) + + +def test_the_verdict_is_per_path_family_and_card(monkeypatch): + _verdicts(monkeypatch, {2: {"promoted": True, "arm": "batched"}}) + quality.record( + "flux.2-klein", CARD, "eager", PASS + ) # the eager path passed, the graphed arm won + assert _engine(device_name = CARD).coalesce_batch_sizes(1024, 1024, 4.0) == frozenset() + quality.record("flux.2-klein", "NVIDIA A100-SXM4-40GB", "graph", PASS) # another card + assert _engine(device_name = CARD).coalesce_batch_sizes(1024, 1024, 4.0) == frozenset() + quality.record("hidream", CARD, "graph", PASS) # another family + assert _engine(device_name = CARD).coalesce_batch_sizes(1024, 1024, 4.0) == frozenset() + quality.record("flux.2-klein", CARD, "any", PASS) + assert _engine(device_name = CARD).coalesce_batch_sizes(1024, 1024, 4.0) == frozenset({2}) + + +def test_no_card_identity_is_no_verdict(monkeypatch): + _verdicts(monkeypatch, {2: {"promoted": True, "arm": "batched"}}) + quality.record("flux.2-klein", CARD, "any", PASS) + assert _engine().coalesce_batch_sizes(1024, 1024, 4.0) == frozenset() # no device, no class + + +def test_streamed_loads_keep_todays_rule_and_a_loss_still_drops_its_size(monkeypatch): + # The gate only holds back promotions; it never adds a size or blocks the streamed default. + _verdicts(monkeypatch, {4: {"promoted": False}}) + engine = _engine(device_name = CARD, offload_policy = "sequential") + assert engine.request_batching()["mode"] == "any" + sizes = engine.coalesce_batch_sizes(1024, 1024) + assert 4 not in sizes and {2, 3} <= sizes + + +def test_the_gate_names_why_a_speed_win_does_not_serve(): + state = types.SimpleNamespace( + family = types.SimpleNamespace(name = "flux.3-klein"), device_name = CARD + ) + won = {"promoted": True, "arm": "batched_eager", "speedup_lb": 1.14} + held = quality.gate(won, state) + assert ( + held["promoted"] is False + and "no G2c verdict" in held["quality_gate"] + and "(eager)" in held["quality_gate"] + ) + assert won["promoted"] is True, "the stored speed verdict is not rewritten" + quality.record("flux.3-klein", CARD, "eager", {"verdict": "FAIL", "n": 24, "upper": 0.02}) + assert "does not pass" in quality.gate(won, state)["quality_gate"] + quality.record("flux.3-klein", CARD, "eager", PASS) + assert quality.gate(won, state) is won + with pytest.raises(ValueError): + quality.record("flux.3-klein", CARD, "compiled", PASS) + + +def test_the_race_itself_still_records_the_speed_verdict(monkeypatch): + # Persisting the speed verdict is unchanged; serving it is what the gate decides. + stored = {} + monkeypatch.setattr( + race, "record", lambda state, w, h, g, k, v, steps = None: stored.setdefault(k, v) is v + ) + generate, clock, _ = _fake_generate(lambda rows: 1.0 + 0.5 * (rows - 1)) + report = race.run_race( + generate, + types.SimpleNamespace(cuda_graphs = ()), + idle = lambda: True, + width = 512, + height = 512, + sizes = (2,), + repeats = 4, + clock = lambda: clock["t"], + ) + assert report["sizes"]["2"]["promoted"] is True and stored[2]["promoted"] is True + + +# ------------------------------------------------------------------------------------------- batch-exact (row 0 vs solo) + + +def test_the_eager_arms_replay_check_renders_its_solo_eager_too(monkeypatch): + """G2a holds the batch shape fixed; the replay check is row 0 of the batch against its own solo render, and on the + batched-eager arm that solo must run eager as well (not a graph replay), or the check compares two paths.""" + from core.inference import diffusion_cuda_graph as cg + + monkeypatch.setattr(race, "record", lambda *a, **k: True) + seen = [] + handle = types.SimpleNamespace(set_bypass = lambda on: None, drop_batched = lambda size: 0) + generate, clock, _ = _fake_generate(lambda rows: 1.0 if rows == 1 else 0.6 * rows) + + def recording(**kw): + rows = len(kw.get("prompts") or [None]) + seen.append((rows, cg.eager_forced())) + if rows > 1 and not cg.eager_forced(): + clock["t"] += 1.0 # the graphed arm loses, so the neighbour check runs on the eager arm + return generate(**kw) + + report = race.run_race( + recording, + types.SimpleNamespace(cuda_graphs = (handle,)), + idle = lambda: True, + width = 512, + height = 512, + sizes = (2,), + repeats = 3, + clock = lambda: clock["t"], + ) + verdict = report["sizes"]["2"] + assert verdict["arm"] == "batched_eager" and verdict["replay_path"] == "eager" + assert (1, True) in seen, "the eager arm's solo replay ran under forced_eager" + assert verdict["b_exact"] is True and verdict["replay_exact"] is True + + +def test_b_exact_allows_only_the_same_shape_noise_floor(): + import numpy as np + + base = np.zeros((4, 4, 3), dtype = np.uint8) + off_by_2, off_by_5 = base.copy(), base.copy() + off_by_2[0, 0, 0], off_by_5[0, 0, 0] = 2, 5 + assert race._b_exact(base, base.copy(), base.copy()) is True # bit-identical + assert ( + race._b_exact(base, off_by_2, base.copy()) is False + ) # deterministic path: any difference fails + assert race._b_exact(base, off_by_2, off_by_5) is True # within the A/A floor of that shape + assert race._b_exact(base, off_by_5, off_by_2) is False # further than the floor + assert race._b_exact(None, base, base) is False + + +def test_seeded_joins_need_the_batch_exact_check(): + won = {"promoted": True, "neighbour_exact": True, "replay_exact": True} + assert race.seeded_join_ok(won) is True # a verdict from before the check + assert race.seeded_join_ok(dict(won, b_exact = False)) is False + assert race.seeded_join_ok(dict(won, replay_exact = False, b_exact = True)) is True + assert race.seeded_join_ok(dict(won, neighbour_exact = False, b_exact = True)) is False + + +# ------------------------------------------------------------------------------------------- review fixes + + +def test_a_held_back_win_never_removes_a_size_the_default_policy_admits(monkeypatch): + """A streamed load (policy any) or a static compile (compiled_sizes) admits sizes before any race; a win the gate + holds back is not a loss, so it must not take its size away (the gate is never stricter than no race at all).""" + _verdicts(monkeypatch, {2: {"promoted": True, "arm": "batched"}}) + streamed = _engine(device_name = CARD, offload_policy = "sequential") + assert streamed.request_batching()["mode"] == "any" + assert streamed.coalesce_batch_sizes(1024, 1024) is None + # a real speed loss still drops its size + _verdicts(monkeypatch, {2: {"promoted": True, "arm": "batched"}, 4: {"promoted": False}}) + sizes = streamed.coalesce_batch_sizes(1024, 1024) + assert 4 not in sizes and 2 in sizes + + +def test_a_held_back_win_keeps_a_compiled_size(monkeypatch): + from core.inference import diffusion as diffusion_module + + monkeypatch.setattr(diffusion_module, "compiled_shapes_are_static", lambda pipe, mode: True) + _verdicts(monkeypatch, {2: {"promoted": True, "arm": "batched"}, 4: {"promoted": False}}) + engine = _engine( + device_name = CARD, + offload_policy = "sequential", + speed_optims = ("compiled",), + compile_cache_ctx = types.SimpleNamespace(shapes = [(1024, 1024, 2), (1024, 1024, 4)]), + ) + assert engine.request_batching()["mode"] == "compiled_sizes" + assert engine.coalesce_batch_sizes(1024, 1024) == frozenset({2}) + + +def test_the_race_persists_the_path_it_ran_and_the_gate_reads_it(monkeypatch): + """Without graph handles the race has only the ``batched`` arm, and that arm runs eager: the verdict says so, and + only an eager (or any) G2c verdict may let it serve.""" + stored = {} + monkeypatch.setattr( + race, "record", lambda state, w, h, g, k, v, steps = None: stored.setdefault(k, v) is v + ) + generate, clock, _ = _fake_generate(lambda rows: 1.0 + 0.5 * (rows - 1)) + report = race.run_race( + generate, + types.SimpleNamespace(cuda_graphs = ()), + idle = lambda: True, + width = 512, + height = 512, + sizes = (2,), + repeats = 4, + clock = lambda: clock["t"], + ) + verdict = report["sizes"]["2"] + assert ( + verdict["arm"] == "batched" and verdict["path"] == "eager" and stored[2]["path"] == "eager" + ) + state = types.SimpleNamespace( + family = types.SimpleNamespace(name = "flux.3-klein"), device_name = CARD + ) + quality.record("flux.3-klein", CARD, "graph", PASS) + assert ( + quality.gate(verdict, state)["promoted"] is False + ), "a graph-only PASS does not vouch for eager" + quality.record("flux.3-klein", CARD, "eager", PASS) + assert quality.gate(verdict, state)["promoted"] is True + + +def test_a_graphed_race_with_handles_records_the_graph_path_and_a_fallback_records_eager( + monkeypatch, +): + stored = {} + monkeypatch.setattr( + race, "record", lambda state, w, h, g, k, v, steps = None: stored.setdefault(k, v) is v + ) + handle = types.SimpleNamespace(set_bypass = lambda on: None, drop_batched = lambda size: 0) + generate, clock, _ = _fake_generate(lambda rows: 1.0 + 0.5 * (rows - 1)) + report = race.run_race( + generate, + types.SimpleNamespace(cuda_graphs = (handle,)), + idle = lambda: True, + width = 512, + height = 512, + sizes = (2,), + repeats = 4, + accuracy = False, + clock = lambda: clock["t"], + ) + verdict = report["sizes"]["2"] + assert verdict["path"] == ("eager" if verdict["arm"] == "batched_eager" else "graph") + # A graphed win whose batch-size graph is gone falls back to the eager arm: its path follows. + monkeypatch.setattr(race, "batched_graph_sizes", lambda state: set()) + graphed = { + "promoted": True, + "arm": "batched", + "path": "graph", + "arms": {"batched_eager": {"promoted": True}}, + } + fallback = race.effective_verdict(graphed, 2, types.SimpleNamespace(cuda_graphs = (handle,))) + assert fallback["graph_missing"] is True and fallback["path"] == "eager" + assert quality.path_of(fallback) == "eager" + + +# ------------------------------------------------------------------------------------------- arm choice, race sizes + + +def test_a_qualifying_arm_wins_over_a_faster_bound_that_fails_p95(monkeypatch): + """Serial 5 s per image at batch 2; the graphed call is 4 s but one timed repeat takes 11 s (higher bound, p95 over + the slack), the eager call is a steady 8 s (bound 1.25, p95 within). The eager arm passes both and must win.""" + from core.inference import diffusion_cuda_graph as cg + + stored, dropped = {}, [] + monkeypatch.setattr( + race, "record", lambda state, w, h, g, k, v, steps = None: stored.setdefault(k, v) is v + ) + handle = types.SimpleNamespace( + set_bypass = lambda on: None, drop_batched = lambda size: dropped.append(size) or 0 + ) + clock = {"t": 0.0} + graphed = {"n": 0} + + def generate( + prompt = None, + prompts = None, + seeds = None, + seed = None, + batch_size = 1, + **kw, + ): + rows = list(prompts) if prompts else [prompt] + row_seeds = list(seeds) if seeds else [seed] + if len(rows) == 1: + clock["t"] += 5.0 + elif cg.eager_forced(): + clock["t"] += 8.0 + else: + graphed["n"] += 1 # the first graphed call is the untimed capture warm-up + clock["t"] += 11.0 if graphed["n"] == 5 else 4.0 + return {"images": [types.SimpleNamespace(p = p, s = s) for p, s in zip(rows, row_seeds)]} + + report = race.run_race( + generate, + types.SimpleNamespace(cuda_graphs = (handle,)), + idle = lambda: True, + width = 512, + height = 512, + sizes = (2,), + repeats = 5, + accuracy = False, + clock = lambda: clock["t"], + ) + verdict = report["sizes"]["2"] + graphed_arm = verdict["arms"]["batched"] + assert ( + graphed_arm["promoted"] is False + and graphed_arm["speedup_lb"] > verdict["arms"]["batched_eager"]["speedup_lb"] + ) + assert ( + verdict["promoted"] is True + and verdict["arm"] == "batched_eager" + and verdict["path"] == "eager" + ) + assert stored[2]["promoted"] is True + + +def test_no_qualifying_arm_records_the_best_bound_as_the_loss(): + lost = race._pick_arm( + { + "batched": {"promoted": False, "speedup_lb": 1.2}, + "batched_eager": {"promoted": False, "speedup_lb": 0.9}, + } + ) + assert lost == "batched" + both = race._pick_arm( + { + "batched": {"promoted": True, "speedup_lb": 1.2}, + "batched_eager": {"promoted": True, "speedup_lb": 1.4}, + } + ) + assert both == "batched_eager" + + +@pytest.mark.parametrize("sizes", [(16,), (2, 9), (1,), (0,)]) +def test_the_race_refuses_a_size_it_has_no_prompts_for_before_any_render(sizes): + calls = [] + with pytest.raises(ValueError, match = "batch sizes"): + race.run_race( + lambda **kw: calls.append(kw) or {"images": []}, + types.SimpleNamespace(cuda_graphs = ()), + idle = lambda: True, + width = 512, + height = 512, + sizes = sizes, + ) + assert calls == [], "nothing renders before the sizes are checked" + assert race.MAX_RACE_SIZE == min(len(race.RACE_PROMPTS), len(race.NEIGHBOUR_PROMPTS) + 1) + + +def test_the_race_endpoint_answers_422_for_an_unsupported_size(monkeypatch): + import asyncio + + from fastapi import HTTPException + + import routes.inference as inference + + monkeypatch.setattr(inference.account_access, "managed_account", lambda: False) + with pytest.raises(HTTPException) as caught: + asyncio.run( + inference.images_batching_race( + inference.ImageBatchRaceRequest(sizes = [16]), current_subject = "x" + ) + ) + assert caught.value.status_code == 422 + assert "2" in caught.value.detail and str(race.MAX_RACE_SIZE) in caught.value.detail + + +# ------------------------------------------------------------------------------------------- adapters + + +@pytest.mark.parametrize( + "pipe", + [ + types.SimpleNamespace(_unsloth_loras = (("style", "/tmp/style.safetensors", 0.8),)), + types.SimpleNamespace( + _unsloth_loras_baked = True, _unsloth_baked_lora_specs = (("style", 0.8),) + ), + types.SimpleNamespace(_unsloth_load_lora_specs = (("style", 0.8),)), + ], +) +def test_the_race_refuses_a_load_with_active_adapters_before_any_render(monkeypatch, pipe): + """The race renders without ``loras``, which generate() reads as none: it would unload or zero the user's adapters + (or, baked under streamed graphs, refuse with a reload error mid-race). Verdicts are not keyed by adapter set, so + the race refuses an adapted load up front.""" + engine = _engine(pipe = pipe, offload_policy = "sequential") + rendered = [] + monkeypatch.setattr(engine, "generate", lambda **kw: rendered.append(kw) or {"images": []}) + with pytest.raises(race.RaceRefused, match = "adapter"): + engine.batch_race(width = 512, height = 512) + assert rendered == [] + + +def test_an_adapter_free_load_still_races(monkeypatch): + engine = _engine( + pipe = types.SimpleNamespace(_unsloth_loras = (("off", "/tmp/off.safetensors", 0.0),)), + offload_policy = "sequential", + ) + called = [] + monkeypatch.setattr(race, "run_race", lambda *a, **k: called.append(k) or {"sizes": {}}) + engine.batch_race(width = 512, height = 512) + assert called, "a zero-weight adapter is not an active selection" + + +# ------------------------------------------------------------------------------------------- deferred speed profile + + +def test_the_engine_refuses_to_race_while_the_speed_profile_is_still_deferred(monkeypatch): + """A fresh Auto load engages its speed profile on its third render: inside a race that would install graphs after + the race snapshotted its handles (graph timings saved as path eager, no eager arm, batch graphs left behind).""" + engine = _engine(offload_policy = "sequential", speed_deferred = True) + rendered = [] + monkeypatch.setattr(engine, "generate", lambda **kw: rendered.append(kw) or {"images": []}) + with pytest.raises(race.RaceRefused, match = "deferred"): + engine.batch_race(width = 512, height = 512) + assert rendered == [] + + +def test_a_race_whose_execution_configuration_changes_stops_and_persists_nothing_more(monkeypatch): + stored = {} + monkeypatch.setattr( + race, "record", lambda state, w, h, g, k, v, steps = None: stored.setdefault(k, v) is v + ) + state = types.SimpleNamespace(cuda_graphs = (), speed_optims = ()) + generate, clock, calls = _fake_generate(lambda rows: 1.0 + 0.5 * (rows - 1)) + + def engaging(**kw): + if len(calls) == 2: # the third render engages a profile: graphs appear under the race + state.cuda_graphs = ( + types.SimpleNamespace(set_bypass = lambda on: None, drop_batched = lambda k: 0), + ) + state.speed_optims = ("compiled", "cuda_graph") + return generate(**kw) + + with pytest.raises(race.RaceRefused, match = "changed"): + race.run_race( + engaging, + state, + idle = lambda: True, + width = 512, + height = 512, + sizes = (4, 2), + repeats = 3, + clock = lambda: clock["t"], + ) + assert stored == {}, "no verdict is persisted for a measurement that straddled the change" + + +# ------------------------------------------------------------------------------------------- route capability check + + +def test_a_measured_moss_layer_major_load_coalesces_through_the_route(studio, monkeypatch): + """MOSS fuses rows only on a layer-major load with a measured win (diffusion_moss_image.coalesce_key(pipe)). The + route's family check has no pipe of its own: it must not refuse MOSS before the engine, which has the pipe, is + asked (#19957).""" + from test_image_batch_infra import _post_while_rendering + from test_image_batching_followups import _groups, _interleaved, _plan + + from core.inference.diffusion_families import MOSS_IMAGE_FAMILY_NAME, detect_family + + fake = types.ModuleType("core.inference.diffusion_moss_image") + fake.coalesce_key = lambda pipe: ("moss-image layer-major",) + monkeypatch.setitem(sys.modules, "core.inference.diffusion_moss_image", fake) + app, backend, _saved = studio + backend.status = lambda: { + "loaded": True, + "repo_id": "x/moss", + "family": MOSS_IMAGE_FAMILY_NAME, + "base_repo": None, + } + _plan( + backend, + detect_family("", MOSS_IMAGE_FAMILY_NAME), + types.SimpleNamespace(transformer = object()), + offload_policy = "group", + ) + responses = _post_while_rendering(app, backend, _interleaved("a fox", "a cat"), waiting = 2) + assert all(r.status_code == 200 for r in responses) + assert _groups(backend) == [sorted(["a fox", "a cat"])] + + +def test_a_moss_load_without_a_measured_win_still_renders_alone_through_the_route( + studio, monkeypatch +): + from test_image_batch_infra import _alone, _batched_calls + from test_image_batching_followups import _interleaved, _plan + + from core.inference.diffusion_families import MOSS_IMAGE_FAMILY_NAME, detect_family + + fake = types.ModuleType("core.inference.diffusion_moss_image") + fake.coalesce_key = lambda pipe: None + monkeypatch.setitem(sys.modules, "core.inference.diffusion_moss_image", fake) + app, backend, _saved = studio + backend.status = lambda: { + "loaded": True, + "repo_id": "x/moss", + "family": MOSS_IMAGE_FAMILY_NAME, + "base_repo": None, + } + _plan( + backend, + detect_family("", MOSS_IMAGE_FAMILY_NAME), + types.SimpleNamespace(transformer = object()), + offload_policy = "group", + ) + + async def run(): + transport = httpx.ASGITransport(app = app) + async with httpx.AsyncClient(transport = transport, base_url = "http://studio") as client: + backend.rendering = True + out = [ + await asyncio.wait_for( + client.post(path, json = body, headers = {"x-test-account": account}), 5 + ) + for path, account, body in _interleaved("a fox", "a cat") + ] + backend.rendering = False + return out + + responses = asyncio.run(run()) + assert all(r.status_code == 200 for r in responses) + assert _batched_calls(backend) == [] and sorted(_alone(backend)) == ["a cat", "a fox"] + + +# ------------------------------------------------------------------------------------------- eager wins need an enforceable path + + +def _eager_wins(monkeypatch, handle): + from core.inference import diffusion_cuda_graph as cg + + stored = {} + monkeypatch.setattr( + race, "record", lambda state, w, h, g, k, v, steps = None: stored.setdefault(k, v) is v + ) + clock = {"t": 0.0} + + def generate( + prompt = None, + prompts = None, + seeds = None, + seed = None, + batch_size = 1, + **kw, + ): + rows = list(prompts) if prompts else [prompt] + row_seeds = list(seeds) if seeds else [seed] + clock["t"] += ( + 5.0 if len(rows) == 1 else (6.0 if cg.eager_forced() else 11.0) + ) # the graphed arm loses + return {"images": [types.SimpleNamespace(p = p, s = s) for p, s in zip(rows, row_seeds)]} + + report = race.run_race( + generate, + types.SimpleNamespace(cuda_graphs = (handle,)), + idle = lambda: True, + width = 512, + height = 512, + sizes = (2,), + repeats = 4, + accuracy = False, + clock = lambda: clock["t"], + ) + return report["sizes"]["2"], stored + + +def test_an_eager_win_on_handles_that_cannot_drop_batched_graphs_is_not_promoted(monkeypatch): + """Block-graph handles record on demand and have no drop_batched: later coalesced calls would replay graphs, so + the eager verdict would not describe what serves. Withhold it.""" + blocks = types.SimpleNamespace(set_bypass = lambda on: None) # no drop_batched + verdict, stored = _eager_wins(monkeypatch, blocks) + eager_arm = verdict["arms"]["batched_eager"] + assert eager_arm["speedup_lb"] >= race.PROMOTE_LB, "the eager arm was fast enough" + assert ( + eager_arm["promoted"] is False and "cannot keep batched calls eager" in eager_arm["reason"] + ) + assert verdict["promoted"] is False + assert stored[2]["promoted"] is False + persisted_win = { + "promoted": True, + "arm": "batched_eager", + "path": "eager", + "neighbour_exact": True, + } + applied = race.effective_verdict(persisted_win, 2, types.SimpleNamespace(cuda_graphs = (blocks,))) + assert applied["promoted"] is False + + +def test_an_eager_win_on_handles_that_drop_their_batched_graphs_is_promoted(monkeypatch): + graphs = types.SimpleNamespace(set_bypass = lambda on: None, drop_batched = lambda size: 1) + verdict, stored = _eager_wins(monkeypatch, graphs) + assert verdict["promoted"] is True and verdict["arm"] == "batched_eager" + applied = race.effective_verdict(dict(verdict), 2, types.SimpleNamespace(cuda_graphs = (graphs,))) + assert applied["promoted"] is True diff --git a/studio/backend/tests/test_image_concurrency.py b/studio/backend/tests/test_image_concurrency.py index 393b4b9d3ac6..18f5cbc93d91 100644 --- a/studio/backend/tests/test_image_concurrency.py +++ b/studio/backend/tests/test_image_concurrency.py @@ -605,3 +605,47 @@ def second(): b.join(timeout = 5) assert outcome["second"] == "served" assert not engine._generate_lock.locked() + + +@pytest.mark.parametrize( + "intervals, shared", + [((0.5, 0.75), False), ((0.5, None), False), ((0.5, 0.5), True)], +) +def test_a_fast_cfg_interval_is_part_of_the_batch_key(studio, intervals, shared): + """Fast CFG (``cfg_interval_end`` -> FLUX.3 ``guidance_stop``) is set per pipeline call: requests with different + intervals never share one, the same interval still does.""" + app, backend, _saved = studio + plain = backend.generate + + def generate( + *, + prompt, + cfg_interval_end = None, + **kwargs, + ): + if cfg_interval_end is not None: + kwargs["cfg_interval_end"] = cfg_interval_end + return plain(prompt = prompt, **kwargs) + + backend.generate = generate + posts = [ + ( + "/api/inference/images/generate", + account, + _create(prompt, **({} if end is None else {"cfg_interval_end": end})), + ) + for account, prompt, end in ( + ("alice", "a fox", intervals[0]), + ("bob", "a cat", intervals[1]), + ) + ] + 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] + batched = _batched_calls(backend) + if shared: + assert len(batched) == 1 and batched[0]["kwargs"].get("cfg_interval_end") == 0.5 + else: + assert batched == [] and len(backend.calls) == 2 + assert sorted(str(c["kwargs"].get("cfg_interval_end")) for c in backend.calls) == sorted( + str(end) for end in intervals + )