Skip to content
Closed
Show file tree
Hide file tree
Changes from 1 commit
Commits
Show all changes
18 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
f4aaf9c
Studio images: poll review-test conditions by count, not by clock dea…
danielhanchen Nov 26, 2026
aa2e573
Merge origin/main into studio-image-concurrency
danielhanchen Nov 26, 2026
d332c7f
Merge commit 'aa2e57379586099b1c4122b5e9172c5467364929' into pr-19667-ci
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: keep per-account LoRAs and embeddings out of shared ba…
…tches

A batched call resolves LoRA ids, hosted adapters (with their HF token)
and textual-inversion embeddings under the leader's account, and an
embedding trigger matches in every member's prompt. A request that sets
any LoRA, or whose account owns embeddings on a family that applies
them, now carries its account in the batch key, so it batches only with
its own account's requests.
  • Loading branch information
danielhanchen committed Nov 26, 2026
commit 7d3e9d251c08d10dcae1c026fe0c62ba76c077e7
16 changes: 16 additions & 0 deletions studio/backend/core/inference/diffusion.py
Original file line number Diff line number Diff line change
Expand Up @@ -17856,6 +17856,22 @@ def generation_waiter(self, cancel: threading.Event):
with self._generation_cancel_lock:
self._queued_generate_cancels.discard(cancel)

def coalesce_plan(self, prompt: str, has_loras: bool) -> Optional[tuple[tuple, bool]]:
"""``(prompt_key, private)`` for joining a batch, or None when this request must render alone. ``private``:
a per-account resource (a LoRA, or an embedding this account owns) could apply, so the request batches only
with its own account. Runs in the requesting account's context."""
state = self._state
if state is None:
return None
private = bool(has_loras)
if not private and getattr(state.family, "textual_inversion", None) is not None:
# Embeddings come from the leader's folder and match triggers in every member's prompt.
try:
private = bool(diffusion_embeddings.list_embeddings())
except Exception: # noqa: BLE001 - an unreadable folder may still hold one
private = True
return (), private

@contextmanager
def generation_rider(self, cancel: threading.Event):
"""A request riding another request's batched call: a Stop from its account sets ``cancel`` even while
Expand Down
29 changes: 22 additions & 7 deletions studio/backend/routes/inference.py
Original file line number Diff line number Diff line change
Expand Up @@ -55969,6 +55969,17 @@ async def _coalesced_image_generate(
return None
if family and getattr(detect_family("", family), "layer_count", 0):
return None
# LoRA ids, hosted adapters (with their HF token) and textual-inversion embeddings resolve under the account
# that runs the call, the leader: a request that could use any of them batches with its own account only.
plan = getattr(backend, "coalesce_plan", None)
loras = generate_kwargs.get("loras")
if plan is not None:
decided = await asyncio.to_thread(plan, prompt, bool(loras))
if decided is None:
return None
prompt_key, private = decided
else:
prompt_key, private = (), bool(loras)

ticket = GenerationTicket()
stopped = TicketStopEvent(ticket)
Expand Down Expand Up @@ -56010,13 +56021,17 @@ async def run_batch(prompts: list[str], seeds: list[int]) -> dict:
raise RuntimeError(DIFFUSION_CANCELLED_MSG) from exc
raise

# No account: requests from different accounts with the same settings share one call.
key = tuple(
sorted(
(name, _frozen_kwarg(value))
for name, value in generate_kwargs.items()
if name not in _COALESCE_KEY_IGNORED
)
# No account unless a per-account resource could apply: then only this account's requests share the call.
key = (
current_account_id() if private else None,
prompt_key,
tuple(
sorted(
(name, _frozen_kwarg(value))
for name, value in generate_kwargs.items()
if name not in _COALESCE_KEY_IGNORED
)
),
)

def cancelled(exc: BaseException) -> bool:
Expand Down
93 changes: 93 additions & 0 deletions studio/backend/tests/test_image_concurrency_review.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
# SPDX-License-Identifier: AGPL-3.0-only
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0

"""Coalescing review fixes: per-account resources, Stop, previews, compiled shapes, partial failures, FIFO
follow-ups, recipes and per-family prompt grouping."""

from __future__ import annotations

import asyncio
import sys
import threading
import types
from pathlib import Path

import pytest

from core.inference import image_request_batching as batching

sys.path.insert(0, str(Path(__file__).resolve().parent))
from test_image_concurrency import ( # noqa: E402,F401 (fixture)
_Backend,
_batched_calls,
_create,
_openai,
_post_while_rendering,
_until,
_waiting,
studio,
)
from utils.account_context import current_account_id # noqa: E402


def _real_plan(backend, family):
"""Bind the real engine's coalesce_plan onto the fake, over a stand-in load state."""
from core.inference.diffusion import DiffusionBackend

