Skip to content

Studio: queue /v1/videos while a video renders and batch waiting /v1/images/generations requests - #15613

Merged
danielhanchen merged 27 commits into
unslothai:mainfrom
oobabooga:studio/media-api-queue-batching
Oct 28, 2026
Merged

danielhanchen merged 27 commits into
unslothai:mainfrom
oobabooga:studio/media-api-queue-batching

Conversation

@oobabooga

@oobabooga oobabooga commented Oct 27, 2026 •

Copy link
Copy Markdown
Member

Follow-up to #14645 and #15344, which made the OpenAI fine-tuning API queue jobs while the GPU is busy and train compatible queued jobs together. This brings the same two behaviours to the image and video generation APIs.

A second POST /v1/videos while a clip rendered was refused with a 409. OpenAI's API accepts it and reports the job as queued, and clients written against it poll until it runs. Image requests that arrived while another image rendered each waited and then rendered one after another, even when they differed only in prompt and seed, although the diffusers engine can already render a list of prompts and seeds in one call.

Videos: POST /v1/videos queues instead of refusing

Videos get a queue rather than batching: a clip's activations already dominate the memory plan, so two clips in one forward would be refused on most hardware.

  • A busy create is accepted. While a video renders, or others are waiting, the create returns status: "queued" with the video_... id the clip keeps. Jobs start first in, first out, each as the account that created it and only while that account is still enabled, through the same path as an immediate create, so auto-switch, managed-account checks and every refusal still apply. The seed and created_at are kept, and size, seconds and model read as an immediate start would report them. A managed account that may not use the loaded model gets the same 403 as on an immediate start.
  • Retrieve, list, content and delete see queued jobs, for their own account only. Deleting a queued job means it never runs. A delete that lands while a queued job is starting waits for the start and then deletes the job, or returns a 409 to retry; it never reports a deletion that did not happen.
  • A refused start fails the job with the reason (for example, no video model loaded any more), and the queue moves on. Refusals that clear by waiting (the engine is busy, a model switch is in progress, another account holds the GPU) keep it queued.
  • Bad input is still a 400 at once, before anything is queued.
  • Limits: 32 waiting videos per account and 64 in total; past that, the create returns a 429.

Queue hardening

  • A queued start goes through the same media admission count as an HTTP request (media_keepwarm.begin_request / end_request), so an idle unload or auto-switch never cancels an accepted clip.
  • The queue counts an in-flight model load as busy, so a job polled during a model replacement keeps waiting instead of failing with "No video model loaded".
  • The family-specific shape, fps and conditioning checks (_refuse_family_inputs, shared with the immediate start) run before a job is queued: an invalid num_frames or size gets the same 400 while busy as when idle.
  • A queued job reports the model that will render it (the resident one unless a switch will load another), matching an immediate start.
  • A queued start holds an inference slot as an HTTP create does, so a model switch for a queued video never treats a running chat as idle and evicts its model.
  • A queued image-to-video job with no size reports the canvas the backend will resolve from its reference image, not the first resolution preset.
  • A queued video rechecks its account right before it reserves the generation, so an account disabled during the admission or model-switch waits never renders.
  • Stopping a queued video by id while its start is in flight waits for the start, then stops it, instead of answering 409 and letting it render.
  • A Stop the engine acknowledged while a batched image call failed cancels every request in the batch, so none renders again on its own.
  • A queued start rechecks its account at the reservation itself, after keyframes and references are prepared, so a disable during that preparation never renders.
  • A queued job naming another downloaded video model reports that model's default size and duration, snapped to its own frame lattice, instead of auto.
  • An explicit size no longer skips the keyframe checks: a reference over 4096 px per side gets the same 400 while queued as when idle.
  • A model load that starts while a queued start waits for admission keeps the job queued instead of failing it with "No video model loaded"; it starts once the load finishes.

Images: waiting /v1/images/generations requests render as one batch

  • What batches: requests without an explicit seed that arrive while an image renders and match on everything but prompt and n (same account, model, size, steps, guidance and negative prompt). Once the generation they arrived behind ends, they render as one diffusers call, and each request gets back its own images. A request that finds the engine idle renders at once, as before, so nothing waits for more requests. A request with an explicit seed always renders alone, so the same seed keeps giving the same pixels whatever else is waiting.
  • No starvation: a batch waits only for the generation it found on arrival. If another generation (a Studio UI render, or a /v1 request too large to batch) takes the slot next, the batch queues for the slot like any other request instead of waiting for the engine to go idle.
  • Seeds and gallery records match a lone request: each batched request draws its seed once and takes seed, seed + 1, ..., each image with its own generator and its own recipe. The starting noise is the same, but pixels are not bit-identical to a lone render on GPU: batch-size-dependent kernel numerics move them slightly (measured in diffusion_batched.py: mean abs pixel delta about 2.5/255, LPIPS delta under 0.002). That is why seeded requests never batch. A tiny FLUX pipeline in fp32 on CPU gives identical 8-bit pixels batched and alone.
  • Failure falls back: if the shared call fails (out of memory, the model replaced), every request renders alone and sees the outcome it would have had without batching. A cancel ends every request in the batch instead, including a Stop while the batch waits on a model change, and a Stop recorded while a failed batch unwinds is final rather than a reason to render alone.
  • Cap: 4 images per batched call by default, set with UNSLOTH_STUDIO_IMAGE_BATCH_MAX (1 turns batching off). A single request can already ask for 10 in one forward with n.

