Skip to content
Closed
Show file tree
Hide file tree
Changes from 1 commit
Commits
Show all changes
17 commits
Select commit Hold shift + click to select a range
6fac8dc
Studio images: coalesce concurrent requests across accounts
danielhanchen Nov 26, 2026
80a7423
Studio images: coalesce plain text-to-image on /images/generate
danielhanchen Nov 26, 2026
d068da9
Studio images: let seeded requests join a batch behind an opt-in
danielhanchen Nov 26, 2026
a40d678
Studio images: serve the generation slot first come, first served
danielhanchen Nov 26, 2026
7d3e9d2
Studio images: keep per-account LoRAs and embeddings out of shared ba…
danielhanchen Nov 26, 2026
ad1d92c
Studio images: group batch members by what their family encodes per call
danielhanchen Nov 26, 2026
2428129
Studio images: one Stop rule for batched requests, across accounts
danielhanchen Nov 26, 2026
eae66f8
Studio images: no live preview for a batch shared across accounts
danielhanchen Nov 26, 2026
20b7f42
Studio images: batch a static-shape load only at sizes it already com…
danielhanchen Nov 26, 2026
17f3a29
Studio images: one member's failure no longer fails the whole batch
danielhanchen Nov 26, 2026
02a10ae
Studio images: a batch keeps its place in line; follow-up passes go f…
danielhanchen Nov 26, 2026
771a1f0
Studio images: record the shared call in recipes; pin coalesced calls
danielhanchen Nov 26, 2026
077bd66
Studio images: reserved batches get their own worker; tighter batch keys
danielhanchen Nov 26, 2026
e0e4311
Studio images: an idle reservation never stalls the line; recovery ke…
danielhanchen Nov 26, 2026
208b5a6
Studio images: CUDA-graph loads serve serially, and status says so
danielhanchen Nov 26, 2026
3be8231
Merge commit '208b5a6673f39ec7658896259fb200c2f436b25d' into pr-19667…
danielhanchen Nov 26, 2026
07acb18
Add staging CI workflows for unslothai/unsloth#19667
danielhanchen Nov 26, 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: an idle reservation never stalls the line; recovery ke…
…eps admitted sizes

- A reserved slot turn that sits first in line, unclaimed, with the
  slot free steps back one place after 0.5 s. If every worker of an
  executor waits behind it, its owner may have no worker to run on;
  the waiters now step past it and the queue drains on any pool, not
  only on the dedicated batch pool.
- Failure recovery consults the static batch-size filter on every
  split: a half whose size this load has not compiled keeps only its
  admitted prefix, and the rest render alone.

[skip ci]
  • Loading branch information
danielhanchen committed Nov 26, 2026
commit e0e431177d61de0f64021bb46caefb7bd37dabd8
22 changes: 22 additions & 0 deletions studio/backend/core/inference/diffusion.py
Original file line number Diff line number Diff line change
Expand Up @@ -4918,6 +4918,8 @@ def _converted_shards_pread(dtype: Any, small_host: Any) -> Any:
_RESERVED_SLOT_TURN: contextvars.ContextVar[Optional[object]] = contextvars.ContextVar(
"unsloth_reserved_slot_turn", default = None
)
# How long a reserved, unclaimed turn may idle first in line with the slot free before a waiter steps past it.
_RESERVED_TURN_GRACE_S = 0.5
_SLOT_FOLLOW_UP: contextvars.ContextVar[bool] = contextvars.ContextVar(
"unsloth_slot_follow_up", default = False
)
Expand Down Expand Up @@ -5006,6 +5008,8 @@ def __init__(self) -> None:
self._slot_turn_changed = threading.Condition(threading.Lock())
# Called (from any thread) when the line moves or the slot frees: a waiting batch wakes on it, not a poll.
self._slot_listeners: list[Callable[[], None]] = []
# Reserved turns no generation has claimed yet: a waiter may step past one that idles at the front.
self._unclaimed_turns: set = set()
self._state: Optional[_LoadState] = None
self._loading: Optional[_LoadingState] = None
# Bumped on begin_load/unload so a superseded worker neither commits nor stamps progress
Expand Down Expand Up @@ -5148,6 +5152,7 @@ def reserve_slot_turn(self) -> object:
turn = object()
with self._slot_turn_changed:
self._slot_turns.append(turn)
self._unclaimed_turns.add(turn)
return turn

def release_slot_turn(self, turn: object) -> None:
Expand All @@ -5174,6 +5179,7 @@ def jump_slot_queue(self):

def _leave_slot_turn(self, turn: object) -> None:
with self._slot_turn_changed:
getattr(self, "_unclaimed_turns", set()).discard(turn)
try:
self._slot_turns.remove(turn)
except ValueError:
Expand All @@ -5183,10 +5189,25 @@ def _leave_slot_turn(self, turn: object) -> None:

def _await_slot_turn(self, turn: object, cancel: threading.Event) -> None:
"""Blocks until ``turn`` is the oldest waiting generation; a cancel still ends the wait within 0.1 s."""
idle_since = None
with self._slot_turn_changed:
while self._slot_turns[0] is not turn:
if cancel.is_set():
raise RuntimeError(DIFFUSION_CANCELLED_MSG)
head = self._slot_turns[0]
if head in self._unclaimed_turns and not self._generate_lock.locked():
# A reserved turn first in line with the slot free and no generation claiming it: its owner
# may have no worker (every one waits here). After a grace it steps back one place.
now = time.monotonic()
idle_since = idle_since if idle_since is not None else now
if now - idle_since >= _RESERVED_TURN_GRACE_S:
self._slot_turns.popleft()
self._slot_turns.insert(1, head)
self._slot_turn_changed.notify_all()
idle_since = None
continue
else:
idle_since = None
self._slot_turn_changed.wait(timeout = 0.1)

