Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
Prev Previous commit
Next Next commit
Studio images: no shared call while FBCache can run; decode coalesced…
… images one at a time

FBCache decides whether to skip the remaining blocks from one mean residual over
the whole call, so in a shared call one request's image would decide another's.
An explicit FBCache load now serves serially, an AUTO cache admits no batch size
at a step count where it engages FBCache, and the race refuses; the static
schedule decides by step only and still batches.

The Qwen-Image single-frame VAE path decoded every image of a call in one pass.
Inside a call carrying several requests it now decodes one image per pass, so
the peak is one feature map and each image decodes exactly as its own request
would; a single user's multi-image call keeps its one batched pass.
  • Loading branch information
danielhanchen committed Nov 26, 2026
commit f5b1cec46bde5ab716c6df5c956210cd0810bd5a
30 changes: 30 additions & 0 deletions studio/backend/core/inference/diffusion.py
Original file line number Diff line number Diff line change
Expand Up @@ -5208,6 +5208,22 @@ def _default_request_batching(state: Any) -> dict[str, Any]:
}


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]
) -> dict[int, dict]:
Expand Down Expand Up @@ -18375,6 +18391,12 @@ def request_batching(self) -> Optional[dict[str, str]]:
"reason": "this family's pipeline renders one image per forward, so concurrent requests render one "
"at a time",
}
if not getattr(state, "cache_auto", False) and _step_cache_couples_rows(state, None):
return {
"mode": "serial",
"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",
}
policy = _default_request_batching(state)
if policy["mode"] == "serial" and policy.get("measurable"):
from . import diffusion_batch_race
Expand All @@ -18392,13 +18414,17 @@ def coalesce_batch_sizes(
width: int,
height: int,
guidance: Optional[float] = None,
steps: Optional[int] = 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."""
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)
winners = frozenset(k for k, v in measured.items() if v.get("promoted"))
losers = frozenset(k for k, v in measured.items() if not v.get("promoted"))
Expand Down Expand Up @@ -18469,6 +18495,10 @@ def idle() -> bool:
raise diffusion_batch_race.RaceRefused(
"this family's pipeline renders one image per forward"
)
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"])
Expand Down
20 changes: 20 additions & 0 deletions studio/backend/core/inference/diffusion_vae_single_frame.py
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,16 @@ def _tiles(vae: Any, z: Any, sample_space: bool) -> 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,
Expand All @@ -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:
Expand Down
2 changes: 2 additions & 0 deletions studio/backend/routes/inference.py
Original file line number Diff line number Diff line change
Expand Up @@ -56252,6 +56252,8 @@ def salvage(exc: BaseException) -> Optional[dict]:
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")

def fits(total: int) -> bool:
if sizes_of is None:
Expand Down
24 changes: 24 additions & 0 deletions studio/backend/tests/test_diffusion_vae_single_frame.py
Original file line number Diff line number Diff line change
Expand Up @@ -114,3 +114,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]
51 changes: 51 additions & 0 deletions studio/backend/tests/test_image_batch_infra.py
Original file line number Diff line number Diff line change
Expand Up @@ -749,3 +749,54 @@ async def 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 (and the other way round), so one request decides another's image."""
torch = pytest.importorskip("torch")
fbc = pytest.importorskip("diffusers.hooks.first_block_cache")
prev = torch.ones(2, 4, 8)

def decide(residual):
hook = types.SimpleNamespace(
threshold = 0.1,
state_manager = types.SimpleNamespace(
get_state = lambda: types.SimpleNamespace(head_block_residual = prev)
),
)
return (
fbc.FBCHeadBlockHook._should_compute_remaining_blocks.__wrapped__(hook, residual)
if hasattr(fbc.FBCHeadBlockHook._should_compute_remaining_blocks, "__wrapped__")
else fbc.FBCHeadBlockHook._should_compute_remaining_blocks(hook, residual)
)

still = prev.clone()
moved = prev.clone()
moved[1] *= 3.0
assert decide(still[:1]) is False # row 0 alone: skip
assert decide(moved) 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"