Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
31 commits
Select commit Hold shift + click to select a range
b24c827
Studio images: family batch adapters, measured batching race and per-…
danielhanchen Nov 26, 2026
28a9ecb
Studio images: no coalescing wait at a shape with no admitted size; r…
danielhanchen Nov 26, 2026
f437380
Studio images: a batch size that loses the race drops its CUDA graphs
danielhanchen Nov 26, 2026
58e0db6
Studio images: test that a measured win coalesces at the winning size…
danielhanchen Nov 26, 2026
6c55fd6
Studio images: members a fired batch could not take coalesce again be…
danielhanchen Nov 26, 2026
f5b1cec
Studio images: no shared call while FBCache can run; decode coalesced…
danielhanchen Nov 26, 2026
e8879fb
Studio images: FBCache coupling test holds with the length guard and …
danielhanchen Nov 26, 2026
731542d
Studio images: free the failed call before the halved retry; key race…
danielhanchen Nov 26, 2026
a8e5e17
Studio images: an edit at a new reference size never evicts a text-to…
danielhanchen Nov 26, 2026
9f0b357
Studio images: batch-size graphs get their own pool and graph budget;…
danielhanchen Nov 26, 2026
51c1217
Studio images: the race's batched-eager arm really runs with the grap…
danielhanchen Nov 26, 2026
bae160e
Studio images: key batching race verdicts by card topology
danielhanchen Nov 26, 2026
95de9ec
Studio images: price and scope batched CUDA graphs by what they hold
danielhanchen Nov 27, 2026
fe47b92
Studio images: seeded joins, eager wins and static compiles follow wh…
danielhanchen Nov 27, 2026
1a97100
Studio images: pin the Fast CFG interval in the batch key
danielhanchen Nov 27, 2026
53efa94
Studio images: the eager arm stays eager, graphed verdicts keep their…
danielhanchen Nov 27, 2026
8ca902e
Studio images: an aborted race size drops the batched graphs its warm…
danielhanchen Nov 27, 2026
3221b2c
Merge remote-tracking branch 'origin/main' into studio-batch-infra-main
danielhanchen Nov 27, 2026
92efbc1
Studio images: block graph handles never count a graphed race winner …
danielhanchen Nov 27, 2026
705da24
Studio images: a graphed race verdict holds only beside a live graph …
danielhanchen Nov 27, 2026
0d7d96d
Studio images: a measured batching win serves only with a passing G2c…
danielhanchen Nov 27, 2026
395de8b
Studio images: the race's replay check compares row 0 with its solo r…
danielhanchen Nov 27, 2026
e5b8e38
Studio images: the quality gate reads the path a race really ran, and…
danielhanchen Nov 27, 2026
71e85dc
Studio images: the race picks a qualifying arm first and refuses size…
danielhanchen Nov 27, 2026
67a7dcd
Studio images: a batched warm-up that runs out of memory keeps the si…
danielhanchen Nov 27, 2026
0dac8dd
Merge remote-tracking branch 'origin/main' into studio-batch-g2c-gate
danielhanchen Nov 27, 2026
7859edb
Studio images: the race never measures across a change in how the loa…
danielhanchen Nov 27, 2026
9173835
Studio images: the route leaves MOSS to the engine, and an eager win …
danielhanchen Nov 27, 2026
6e6b15b
Studio images: an adapted load never consumes the adapter-free batchi…
danielhanchen Nov 27, 2026
6332acb
Studio images: withhold an eager batching win once a same-size graph …
danielhanchen Nov 27, 2026
9993ecd
Merge remote-tracking branch 'origin/main' into studio-batch-g2c-gate
danielhanchen Nov 27, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
388 changes: 330 additions & 58 deletions studio/backend/core/inference/diffusion.py

Large diffs are not rendered by default.

160 changes: 160 additions & 0 deletions studio/backend/core/inference/diffusion_batch_adapters.py
Original file line number Diff line number Diff line change
@@ -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
)
158 changes: 158 additions & 0 deletions studio/backend/core/inference/diffusion_batch_quality.py
Original file line number Diff line number Diff line change
@@ -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
(``<cache>/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
Loading