@contextmanager
Expand All @@ -5200,6 +5221,7 @@ def _generation_slot(self, cancel: threading.Event):
if reserved is not None and reserved in self._slot_turns:
# A coalesced batch keeps the place it took when it opened.
turn = reserved
self._unclaimed_turns.discard(turn)
else:
turn = object()
if reserved is not None or _SLOT_FOLLOW_UP.get():
Expand Down
12 changes: 9 additions & 3 deletions studio/backend/core/inference/image_request_batching.py
Original file line number Diff line number Diff line change
Expand Up @@ -145,11 +145,15 @@ async def _render_group(
shared_outcome: Callable[[BaseException], bool],
splittable: Optional[Callable[[BaseException], bool]],
salvage: Optional[Callable[[BaseException], Optional[dict[str, Any]]]],
fits: Optional[Callable[[int], bool]] = None,
) -> dict[int, dict[str, Any]]:
"""Renders ``group`` as one call; ``{id(member): part}`` for every member it rendered. A failure keeps the
images that finished; a refusal, a ValueError or an OOM splits the rest by member, so one member's error never
fails the others. Members left out render alone; only a shared outcome raises."""
fails the others. Members left out render alone; only a shared outcome raises. Every call, a recovery split
included, uses a size ``fits`` admits."""
group = [member for member in group if not member.future.done()]
if fits is not None:
group = _fitting_prefix(group, fits)
if len(group) < 2:
return {}
prompts = [member.prompt for member in group for _ in member.seeds]
Expand Down Expand Up @@ -179,7 +183,7 @@ async def _render_group(
middle = (len(rest) + 1) // 2
for half in (rest[:middle], rest[middle:]):
done.update(
await _render_group(half, run_batch, shared_outcome, splittable, salvage)
await _render_group(half, run_batch, shared_outcome, splittable, salvage, fits)
)
return done

Expand Down Expand Up @@ -295,7 +299,9 @@ async def generate(
sum(len(member.seeds) for member in members),
)
try:
done = await _render_group(members, run_batch, shared_outcome, splittable, salvage)
done = await _render_group(
members, run_batch, shared_outcome, splittable, salvage, fits
)
except Exception as exc:
_share(exc, members[1:], owner)
raise
Expand Down
78 changes: 78 additions & 0 deletions studio/backend/tests/test_image_concurrency_review.py
Original file line number Diff line number Diff line change
Expand Up @@ -824,3 +824,81 @@ def post(account, body):
assert calls[0] == ["a fox", "a cat"]
assert sorted(calls[1:]) == ["a hen", "an owl"]
assert len(saved) == 4


def test_an_unclaimed_reservation_cannot_stall_waiters_that_hold_every_worker():
"""The recheck's schedule: one pool runs everything, and both of its workers wait behind a reservation whose
owner then has no worker. The waiters step past the idle reservation and the queue drains."""
from concurrent.futures import ThreadPoolExecutor

from core.inference.diffusion import DiffusionBackend, reserved_slot_turn

engine = DiffusionBackend()
started, release = threading.Event(), threading.Event()
entered = []

def active():
with engine._generation_slot(threading.Event()):
started.set()
release.wait(5)

def later(name):
with engine._generation_slot(threading.Event()):
entered.append(name)

def earlier(turn):
with reserved_slot_turn(turn), engine._generation_slot(threading.Event()):
entered.append("reserved")

with ThreadPoolExecutor(max_workers = 2) as pool:
holder = pool.submit(active)
assert started.wait(5)
turn = engine.reserve_slot_turn()
first = pool.submit(later, "later 1")
_wait_until(lambda: len(engine._slot_turns) == 2)
release.set()
holder.result(timeout = 5)
second = pool.submit(later, "later 2")
_wait_until(lambda: len(engine._slot_turns) == 3)
reserved = pool.submit(earlier, turn)
for future in (first, second, reserved):
future.result(timeout = 10)
assert sorted(entered) == ["later 1", "later 2", "reserved"]
assert not engine._slot_turns and not engine._unclaimed_turns


def test_sdxl_keys_break_prompts_apart_in_both_tokenizers():
from core.inference.diffusion import coalesce_prompt_key

family = types.SimpleNamespace(name = "sdxl", textual_inversion = "sdxl")
pipe = _clip_pipe(tokenizer_2 = _ClipWords(), text_encoder_2 = object())
assert coalesce_prompt_key(family, pipe, "(red) BREAK blue") != coalesce_prompt_key(
family, pipe, "(red) blue"
)
# A pipe with a tokenizer but no encoder to count for never batches.
tokenizer_only = types.SimpleNamespace(tokenizer = _ClipWords())
assert coalesce_prompt_key(family, tokenizer_only, "(red) blue") is None


def test_failure_recovery_renders_only_admitted_sizes():
attempts = []

async def run_batch(
prompts,
seeds,
owners = None,
):
attempts.append(len(seeds))
if len(seeds) == 4:
raise ValueError("controlled batch failure")
return _echo(prompts, seeds)

results = _queue_members(
[("0", 1), ("1", 1), ("2", 1), ("3", 1)],
run_batch,
fits = lambda size: size == 4,
splittable = lambda exc: isinstance(exc, ValueError),
)
# The halves (size 2) are not admitted: every member falls back to rendering alone.
assert attempts == [4]
assert results == [None, None, None, None]