Behavior boundaries

  • Only /v1 changes. The Studio UI routes (/api/video/generate, /api/inference/images/generate) are unchanged, and a video started from the Video page still starts at once when the engine is free.
  • The chat generate_video tool still starts at once or gets the busy 409, which it reports to the model.
  • Images batch on diffusers only. sd.cpp and MLX take no prompt or seed lists, and FLUX.3 renders one image per call anyway.
  • Queued videos live in this process, like queued fine-tuning jobs: a restart drops the ones that have not started.
  • MCP's video queue only kicked in on the busy 409, so MCP clients now receive the server's queued job directly. The MCP code is unchanged.
  • Unsloth Studio / Desktop: queue image generations from the Images page and the API #15005 (draft) adds a separate queue for the Images page; this PR does not touch that page or route.

Validation

  • New tests: test_openai_videos_queue.py (18) and test_openai_images_batching.py (16), driving the real routes over the real VideoBackend job machinery and a fake diffusers engine. On main, all 18 video tests and 9 image tests fail; the 6 that pass check behaviour this PR keeps (an idle engine, sd.cpp and MLX) or the batching module directly. Besides the behaviour above, they cover deletes and concurrent creates racing the queue, a disabled account, a managed account without access to the loaded model, and a cancel or Stop reaching a batch.
  • Suites: the 356 studio/backend test files that import the video or inference routes pass with 8 workers, apart from host CUDA error: device(s) busy or unavailable failures and test_preview_chat_waits_for_a_slow_checkpoint_load, which pass when run alone. The later commits were checked with the video, image, chat-tool and diffusion backend tests (1,077 passed).
  • OpenAI spec: the queued create, retrieve, list, delete, the 429 and a failed queued job validate against the spec's schemas (links below). The one mismatch is size, where Studio reports the loaded model's own size instead of the four Sora sizes, as the immediate-start path already does.
  • Checks: the repository formatter (ruff-unsloth 0.6.9.post1), ruff check at the CI pin and the duplicate-definition lint are clean.

Not tested

  • No live run with a loaded image or video model, so the batching speedup and memory use on real hardware are not measured.
  • Two managed accounts rendering at the same time, beyond the account-isolation test.
  • Windows and macOS.

Specs

Validated against the official OpenAPI spec. It is raw and machine-readable, so it is easy to grep or hand to an AI agent for review:

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 27, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ⚠️ Failed 2026-10-28T05:26:53.805296Z
We couldn’t complete this review. Comment @codex review to try again.
1106f3c Manual request
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@oobabooga

Copy link
Copy Markdown
Member Author

Reached Codex review convergence at oobabooga#425 (Codex found no major issues on a610c84).

@NilayYadav NilayYadav self-assigned this Oct 27, 2026

@NilayYadav NilayYadav left a comment •

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

​

@NilayYadav

Copy link
Copy Markdown
Collaborator

Review + reproduction evidence

Pinned review: db39d491c31bc236de7e8cb805674549291c04f7. 2 findings: 1 fixed in f470a0d, 1 suggested inline.

I reproduced a second video create and a burst of image requests through the /v1 API on the merge base c4f9de9 (Linux, NVIDIA L4, Wan2.1-T2V-1.3B and sdxl-turbo):

  • Before: the second POST /v1/videos while a clip rendered returned 409 {"error":{"message":"A video generation is already in progress.","type":"conflict_error"}}. Two waiting image requests rendered as two calls (images=1 seeds=[11], then images=1 seeds=[22]).

  • PR head: the second create returned 200 status: "queued" with seed 202, then went queued, in_progress, completed after the first clip (seed 101). A queued clip cancelled by id returned {"cancelled": true} and a queued clip deleted returned {"deleted": true}; neither ever rendered. The two image requests rendered as one call (openai_images.batch: 2 requests render as one call of 2 images, images=2 seeds=[22, 11]), each response with its own image and gallery seed.

  • The Studio Video and Images page routes behave the same on both sides.

  • Two batched sdxl-turbo 1024px images took 8.21 to 8.37 s versus 7.86 to 8.11 s alone, and the first batch of size 2 paid an extra compile of about 113 s.

  • 164 backend tests pass on head; the 18 video queue tests fail on the merge base, and the new cancel test fails with its fix reverted.