backend._state = types.SimpleNamespace(family = family, pipe = None)
backend.coalesce_plan = types.MethodType(DiffusionBackend.coalesce_plan, backend)


def test_requests_with_loras_batch_only_with_their_own_account(studio):
app, backend, _saved = studio
lora = {"loras": [{"id": "style-lora", "weight": 0.8}]}
posts = [
("/v1/images/generations", "alice", _openai("a fox", **lora)),
("/v1/images/generations", "bob", _openai("a cat", **lora)),
("/v1/images/generations", "alice", _openai("an owl", **lora)),
]
responses = _post_while_rendering(app, backend, posts, waiting = 3)
assert all(r.status_code == 200 for r in responses), [r.text for r in responses]
[call] = _batched_calls(backend)
assert call["account"] == "alice" and sorted(call["prompts"]) == ["a fox", "an owl"]
[alone] = [c for c in backend.calls if c["prompts"] is None]
assert alone["account"] == "bob"


def test_an_account_with_embeddings_never_shares_a_call_with_another_account(studio, monkeypatch):
import core.inference.diffusion_embeddings as embeddings

app, backend, _saved = studio
_real_plan(backend, types.SimpleNamespace(name = "sdxl", textual_inversion = "sdxl"))
owned = {"bob": ["secret-style"]}
monkeypatch.setattr(
embeddings, "list_embeddings", lambda kind = None: owned.get(current_account_id(), [])
)
posts = [
("/v1/images/generations", "alice", _openai("a fox")),
("/v1/images/generations", "bob", _openai("a cat in secret-style")),
("/v1/images/generations", "carol", _openai("an owl")),
]
responses = _post_while_rendering(app, backend, posts, waiting = 3)
assert all(r.status_code == 200 for r in responses)
[call] = _batched_calls(backend)
assert sorted(call["prompts"]) == ["a fox", "an owl"]
assert [c["account"] for c in backend.calls if c["prompts"] is None] == ["bob"]


def test_the_engine_plan_marks_loras_and_owned_embeddings_private(monkeypatch):
import core.inference.diffusion_embeddings as embeddings
from core.inference.diffusion import DiffusionBackend

engine = DiffusionBackend()
assert engine.coalesce_plan("a fox", False) is None # nothing loaded
engine._state = types.SimpleNamespace(family = types.SimpleNamespace(name = "z-image"), pipe = None)
assert engine.coalesce_plan("a fox", False) == ((), False)
assert engine.coalesce_plan("a fox", True) == ((), True)
engine._state = types.SimpleNamespace(
family = types.SimpleNamespace(name = "sdxl", textual_inversion = "sdxl"), pipe = None
)
monkeypatch.setattr(embeddings, "list_embeddings", lambda kind = None: [])
assert engine.coalesce_plan("a fox", False)[1] is False
monkeypatch.setattr(embeddings, "list_embeddings", lambda kind = None: ["x"])
assert engine.coalesce_plan("a fox", False)[1] is True