Repository navigation
Studio images: coalesce identical requests across users, batch plain /images/generate, first-come-first-served slot - #19667
Conversation
The image batch key no longer holds the account, so requests from different users with the same model, adapters, size, steps, guidance, negative prompt and other render settings share one pipeline call. Each member still gets only its own images through its own future. - A shared Stop reaches only the leader's own account; members from other accounts render alone instead. - A member's own Stop leaves the batch (generation_rider), even while another account's call holds the slot. - Prompt-derived result fields are not shared across accounts. - A full batch stops collecting and the next request opens another. - UNSLOTH_STUDIO_IMAGE_BATCH_MAX defaults to 8; the engine's OOM halving still splits a chunk that does not fit.
The Studio Images page and bench clients call /images/generate, which never batched. A plain Create run (no init image, mask, reference images, ControlNet, Detailer, hires, upscale, variation seed, X/Y grid, prompt or seed lists, or prompt upsampling) now goes through the same coalescer as /v1/images/generations. - Every generate() argument other than prompt, seed and count is part of the batch key, so only renders that would match share a call. - An idle engine with no batch collecting renders at once with no extra status read, so a single user's latency is unchanged. - FLUX.3, Anima and layered models stay batch-1. - Queued jobs, X/Y cells and the chat image tool keep their own path.
Bench clients and recipe replays send a seed, so nothing coalesced for them. With UNSLOTH_STUDIO_IMAGE_BATCH_SEEDED=1 a seeded request joins a waiting batch and keeps the per-image seeds a lone request would use (seed, seed + 1, ...), passed per member through seeds=. Off by default: a batched render can differ slightly in pixels from the same seed rendered alone.
Waiting generations each polled the slot lock every 0.1 s, so the thread that happened to wake first won and a request could be overtaken by later arrivals. Each generation now takes a ticket on arrival and only the oldest waiter competes for the lock; the next ticket becomes the head as soon as one is admitted. Cancel and timeout behaviour is unchanged: a queued waiter still sees its cancel within 0.1 s and leaves the queue, a teardown fence still holds the head (which keeps its place), and the image queue drain still waits on direct runs as before.
Codex Review Summary: ✅ CompletedThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
…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.
Some families render a prompt differently, or gain nothing, inside a batch, so the batch key now carries a per-prompt group: - MiniMax-H3-Image loops per image when resident: never batched. - Qwen-Image-2.1 builds its RoPE layout from row 0: equal prompt token lengths only. - FLUX.1 / Kontext pad T5 to one bucket per call: 256 and 512 apart. - SD / SDXL weight and chunk prompts per call: prompt weighting and the 77-token chunk count must match. A prompt that cannot be measured renders alone.
- The Stop route stops this account's waiting and riding batched work before its foreign-generation early return. Under managed accounts a member riding another account's call saw that call as foreign, so its Stop answered cancelled: false while its images still saved. - cancel_generate applies one rule in every branch: Stop ends this account's denoising generation and all of its waiting and riding batched requests. - A Stop during a model change sets only the caller's queued requests; each queued cancel now records its account.
The preview decodes row 0 of each forward. An OOM split or a Qwen-Image-2.1 equal-length run can start a forward with another account's image, which the leader would then see. A batched call whose members come from more than one account now runs with the preview off; a batch of one account's requests keeps it.
…piled A static compile and CUDA graphs key their artifacts on the batch, so a coalesced call of a new size compiled or captured inside the slot while every other request waited, and an OOM split resets every graph. DiffusionBackend.coalesce_batch_sizes reports the batch sizes this load already compiled at the requested size (None when shapes are dynamic). A batch keeps the longest arrival-order run of members whose image total is one of them; the rest render alone.
- A failed batched call keeps the images that finished: the engine attaches them (in job order) to the exception, and the members whose images all finished get them instead of rendering again. Never after a Stop. - A ValueError, a memory refusal or an OOM that survived halving splits the remaining members in two and retries each half, so the member that caused it ends up rendering alone and only it sees the error. - A blank prompt, which fails validation for the whole call, renders alone.
…irst - A coalesced batch takes its slot ticket when it opens (reserve_slot_turn), so requests arriving while it collects members queue behind it, and a leader left alone renders in that place instead of at the back. - The waiting batch wakes from the slot itself (add_slot_listener on a release or a line change) instead of a 50 ms poll; a 250 ms timeout covers lock holders outside the line. - Follow-up passes of a request already admitted go to the front: X/Y cells after the first, Detailer crop inpaints (slot_follow_up), and the Detailer's segmenter pass (jump_slot_queue). The head of the line rechecks its place after taking the lock. The hires refine already runs inside its base pass's slot.
- Each coalesced image's recipe and gallery record carry coalesced_batch_size and coalesced_index: its pixels come from a forward of that size, so a solo replay of the seed lands close to it, not on it. Images rendered alone carry neither. - A coalesced call is always pinned to the load its settings were read for (expected_load), so a model swapped in while the batch collected is refused and each member retries, instead of every member rendering on the new model. [skip ci]
- A coalesced batch's own call (and a leader left alone) runs on a small dedicated pool. Its slot turn is first in line, while requests queued behind that turn could hold every worker of the shared image pool, so the batch could never start and nothing ran. - A variation request with a random subseed (variation_strength set, no variation_seed) renders alone: per-member seeds would replace the base seed it repeats across its images. - The SD / SDXL batch key counts the conditioning chunks the weighted encode actually builds (tokenize_chunks, BREAK and comma backtracking included) in every CLIP encoder, weighted and unweighted, so a member is never padded with an extra empty chunk.
…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]
|
Codex Review: Didn't find any major issues. You're on a roll. Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
|
The staging Both hits are poll deadlines: # 5 s poll deadlines for queued image requests and teardown: descheduling only delays the poll.
("test_image_concurrency_review.py", "test_a_stop_during_a_teardown_reaches_only_the_callers_queued_requests"),
("test_image_concurrency_review.py", "_wait_until"),This passes on main. It only appears with this branch because the file is new. |
A CUDA graph replays one batch size: a coalesced call of a new size captures inside the slot (seconds, plus its own memory pool) while every other request waits, and an OOM split drops every graph. Serial graph replay already keeps the card busy; a G4 FLUX.2 Klein trial with 4 clients measured 129.5 images/min serial against 127.1 batched. - DiffusionBackend.request_batching reports how concurrent requests are served on the load: any, compiled_sizes (static compile, only batch sizes already compiled) or serial (CUDA graphs), with the reason. - coalesce_batch_sizes follows it, so a graph load is serial by an explicit rule rather than by an empty compiled-size set. - /images/status carries request_batching. [skip ci]
…dline The two waits in test_image_concurrency_review.py compared time.monotonic() against a deadline, which the backend CI parallel-isolation scan flags as a timing claim under -n 4. They only wait for an ordering condition, so poll a fixed number of times instead.
Conflict in studio/backend/models/inference.py: DiffusionStatusResponse gained fp8_gemm on main and request_batching here; both fields are kept.
A Stop landing after the engine's last cancel check, while the leader is still a registered coalescing waiter, sets its event and is answered as cancelled, yet the leader still returned and saved its images. Recheck the event once the waiter is deregistered, on both the batched and the reserved-turn solo path, as members already do. [skip ci]
|
Codex Review: Didn't find any major issues. 🎉 Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
Requests arriving interleaved through the route: two Qwen-Image-2.1 prompt lengths never share a call, MiniMax-H3-Image requests render at once without opening a batch, FLUX.1 members group by T5 bucket, and an SDXL prompt over 75 tokens never shares a call with short ones while two long prompts of the same chunk count still batch. All fail on a40d678, before members were grouped by what their family encodes per call.
The batch key tokenizes an arriving prompt while another request renders. A fast tokenizer used from two threads at once raises "Already borrowed" in whichever call loses, so an arrival could fail the running render (seen on Qwen-Image-2.1 on A100: the in-flight request returned 500) or drop itself out of batching. The key now reads a copy of each fast tokenizer, made once per load from inside the generation slot, and only for loads whose keys tokenize (Qwen-Image-2.1, FLUX.1, SD / SDXL). Without a copy the prompt renders alone and the original is never touched.
On an A100 with Studio Auto (INT8), two equal-length Qwen-Image-2.1 prompts in one call render 1.02x to 1.03x faster than serially, and each member lands 34.6 to 36.8 dB PSNR from its solo render. Auto loads with CUDA graphs serve serially anyway. Like MiniMax-H3-Image, its requests now render alone without waiting to coalesce. The docstrings no longer claim equal lengths match a solo render exactly.
…s from host Measured per family with a batch of 4, resident loads ran 0.81x to 1.19x of serial while every member drifted from its solo render (LPIPS up to 0.31). Only loads streaming the denoiser from host gained: FLUX.2-dev 3.35x, Ideogram-4 2.48x, HiDream-I1 1.47x, since one shared call pays for one pass of weight copies. request_batching now reports serial (resident weights) unless the load uses model, sequential or streaming offload, or group offload with any group unpinned, and coalesce_plan returns None for every serial load, so those requests render one at a time without waiting to coalesce. The per-family exclusions stay. [skip ci]
|
@codex review |
|
Codex Review: Didn't find any major issues. 🎉 Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
MOSS-Image's forward runs every transformer layer once per sample, so a batch of B under group or sequential offload streams the weights B times: no throughput gain, and up to B times the latency for the first member. Like MiniMax-H3-Image, its requests now render alone without waiting to coalesce.
torchao's NVFP4 dynamic-activation config and the ComfyUI dynamic NVFP4 linear take each linear's activation global scale from the whole call's amax. In a shared call, one request's prompt would set the activation quantization of every other member, so their pixels would depend on who they were batched with. request_batching now reports serial with the offending layer when any denoiser layer does this, reusing the CFG batch check, and those requests render one at a time. Studio's own NVFP4 linear freezes its scale and FP8 / INT8 scale per row, so those loads still batch. [skip ci]
|
@codex review |
|
Codex Review: Didn't find any major issues. You're on a roll. Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
…size CUDA graphs (#19837) ## Summary Builds on #19667 (merged). Concurrent image requests from different accounts now share one pipeline call only where it is measured to help, and the batching decision moves from blanket per-family refusals to a per-family capability plus a measured verdict per card, load and shape. Unmeasured loads keep the #19667 rules, so nothing changes until a race on that card proves a win. **Where Auto now batches.** In the measured runs, Auto batched only HiDream-I1-Fast streamed on an A100 40GB. Its race promoted batch 4 (median 1.44x, lower bound 1.40x) and batch 2 (lower bound 1.06x), and 16 concurrent users went from 6.4 to 8.0 images/min with p95 down from 149 s to 120 s. FLUX.2 klein 4B resident on RTX PRO 6000 measured 1.037x at batch 2 and 1.055x at batch 4, below the 1.05 lower bound, so it stays one request at a time, byte-identical to before. **Klein accuracy.** At batch 4, klein's rows are 0.064 LPIPS from the eager reference, against 0.028 for solo renders, so the paired gate fails at eps 0.01. This is the existing batch-shape behaviour of the INT8 path: neighbour invariance is bit-identical at batch 2 and 4, and a single request with `batch_size` 4 gets the same drift today. Auto does not batch klein. **Family capability.** `batched_forward` is read from the family object with `getattr`. `DiffusionFamily` is unchanged here; families opt in by setting the attribute in their own PRs. ## What changed **Family capability (`core/inference/diffusion_batch_adapters.py`, new)** - A family says whether its pipeline call fuses a list of prompts into one forward with `batched_forward` (bool) on the family object. Unset keeps today's answer: FLUX.3, Anima, layered, MiniMax-H3-Image, MOSS and Qwen-Image-2.1 render one image per forward; everything else uses the diffusers list call. - `BatchAdapter` (`prepare` gives the row layout key, `compatible`, `denoise_batched`, `split`) with `DefaultAdapter` for the list call (FLUX.1 T5 bucket, SD / SDXL CLIP chunk counts). A family can set `batch_adapter` for its own row layout. - The route refusal (FLUX.3 / Anima / layered), the key refusal (H3 / MOSS / Qwen-Image-2.1) and the in-request chunking rule now read the capability, so a family that gains a batched forward is admitted without touching the batching code. **Measured race (`core/inference/diffusion_batch_race.py`, new)** - `POST /api/inference/images/batching/race` (owner only) races k requests served one at a time against the same k in one call, at sizes 2 and 4 by default, each arm including encode, denoise and decode, interleaved in random order over several repeats. With CUDA graphs on it also races the batched call with the graphs bypassed (`set_bypass`). Static compile races only sizes already compiled. - It runs only on an idle engine: it is refused when a request holds or waits for the slot, and it stops (persisting nothing for that size) as soon as one starts waiting. - A size is promoted only when the one-sided 95% lower bound of the speedup is at least 1.05x (the smaller of a Student t bound on the log ratios and a percentile bootstrap) and the batched p95 request latency is at most 3% above serial. Losers are persisted too. - Verdicts go through `diffusion_probe_cache.Namespace("batch_race")`: keyed by torch, driver, card and env (the probe fingerprint) plus model and revision, family, denoiser class, precision, speed mode, attention backend, offload placement, graph and compile state, step cache, canvas, guidance, step count and batch size. - The step count is in the key because the fixed per-call cost of encode and decode weighs more at few steps. - It also checks neighbour invariance at the batch shape (the target row first and last, only the neighbours' prompts and seeds changed, plus an A/A repeat) and whether a member equals its solo render. - Each verdict stores its winning arm (graph replay at that batch size, or batched eager). User requests never record a batched graph, so a verdict won by graph replay admits its size only while the load holds that batch-size graph. After a restart, a LoRA reset or an OOM drop, the size is admitted only if the eager arm passed the 1.05x bound on its own. Seeded joins are then off, because the neighbour check ran on the graphed arm. **Policy (`diffusion.py`)** - `request_batching` keeps per-call dynamic NVFP4 serial and serves families without a batched forward serially. Resident and CUDA-graph loads stay serial unless a race promoted a size on this load (new mode `measured`). In that mode only the winning sizes and shapes are admitted. - `coalesce_batch_sizes` drops measured losers and adds measured winners at that shape. A request that cannot be part of any admitted size at its shape no longer waits to coalesce. - Seeded requests may join only where the measured path is neighbour-exact and replays bit for bit from the seed (`coalesce_seeded_ok`), at every batch size the request could render at. A streamed load that still admits unmeasured sizes keeps seeded requests alone. The env switch still opts every seeded request in. - The eager arm runs under a `forced_eager()` scope that the per-chunk graph re-arm in `generate()` cannot undo. - A verdict won by graph replay records the prompt layout it was raced at (the batch key's T5 bucket or chunk count) and holds only for requests in that layout. Any other layout gets the eager arm's verdict. - An out-of-memory error at one batch size is persisted as a loss with its reason, that size's graphs are dropped and the cache emptied, and the race goes on to the smaller sizes. - When the eager arm wins a size, the race drops that size's recorded graphs, so dispatch runs the arm that was measured. On a static compile, the race only tries batch sizes that are already compiled, whatever the policy mode, so resident and graphed loads are covered too. **Row coupling outside the denoiser** - 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 whether another's blocks run. - An explicit FBCache load now serves serially. - An AUTO cache admits no batch size at a step count where it would engage FBCache. - The race refuses such a load. - 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. **Out-of-memory retry (`image_request_batching.py`)** - A batch that ran out of memory was split into halves while its exception was still alive. The traceback pinned the failed call's frames and the tensors they held, so the halves started with that memory still allocated. - The tracebacks are now dropped before the halves run. **Re-coalescing (`image_request_batching.py`)** - When only some sizes are admitted, a fired batch takes the longest admitted prefix. The members it leaves out used to render one at a time. - They are now told as the batch fires and coalesce again behind it, at most 3 rounds. **CUDA graphs per batch size (`diffusion_cuda_graph.py`)** - A coalesced call runs under `batch_rows(k)`. It may record a graph of its own only at sizes 2 and 4, only during the race (never on a user's request), at most 2 per module, and within the pool budget (`UNSLOTH_DIFFUSION_BATCH_GRAPH_POOL_MB`, else free VRAM minus 1 GiB). The estimate is k times the size-1 graph's own pool growth, measured around its capture, not the whole shared pool. Free VRAM is read on the card the call's operands are on. - Batched graphs are recorded only on resident loads. Under an offload placement a failed recording poisons the whole load, so batched calls there run eager. - A key recorded by a batched call that a size-1 call later replays (true CFG gives a size-1 call 2 rows, the same shape as 2 coalesced requests without CFG) counts as a size-1 graph from then on, so dropping batched graphs never takes it. - A placement change clears the batched and edit labels together with the graphs. - A full cache never evicts for a batched key, and a planned eviction takes a batched graph first. - On a resident load, running out of memory while recording a batched graph drops only the batched graphs and stops batched recording for the load. That call runs the way other unrecorded shapes run beside live graphs, and the size-1 graphs keep replaying, where before any capture failure poisoned the wrapper. - Batch-size graphs record into their own pool, one shared by every batched graph and both DiTs of a dual-DiT family. torch frees a pool's blocks only once no graph uses it, so with a single pool, dropping the batched graphs (a lost race, an OOM) gave nothing back while the size-1 graphs lived. `UNSLOTH_DIFFUSION_BATCH_GRAPH_POOL=shared` keeps one pool, and with it dropping batched graphs returns no VRAM until the size-1 graphs go too. - Batched graphs also have their own budget, so they never take a size-1 prompt-length variant's slot. The race records the largest size first. - Edit scopes are covered by the same rule. The image scope keys on reference shapes, and a full planned cache (Qwen-Image-2.1's step) evicted the least recently replayed graph. With true CFG, three edit reference sizes evicted both text-to-image graphs, so the next plain render recorded again on the user's request. A full planned cache now drops a batched graph first, then an edit's; an edit that would have to drop a text-to-image graph runs ungraphed instead. **Trace (`core/inference/diffusion_batch_trace.py`, new; status `batch_trace`)** - Always on: admitted requests, idle direct dispatches, leads and joins, realized call sizes, why a request rendered alone, and rows per pipe call. - With `UNSLOTH_STUDIO_IMAGE_BATCH_TRACE=1`: denoiser invocations, rows and block executions per call. A pipeline that loops over the rows of one call shows up as invocations growing with the rows. **Unchanged** - One request on an idle engine dispatches before any key, policy or status read. - Dynamic NVFP4 (per-call amax scales) stays serial. LoRA and textual-inversion requests stay private to their account. - The FIFO slot order is unchanged. ## Tests `tests/test_image_batch_infra.py` (new) and the batched-graph tests added to `tests/test_diffusion_cuda_graph.py`. They cover: - the capability defaults and overrides, including the lifted key, route and chunk refusals; - unmeasured loads keeping today's rules; - a measured win lifting the resident and graph rules to the winning sizes, and a measured loss dropping that size; - per-call NVFP4 staying serial whatever was measured; - the seeded-join gate; - the promotion statistics; - verdict persistence (losers included, a new process reading them back, another precision missing); - race idle refusal and abort, neighbour-leak detection, and static-compile sizes; - batched graphs: no recording on a user's request, sizes 2 and 4 only, no eviction of size-1 graphs, OOM dropping only batched graphs on resident loads, none recorded on placed loads, the pool budget priced from the size-1 graph's own growth on the operands' card, relabelling on a size-1 replay, and placement changes clearing the labels; - a graphed verdict admitting its size only while that graph exists, else the eager arm's verdict; - the idle path touching no key, policy, status or timer; - the trace telling a fused call from a looped one. ## GPU evidence Every arm ran in its own fresh process on the same VM, through the real `/api/inference/images/generate` route, with one account per client. The arms were: - `main` at the #19667 merge base; - #19667; - `fair`: #19667 with `UNSLOTH_STUDIO_IMAGE_BATCH_MAX=1`; - this branch; - `ref`: an eager reference (speed mode off); - a repeat of #19667 at the end (A/A). Images are 1024x1024. N is the number of concurrent clients in one synchronized burst, 3 repeats each. **FLUX.2 klein 4B, RTX PRO 6000 (Auto: INT8, compiled, CUDA graphs, resident)** | arm | N=1 img/min | N=4 img/min | N=16 img/min | N=16 p95 s | solo p50 / p95 s | |---|---|---|---|---|---| | main | 183.75 | 184.24 | 183.76 | 5.22 | 0.325 / 0.347 | | #19667 | 183.86 | 184.21 | 184.28 | 5.21 | 0.338 / 0.357 | | #19667 repeat (A/A) | 184.29 | 183.79 | 184.04 | 5.21 | 0.326 / 0.351 | | fair serial | 183.69 | 183.71 | 183.83 | 5.22 | 0.326 / 0.348 | | this branch | 183.39 | 184.38 | 183.66 | 5.22 | 0.327 / 0.349 | - **Single user:** - The 14 solo and seed-list images are byte-identical across main, #19667, fair serial and this branch. - The N=1 throughput difference against #19667 (-0.4%) is within the 1% resolution, and the #19667 A/A spread is 0.2%. - **Race:** batch 2 measured 1.037x (lower bound 1.026) and batch 4 measured 1.055x (lower bound 1.047). Neither was promoted, so Auto keeps serving one request at a time and the N=1/4/16 rows after the race match the rows before it. - **Accuracy:** - Neighbour invariance at batch 2 and 4 is bit-identical, with the target row both first and last. - Identity holds: the minimum margin ratio is 6.1. - The batch-4 rows are not bit-identical to the solo renders. - The paired gate against the eager reference fails at eps 0.01: batched rows are 0.064 LPIPS from the reference, against 0.028 for solo renders. This is the batch-shape difference of the INT8 path, not a cross-row effect, and it already applies to a single request with `batch_size` 4. **HiDream-I1-Fast, A100 40GB (Auto: INT8, group offload, CUDA graphs requested; their capture falls back to eager on #19667 too)** - #19667 serves this load serially because of the CUDA-graph rule: N=4 bursts ran at 7.51 img/min on #19667 and 7.45 on this branch before the race. - The race promoted batch 4: speedup 1.55x median, lower bound 1.42x, p95 24.3 s against 37.5 s. Batch 2 was not promoted (median 1.09x, lower bound 0.99 over 3 repeats). Status then reports `measured`. - Byte identity and neighbour exactness cannot be judged on this model on either branch: its scheduler draws step noise from the global RNG, so solo renders of the same seed differ. HiDream N=16 in one process, before the race (#19667 rules, serial) and after it (batch 4 promoted, lower bound 1.40x), before the re-coalescing change: | phase | N=16 img/min | p50 s | p95 s | calls | |---|---|---|---|---| | before race | 6.38 / 6.49 | 75.5 / 73.3 | 150.4 / 148.0 | 16 x 1 | | after race | 7.36 / 7.06 | 64.9 / 70.5 | 130.4 / 136.0 | 2 x 4 + 8 x 1, or 1 x 4 + 12 x 1 | | staggered 16, before / after | 6.49 / 7.38 | 69.6 / 59.6 | 140.4 / 123.6 | | In that run, the members a batch of 4 left out rendered alone. The re-coalescing change addresses this. The same model and card with re-coalescing (the race promoted both 2 and 4, with lower bounds of 1.06x and 1.40x): | phase | N=16 img/min | p50 s | p95 s | calls | |---|---|---|---|---| | before race | 6.38 / 6.46 | 75.6 / 73.5 | 150.5 / 148.5 | 16 x 1 | | after race | 7.98 / 8.00 | 65.3 / 83.6 | 120.2 / 120.0 | 3 x 4 + 4 x 1, both repeats | | staggered 16, before / after | 6.57 / 7.37 | 67.6 / 59.6 | 138.6 / 122.7 | 2 x 4 + 8 x 1 | - Throughput rose 24% and p95 fell 19%. - p50 improved in one repeat and got worse in the other (73.5 to 83.6 s), so a p50 non-regression at N=16 is not shown by 2 repeats. **Batch-size graphs on a real card (Tesla T4)** - `tests/test_diffusion_cuda_graph_batch_gpu.py` records a size-1 and a size-2 graph in the one shared pool. - After the warm-ups, both replay with no host sync under `torch.cuda.set_sync_debug_mode("error")` and match the eager step. **Graph pool probe (L4, synthetic 6-block MLP DiT, 4608 tokens x 3072, fp16)** Each row captures size 1, then sizes 2 and 4. It then drops the batched graphs and calls `release_cached_outside_capture()`. | pool, capture order | reserved with sizes 1/2/4 (MiB) | after drop and release (MiB) | freed (MiB) | eager batch-4 peak after (MiB) | |---|---|---|---|---| | one pool, ascending | 3000 | 2622 | 378 | 4190 | | one pool, descending | 2676 | 2190 | 486 | 3758 | | batched pool, ascending | 3270 | 1326 | 1944 | 2894 | | batched pool, descending | 3216 | 1326 | 1890 | 2894 | - The batched pool frees 1.4 to 1.6 GB more and returns the card to its size-1 level. - Its steady cost is 270 MiB more in ascending order and 540 MiB more in descending order. - Largest-first order saves 324 MiB in one pool and 54 MiB in the batched pool. - With one pool, every lost race leaves its batched graphs' memory stuck for the life of the load, which is why the batched pool is the default. - The trade-off: losing the race is the common case, and there the batched pool gives the 1.4 to 1.6 GB back. Only loads that won pay its 270 to 540 MiB steady cost. `UNSLOTH_DIFFUSION_BATCH_GRAPH_POOL=shared` keeps one pool for anyone who prefers the lower steady cost. - Caveat: these numbers come from a synthetic MLP DiT on L4, not a real model. A real DiT's activation layout may move both the freed and the steady figures. **What the trace shows** - The idle path dispatches directly on every first request of a burst. - Denoiser invocations per pipe call equal the step count for 1, 2 and 4 rows: the call is fused, not looped. - On HiDream, block executions per call stay at 768 for any row count, so the streamed weights upload once per step for the whole batch. ## Not shown - **L4 graph-replay control:** not run. Colab had no L4 slot on any account for about 2 hours, so the guard that batching must not lose to graph replay on L4 is unproven. The L4 pool probe above used a synthetic model. - **HiDream N=16 p50:** mixed. One repeat improved (75.6 to 65.3 s) and the other got worse (73.5 to 83.6 s), so a p50 non-regression is not shown. Throughput and p95 improved in both repeats. - **G2c:** the FLUX.2 klein paired gate against the eager reference fails at eps 0.01. This is the batch-shape difference of the INT8 path; Auto did not promote batching there. - **HiDream:** G1 bytes and neighbour exactness cannot be judged, because its scheduler draws step noise from the global RNG on both branches. - **Out-of-memory recovery:** dropping only the batched graphs after an OOM is covered by CPU tests only. No GPU OOM was provoked. - **Dynamic NVFP4:** stays serial. There are no per-row scales in this change. - **Multi-card:** the verdict key now includes the card topology: card count, component split, CFG replica and layer split. A per-card replica arm (one replica per card, N >= 2 only, host RAM priced per replica) is not built; Kaggle 2xT4 evidence for it is in a separate report. ## Quality gate on promotion (0d7d96d) A measured race win now serves only with a stored passing G2c verdict for the same (family, card model, execution path): PASS, at least 24 pairs, 95% CI upper bound of the paired LPIPS difference at most +0.01. A missing, failing or under-powered verdict keeps today's serial rule; the speed verdict is still saved and the race report says per size whether the win serves and why not. The shipped verdict table starts empty, so every race-promoted family (including HiDream on A100) stays serial until a G2c verdict is measured and added. Motivation: FLUX.2 klein on an RTX PRO 6000 won the speed race at size 2 (1.141x lower bound) but failed G2c (+0.0136 at n=8). Test: `test_image_batch_quality.py` (a speed-winning race with no G2c pass stays serial).
Summary
Studio runs one image render at a time per process, and concurrent users of different accounts were never merged into one batch. With 16 users sending the same settings, throughput was the time of one render per request. This PR lets concurrent image requests share a batched pipeline call without changing what a single user sees.
The first four commits add the feature, smallest first:
current_account_id()by default. It still holds the model load, the LoRA set and weights, size, steps, guidance, negative prompt and every othergenerate()argument, so only requests whose renders would match share a call. Each member gets only its own images through its own future.UNSLOTH_STUDIO_IMAGE_BATCH_MAXnow defaults to 8; the engine's OOM halving still splits a chunk that does not fit./images/generateplain text-to-image goes through the same coalescer. No init image, mask, reference images, ControlNet, Detailer, hires, upscale, variation seed, X/Y grid, prompt or seed lists, or prompt upsampling. Queued jobs, X/Y cells and the chat image tool keep their own path. FLUX.3, Anima and layered models stay batch-1.UNSLOTH_STUDIO_IMAGE_BATCH_SEEDED=1a seeded request joins a waiting batch and keeps the per-image seeds a lone request would use (seed,seed + 1, ...) via per-memberseeds=. Off by default because batched pixels differ from a solo render (numbers below)._generation_slotused to poll the lock every 0.1 s, so whichever waiter woke first won. Each generation now takes a ticket on arrival and only the oldest waiter competes for the lock. Cancel semantics and the image queue drain are unchanged.The remaining commits harden it:
cancel_generate. The Stop route reaches a member's batched images before its foreign-generation early return, so under managed accounts a member riding another account's call getscancelled: trueand its images are not saved. A Stop during a model change sets only the caller's queued requests.coalesced_batch_sizeandcoalesced_index. A coalesced call is always pinned to the load its settings were read for (expected_load).Which loads batch
GET /images/statusreportsrequest_batching, with amodeand a reason. They are checked in this order:serial, per-tensor dynamic activation scales. A denoiser layer takes its activation global scale from the whole call's amax: torchao NVFP4 with its dynamic per-tensor scale (opt-in NVFP4), or a dynamic NVFP4 linear that computes its scale on every call. In a shared call, one request's prompt would set every other member's activation quantization. The reason names the layer. Studio's own NVFP4 linear freezes its scale, and FP8 / INT8 scale per row, so neither triggers this.serial, resident weights. The load keeps the denoiser on the card: no offload, or group offload with every group pinned.serial, CUDA graphs. The load streams the denoiser from host but replays CUDA graphs.compiled_sizes. The load streams, and a static compile shares a call only at batch sizes this load already compiled.any. The load streams with no graphs and no static compile, so concurrent requests with the same settings share one call.Streaming means model, sequential or streaming offload, or group offload with any group left unpinned. The placement is read from the live offload hooks when the batch fires. A
serialload never opens a batch, so its requests wait only for the slot, as before this PR. The rule is the same on every device.Why resident loads are serial. One call of 4 against 4 solo renders, Studio Auto, 1024x1024, direct pipeline calls:
The speedups are indicative: one process per family, 2 interleaved repeats. Cards were A100-40GB, plus RTX PRO 6000 for Qwen-Image, HunyuanImage-2.1, Chroma and MOSS-Image. Resident loads never gained more than 1.19x, and every batched member drifted from its own solo render.
Why streamed loads with CUDA graphs stay serial. FLUX.2-dev (
unsloth/FLUX.2-dev) on one Colab L4, Studio Auto: INT8 transformer streamed in 57 offload groups, INT8 encoder, compiled, 20 steps, 1024x1024. Each arm ran 4 requests from 4 accounts, sent while another render held the slot, with 2 interleaved repeats:Apple Silicon (macOS 15 runner, MPS, torch 2.14.1, bf16; correctness only, tiny SDXL pipeline at 256 px), measured before the placement rule: two requests from two accounts ran as one call of 2 images, and each member matched its solo render bit for bit (max abs diff 0, LPIPS 0.0). That tiny pipeline is resident, so at this head it reports
serialand renders the two requests one at a time. Torch 2.15 no longer sees the runner's paravirtual GPU, so this job pins torch below 2.15.Batch keys, Qwen-Image-2.1 and per-family grouping
Batch keys read private tokenizer copies
The race.
coalesce_prompt_keytokenizes each arriving prompt to build its batch key:This always happens on a worker thread while another request renders, because that is the only time requests coalesce. A fast tokenizer used from two threads at once raises
RuntimeError: Already borrowedin whichever call loses.The fix.
Qwen-Image-2.1 no longer joins cross-account batches
A100-40GB, Studio Auto (INT8, compiled), 1024x1024, 25 steps. Two prompt lengths (41 and 31 tokens), four images, three interleaved repeats:
Per-family grouping, with interleaved arrivals
New
studio/backend/tests/test_image_batching_followups.pycovers these through the route:serialand gets no batch plan. Frozen NVFP4 scales and plain linears still batch.Testing
The grouping tests fail on
a40d6780d3, before members were grouped by what their family encodes.The tokenizer tests and the Qwen-Image-2.1 exclusion tests fail on
43ed7c33cf.The resident-placement tests fail before the placement rule: a resident fake load never batches and never waits, and group offload with every group pinned reports serial. A streamed fake load still batches across accounts.
Changed tests, now on a streamed placement:
At the head,
test_openai_images_load_swap.py,test_image_batching_followups.py,test_image_concurrency.py,test_image_concurrency_review.py,test_openai_images_batching.py,test_diffusion_qwenimage21.pyandtest_openai_images_generations_route.py: 175 passed, 1 skipped.Race check with the real Qwen-Image-2.1 tokenizer. One thread runs a padded encode the way a render does; the other reads the batch key for 5 s:
A100, real coalescer, CUDA graphs off. Four accounts posted A B A B while another render held the slot:
Already borrowed.Not covered
The per-family speedup table comes from direct batched calls. The coalescer itself was run on a streamed load only for FLUX.2-dev on L4 (above).
Among the measured families, Ideogram-4 is the only one whose Auto load streams with no CUDA graphs, so in Auto it is the only one that coalesces. Its coalescer gain was not measured, and neither were AMD, Intel XPU or MPS streamed loads.
Qwen-Image-2.1 was measured only on A100 INT8. FP8 / NVFP4 and offloaded placements may batch differently.
With textual-inversion embeddings, tokens an embedding adds after the first render of a load are not in the copy. Those requests already batch only within their own account.
Single-user latency
A batch forms only while a render is already running. An idle engine with no batch collecting renders the request at once, with no extra status read and the same
generate()call as before.Account isolation
Tests
CPU tests are in
studio/backend/tests/test_image_concurrency.py(feature) andtest_image_concurrency_review.py(hardening). They cover:/images/generatecoalescing and its exclusions, and the opt-in seeded join;All of these fail on the commit before their fix. A few guards pass on both sides on purpose: different settings never share a call, the leader's Stop ends only its own account, and a cancelled waiter leaves the queue.
Related suites (diffusion routes, backend, slot release, hires, Detailer, segment, X/Y, image queue, account media generation, OpenAI images, embeddings, LoRA, gallery) show only the 6 failures that already exist on the merge base (
test_diffusion_backend.py: FLUX.2 shape guard, MiniMax-H3-Image download plan).A CPU illustration of why new batch sizes matter on a static compile: a 3-layer conv net under
torch.compile(dynamic=False)takes 2.8 s for its first batch size and about 0.85 s for each new one (2, 3, 4). Cached sizes add nothing. A real UNet or DiT takes far longer per new size.GPU correctness check (B200, sm100, before the hardening commits)
This checks correctness only, not throughput. It drives the real
DiffusionBackendand the real FastAPI routes in process, usingunsloth/stable-diffusion-xl-base-1.0(bf16, 512x512, 8 steps, guidance 5). A 1024x1024, 50-step render holds the slot while 8 clients from 8 accounts send their requests.prompts=None,batch_size=1/images/generate/v1/images/generationsBatched vs solo pixels: for each member I rendered the same prompt and seed alone and compared. A repeated solo render is bitwise identical, so every difference below comes from batching.
Not in this PR
DiffusionBackendper GPU plus a least-loaded dispatcher.