Conclusion: the video queue is real and works, including cancel and delete of queued clips after the fix. Image batching works correctly but showed no speedup here, so I would ship it off by default until it does. CI on the head still has to finish.

@danielhanchen danielhanchen self-assigned this Oct 28, 2026
@danielhanchen

Copy link
Copy Markdown
Member

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Something went wrong. Try again later by commenting “@codex review”.

An unknown error occurred
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

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".

@danielhanchen

Copy link
Copy Markdown
Member

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Something went wrong. Try again later by commenting “@codex review”.

An unknown error occurred
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

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".

… queued jobs like an immediate start

- A queued start now enters media_keepwarm.begin_request(VIDEO) / end_request,
  so an idle unload or auto-switch holding the admission gate sees it and
  cannot cancel an accepted clip.
- The drainer treats an in-flight model load (loading_repo_ids) as busy, so a
  job polled mid-replacement keeps waiting instead of failing with
  "No video model loaded".
- The family-specific shape, fps and conditioning checks are factored into
  _refuse_family_inputs and run before a busy create is queued, against the
  resident family or the resolved switch target, so an invalid clip gets the
  same 400 it would get when idle.
- A queued job reports the resident model whenever the resident will render
  it (for example a named model with auto-switch off), not the requested name.
@danielhanchen

Copy link
Copy Markdown
Member

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Something went wrong. Try again later by commenting “@codex review”.

An unknown error occurred
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

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".

…ued image-to-video canvas from its reference
@danielhanchen

Copy link
Copy Markdown
Member

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Something went wrong. Try again later by commenting “@codex review”.

An unknown error occurred
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

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".

…erves, keep an engine Stop on a failed image batch final

- A queued /v1/videos start rechecks its account in the same call that reserves the generation, so an account disabled during the admission or auto-switch waits never renders.
- A Stop by id on a queued video whose start is in flight waits for the start to settle, then stops what it left, instead of answering 409 and letting it render.
- A Stop acknowledged by the engine while a shared /v1/images call fails is reported as cancelled to every request in the batch, so none renders again alone.
…nresident target's size and seconds

- A queued /v1/videos start checks its account again inside begin_generate, after the keyframes and references are prepared and right before the job is reserved, so a disable during that preparation never renders.
- A queued job naming another downloaded model reports that model family's default size and duration, on its own frame lattice, instead of auto.
danielhanchen added a commit that referenced this pull request Oct 28, 2026
#15745)

## Summary

`Repo tests (CPU, rest)` fails on main with three guard failures. It
shows on every staging CI run of recent PRs (#15613, #15615, #15673 and
others), whatever the PR changes:

```
tests/test_rendezvous_port_everywhere.py::test_distributed_tests_take_their_port_from_the_shared_helper
    tests/test_gc_skip_auto_dist_cells.py: _free_port does not use tests._rendezvous_port
    tests/test_gc_skip_auto_dist_gloo.py: _free_port does not use tests._rendezvous_port
tests/test_source_read_encoding.py::test_checked_in_file_reads_name_an_encoding[5]
    tests/test_mamba_fused_lora_adapters.py:464: read_text()
tests/test_source_read_encoding.py::test_checked_in_file_reads_name_an_encoding[13]
    tests/test_refresh_moved_layer_devices.py:81: read_text()
```

These tests landed around the same time as the guards that now catch
them:
- 570b9b8 added the two `gc_skip_auto_dist` gloo tests with their own
`bind(("127.0.0.1", 0))` port picker. That is the ephemeral-range race
that #15679 moved every distributed test off, which produces
`EADDRINUSE`.
- 986558e and 7f3c5a1 read checked-in source with the platform
default encoding, which breaks on Windows once the file gains a
non-ASCII byte.

The guards are right in all three cases, so the tests change, not the
guards.

## Change

- `tests/test_gc_skip_auto_dist_cells.py`,
`tests/test_gc_skip_auto_dist_gloo.py`: `_free_port()` delegates to
`tests._rendezvous_port.free_port()`, the same three lines every other
distributed test uses. The now-unused `import socket` is dropped.
- `tests/test_mamba_fused_lora_adapters.py:464`,
`tests/test_refresh_moved_layer_devices.py:81`: `read_text(encoding =
"utf-8")`.

## Testing

- `tests/test_source_read_encoding.py` +
`tests/test_rendezvous_port_everywhere.py`: 3 failed on main, 22 passed
with this change.
- The four touched test files under `-n 4`: 43 passed, 4 skipped.
@danielhanchen
danielhanchen merged commit 85744ff into unslothai:main Oct 28, 2026
11 of 55 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants