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: a graphed race verdict holds only beside a live graph …
…of its own canvas

effective_verdict reduced the live batched graphs to batch sizes, so a batch-2 graph recorded while racing one canvas
satisfied a persisted graph-only batch-2 verdict for another canvas, whose requests then ran eager (GraphedForward keys
on tensor shapes) with seeded joins enabled. The race now labels every batched graph it records or replays with its
canvas token (width, height, guidance, steps, prompt layout) via batch_rows(canvas=...), stores the token on the
verdict as graph_canvas, and a graph-only win is admitted only when every step-graph handle holds a batch-size graph
carrying that label; otherwise the eager arm's verdict applies (legacy verdicts without the token included).

[skip ci]
  • Loading branch information
danielhanchen committed Nov 27, 2026
commit 705da24385d649fff5ced9182042ed254d6adb2c
53 changes: 47 additions & 6 deletions studio/backend/core/inference/diffusion_batch_race.py
Original file line number Diff line number Diff line change
Expand Up @@ -457,6 +457,7 @@ def run_race(
if guidance is not None:
common["guidance"] = float(guidance)
handles = tuple(getattr(state, "cuda_graphs", ()) or ())

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Settle deferred optimization before snapshotting race handles

When a freshly loaded model has speed_deferred=True, the race's own renders can trigger _engage_deferred_speed() on the third generate() call, which installs graphs and replaces state.cuda_graphs. This snapshot remains empty, however, so subsequent graph-backed measurements are recorded as path="eager", no eager comparison arm is run, and cleanup cannot drop the newly recorded batch graphs. An eager-only G2c PASS can consequently authorize a graph-backed win. Settle the deferred profile before measuring, or restart the race when its execution configuration changes.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in b8e1016bc2: batch_race now refuses (the endpoint's 409) while the load's speed profile is still deferred, so a race never starts on a load whose graphs can still be installed by its own renders. run_race also re-checks the graph handles and speed profile before saving each size; if they changed mid-race it saves nothing, drops the batch graphs the new handles recorded and refuses. Settling the profile inside the race was not done because that would engage speed outside generate()'s lock. Both tests fail without the fix.

canvas = canvas_token(width, height, guidance, steps, layout)
report: dict = {"width": int(width), "height": int(height), "guidance": guidance, "sizes": {}}

class _Aborted(Exception):
Expand All @@ -480,7 +481,7 @@ def batch(
raise _Aborted()
start = clock()
with (
cuda_graph.batch_rows(len(prompts), capture = capture),
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(),
Expand Down Expand Up @@ -535,6 +536,7 @@ def batch(
arms = verdicts,
size = size,
layout = layout_token(layout),
graph_canvas = canvas,
t = time.time(),
)
if accuracy:
Expand Down Expand Up @@ -652,6 +654,40 @@ def _neighbour_check(solo, batch, prompts: list, seeds: list, *, eager: bool) ->
}


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.

Expand Down Expand Up @@ -687,10 +723,11 @@ def effective_verdict(
state: Any,
layout: Any = None,
) -> dict:
"""The verdict as it applies now: one won on the graphed arm holds only while that batch-size graph exists (user
calls never record one) and for the prompt layout it was raced at (graphs key on tensor shapes, so 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."""
"""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
Comment on lines +858 to +859

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Revalidate eager winners when later races install matching graphs

If a size wins on the eager arm at canvas A, then a later race wins on the graph arm at canvas B with the same tensor shapes (for example, the same dimensions and guidance but a different step count), this early return still admits A as eager. The second race has installed a graph that GraphedForward will replay for A, and the request route does not force eager execution. Having drop_batched() only enforces the winner immediately after its race; it does not prevent later captures from changing that path. Consequently, an eager-only quality PASS and eager reproducibility checks can authorize graph-backed requests. Force the recorded eager path per request, or withhold its verdict whenever matching graphs have subsequently appeared.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 6332acb. effective_verdict now withholds any promoted eager-path verdict (an eager-arm win, or a graphed win falling back to its eager arm) while a step-graph handle holds a batch-size graph of that size. Graphs key on tensor shapes, and a later race at another canvas or step count can record one with the same shapes, so the eager path could no longer be guaranteed. Withheld sizes fall back to serial, and seeded joins are refused with them. A graphed win at its own canvas and layout still holds, and other sizes are unaffected. New test test_an_eager_win_is_withheld_once_a_later_race_records_a_graph_of_that_size fails before the change; 338 batching and graph tests pass.

held = batched_graph_sizes(state)
Expand All @@ -699,7 +736,11 @@ def effective_verdict(
same_layout = verdict.get("layout") is not None and layout_token(layout) == verdict.get(
"layout"
)
if int(size) in held and same_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):
Expand Down
30 changes: 28 additions & 2 deletions studio/backend/core/inference/diffusion_cuda_graph.py
Original file line number Diff line number Diff line change
Expand Up @@ -66,13 +66,27 @@ def _bg_planned_replay_enabled() -> bool:
)


_BATCH_CANVAS: "contextvars.ContextVar[Optional[str]]" = contextvars.ContextVar(
"unsloth_graph_batch_canvas", default = None
)


@contextlib.contextmanager
def batch_rows(rows: int, *, capture: bool = False):
"""Calls in this context carry ``rows`` requests; ``capture`` allows a new batched graph to record."""
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)


Expand Down Expand Up @@ -1519,6 +1533,8 @@ def __init__(
}
# 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
Expand Down Expand Up @@ -2304,6 +2320,10 @@ def __call__(self, *args, **kwargs):
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)
Expand Down Expand Up @@ -2332,6 +2352,12 @@ def __call__(self, *args, **kwargs):
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)
Expand Down
19 changes: 19 additions & 0 deletions studio/backend/tests/test_diffusion_cuda_graph.py
Original file line number Diff line number Diff line change
Expand Up @@ -2774,3 +2774,22 @@ def test_out_of_memory_recording_a_batch_falls_back_like_the_other_recorded_shap
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
73 changes: 71 additions & 2 deletions studio/backend/tests/test_image_batch_infra.py
Original file line number Diff line number Diff line change
Expand Up @@ -934,6 +934,7 @@ def test_a_graphed_verdict_admits_a_size_only_while_its_graph_exists(monkeypatch
"promoted": True,
"arm": "batched",
"layout": race.layout_token(()),
"graph_canvas": "c",
"arms": {"batched": {"promoted": True}, "batched_eager": {"promoted": False}},
}
both_win = {
Expand All @@ -942,7 +943,9 @@ def test_a_graphed_verdict_admits_a_size_only_while_its_graph_exists(monkeypatch
"layout": race.layout_token(()),
"arms": {"batched": {"promoted": True}, "batched_eager": {"promoted": True}},
}
handle = types.SimpleNamespace(cache = {"k2": object()}, _batched = {"k2": 2})
handle = types.SimpleNamespace(
cache = {"k2": object()}, _batched = {"k2": 2}, _batched_canvas = {"k2": {"c"}}
)
with_graph = types.SimpleNamespace(cuda_graphs = (handle,))
without = types.SimpleNamespace(
cuda_graphs = (types.SimpleNamespace(cache = {"k1": 1}, _batched = {}),)
Expand Down Expand Up @@ -1058,9 +1061,12 @@ def test_a_graphed_verdict_holds_only_for_the_prompt_layout_it_was_raced_at(monk
"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})
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
Expand Down Expand Up @@ -1193,3 +1199,66 @@ def test_block_graph_handles_never_count_a_graphed_winner_as_missing():
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