Skip to content

Unsloth Studio / Desktop: queue image generations from the Images page and the API - #15005

Merged
danielhanchen merged 28 commits into
unslothai:mainfrom
LeoBorcherding:studio/images-queue
Nov 8, 2026
Merged

danielhanchen merged 28 commits into
unslothai:mainfrom
LeoBorcherding:studio/images-queue

Conversation

@LeoBorcherding

@LeoBorcherding LeoBorcherding commented Oct 23, 2026 •

Copy link
Copy Markdown
Collaborator

Part of #10695.

Clicking Queue while an image renders lines the next one up instead of waiting. It works from the Images page and over the API: each job is a full generate request, runs through the same path as POST /images/generate, one at a time, and its images land in the gallery.

Changes in this PR

  • Backend: core/inference/image_queue.py, one worker, per-account jobs (100 queued, 20 finished kept). Routes under /api/inference: POST /images/queue (409 when nothing is loaded), GET /images/queue, POST /images/queue/{id}/cancel, POST /images/queue/{id}/move {"index": n}, DELETE /images/queue.
  • A job runs only on the model that was loaded when it was queued; if another model is loaded by then, that job fails with a clear message and the queue moves on. No auto-reload in v1.
  • Images page: Queue sits next to Stop while a render runs, and a compact panel lists waiting jobs (prompt, size, steps, seed) with up, down and remove. Stop cancels only the running job. Jobs queued over the API show up on the page, and the queue survives a page reload (not a server restart).
  • Generate's request body is built by one requestFor(i) helper, so Queue sends exactly what Generate would.

Test matrix

where what ran result
Colab L4 (NVIDIA L4, 23 GB), Linux, 7014602 Z-Image-Turbo Q4_K_M, 1024px, 8 steps. UI: 3 prompts queued during a render, one moved up, one removed ran in the new order, removed job never ran, drained in 34 s
same, main b6fc821 busy footer only Stop, no way to line anything up
7014602, unit tests frontend queue tests (3 files), typecheck, backend test_image_queue*.py 62/62, clean, 15/15
Colab L4 (NVIDIA L4, 22.5 GB), Linux, 2a55305 Z-Image-Turbo Q4_K_M GGUF. UI: 3 prompts queued during a render, one moved up twice, one removed ran in the new order, removed one never ran, drained in 38 s
same API: 4 enqueues, move to index 0, cancel queued, cancel running, provider_id, unknown id, DELETE 200 x4, reordered, cancelled, running job ended cancelled, 400, 404, emptied
Apple M5 Mac, 2a55305 backend pytest (15 new), frontend npm test 15/15; 13741 pass, 0 fail

Merged with main at b6fc821.

Screenshots
Main while rendering: only Stop, no way to line up another prompt.

Branch: "Queue · 3 waiting", one running, up / down / remove on each job, Stop and Queue in the footer.

After moving one up and removing one: 2 waiting.

Queue drained in 34 s, results in the gallery strip, removed job absent.

Not tested

  • Unsloth Desktop, Windows, AMD, MPS: not run.
  • Server restart: clears the queue by design.
  • Compare grid and saved connections still generate directly; they can't be queued.

Before / after on a real render (Kaggle T4, Z-Image-Turbo Q4_K_M, 50-step render; merge base 91935a1 vs head 9868e21; two isolated Studio installs)

Mid-render footer: the base offers only Stop; the head offers Stop and Queue.

Three more prompts queued from the form during that render: the head lists them in order with up, down and remove; the base has nowhere to put them (GET /images/queue is 404 there). On the head the queue then ran them in order: the first finished with one image while the next was rendering.

A server-side queue of full generate requests that run one at a time through
the same path as POST /images/generate. New routes: POST/GET/DELETE
/images/queue, POST /images/queue/{id}/cancel and /images/queue/{id}/move.
While a render runs the Images page offers Queue beside Stop, and a compact
panel lists the waiting jobs with reorder and cancel.
@danielhanchen

Copy link
Copy Markdown
Member

Three of the red checks here are specific to this PR's new image queue routes:

  • (Python 3.13, rest): tests/multi_account/test_alice_bob_matrix.py::test_object_route_factory_completeness flags routes.inference:POST:/images/queue/{job_id}/cancel and .../move. The two new per-job routes need entries in the multi-account object-route matrix, so cross-account access to a job id is covered.
  • Chat UI Tests (extra): /api/inference/images/queue is polled about 4x per dwell (~19/min) but is not in the log budget. Adding it to IDLE_POLLS (or BUSY_POLLS if it only polls while a job runs) in studio/backend/tests/log_budget/session.py clears it.
  • Frontend build + bundle sanity: please check this after the two above.

connection (openclaw, stable) is not this PR. openclaw@latest raised its Node floor above the runner's cached Node 24, and #15013 fixes that for every PR.

danielhanchen added a commit that referenced this pull request Oct 23, 2026
…15015)

`studio/backend/tests/test_diffusion_offload_step_graphs.py::test_releasing_an_offloaded_step_graph_frees_its_capture_stream_workspace`
fails in Backend CI `(Python 3.13, a-k)`, for example on #15005, with
`assert [] == [1, 2]`. It fails on a clean `main` every time when run on
its own.

## Cause

#14777 routed `GraphedForward._release` through
`release_cached_outside_capture`. That flush runs `synchronize`, the
cuBLAS workspace clear and `empty_cache` only when
`torch.cuda.is_available()`. The test patched
`_cuda_clearCublasWorkspaces` and `empty_cache` but not the availability
probe. On a CPU runner it therefore passed only when an earlier test on
the same xdist worker had installed the CUDA spoof, and otherwise
recorded no calls.

The product is right: there is nothing to flush without CUDA. The test
was depending on ambient state.

## Fix

The test now also patches `torch.cuda.is_available` (True) and
`torch.cuda.synchronize` (no-op). Its assertion is unchanged: the cuBLAS
clear and then `empty_cache` run only when the handle owned a
capture-stream placement.

## Verification

- The file: 15 passed, 15 skipped. Before, it was 1 failed in isolation
on every commit back to ae3dc79.
- Sabotage check: making `_release` pass `clear_cublas = False` fails
the test.
danielhanchen added a commit that referenced this pull request Oct 23, 2026
…5013)

`connection (openclaw, stable)` in Local agent guides CI fails on every
PR that runs it (for example #15002 and #15005):

```
[install] npm install -g openclaw@latest attempt 3 failed
[install] curl|bash https://openclaw.ai/install.sh attempt 3 failed
[agent install failed] agent=openclaw: openclaw install failed (npm + curl)
```

## Cause

`[email protected]`, published 2026-10-22, raised its engines floor:
- before: `node >=24.16.0 <25 || >=26.1.0` (2026.10.5)
- now: `node >=24.22.1 <25 || >=26.12.1`

The openclaw legs run `actions/setup-node` with `node-version: '24'`,
which takes the runner's cached Node. That is `v24.21.0` on the current
ubuntu-latest image, so npm refuses the install and the curl installer
fails the same way. Node 24.22.1 was released on 2026-10-20 and is in
setup-node's manifest; the runner image has not picked it up yet.

Nothing in the repo changed. The upstream package moved, so the workflow
is what needs fixing.

## Fix

- Both setup-node steps that run openclaw now pass `check-latest: ${{
matrix.agent == 'openclaw' }}`, so `'24'` resolves to the newest 24.x
release instead of the cached one. The other agents keep the cached Node
22 as before.
- `tests/studio/test_agent_guides_openclaw_node.py` pins this for every
job whose matrix runs openclaw. Removing `check-latest` fails it.

The workflow-wide tests
(`test_studio_smokes_do_not_trigger_on_the_training_library.py` and the
other workflow-parsing suites, 426 tests) still pass. The proof of the
fix itself is this PR's own `connection (openclaw, stable)` leg.
@LeoBorcherding
LeoBorcherding marked this pull request as draft October 23, 2026 22:27
# Conflicts:
#	studio/frontend/src/features/images/images-page.tsx
danielhanchen added a commit to Etherll/unsloth that referenced this pull request Oct 28, 2026
…images/generations requests (unslothai#15613)

Follow-up to unslothai#14645 and unslothai#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.
- **unslothai#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:

- **OpenAI**:
https://raw.githubusercontent.com/openai/openai-openapi/master/openapi.yaml
(repo: https://github.com/openai/openai-openapi). Relevant paths:
`/videos`, `/videos/{video_id}`, `/videos/{video_id}/content`,
`/images/generations`. Relevant schemas: `VideoResource`, `VideoStatus`,
`VideoListResource`, `DeletedVideoResource`, `ErrorResponse`,
`CreateImageRequest`, `ImagesResponse`, and the `InferenceRateLimited`
response for the 429. The file is large, so grep for a path or schema
name rather than reading it whole.

---------

Co-authored-by: Nilay Yadav <[email protected]>
Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Co-authored-by: Daniel Han <[email protected]>
@danielhanchen danielhanchen self-assigned this Nov 7, 2026
…tion ticket

The cancel route called the account-wide image Stop, which reaches whichever render holds the engine. A queued job waiting behind a chat image stopped that image and then ran anyway. Each job now carries a GenerationTicket bound around its render, so cancelling it stops only that job, queued behind another render or running.

[skip ci]
…ap between direct runs

The queue checked the resident model, then the render read it again and followed a swapped-in model. The job's load is now passed to the render as expected_load, and a replacement fails the job instead of retrying on the new model.

A multi-run Generate sends one request after another; a job queued meanwhile could start in the gap between two. The queue now waits until no direct run has ended within the last 1.5 s.
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 7, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ❌ Failed

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

Review Status Commit Review trigger
📝 Code Review ❌ Failed 2026-11-08T16:29:21.509156Z
We couldn’t complete this review. Comment @codex review to try again.
1c279d8 Draft marked ready
ℹ️ 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.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

… warm, stop captioning on Stop

- Disabling or deleting an account cancels its queued jobs and stops its running one; a job also checks the account is live before it renders.
- A queued render counts as media activity, so idle auto-unload does not drop the model under it.
- The FLUX.3 prompt enhancer binds its cancel event to the generation ticket, so a queued job's or chat image's own Stop ends captioning too.
- The page notices an API job that was queued and finished between two polls, and keeps probing until a running queued job starts denoising.
- The render-fence test double takes the new pinned_load argument.

[skip ci]
…hen following another job

- Each multi-run Generate sends an X-Unsloth-Run-Sequence id; holds are kept per sequence and released only by that sequence's next run, Stop or the 60 s lapse, so another client's run never frees them.
- Moving on to a different queued job resets the page's Stop state and run token, so the new job neither shows Stopping nor loses its own Stop behind the previous job's in-flight cancel.

[skip ci]
danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Nov 7, 2026
chatgpt-codex-connector[bot]

This comment was marked as resolved.

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Nov 7, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Nov 7, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Nov 7, 2026
danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Nov 7, 2026
chatgpt-codex-connector[bot]

This comment was marked as resolved.

@danielhanchen

Copy link
Copy Markdown
Member

A CI run of this branch merged onto current main has a failure that comes from this PR. Chat UI Tests (extra) fails at "Every polled path is declared in the log budget (Playwright)":

FAIL these paths are polled by the app but are not in the log budget:
  /api/inference/images/queue   4x within one dwell (~19.2/min)

The new queue poll needs the two entries that message asks for:

  • the path in IDLE_POLLS in studio/backend/tests/log_budget/session.py, or in BUSY_POLLS if it only polls while a generation is queued or running, with the interval its call site uses;
  • a class for it in studio/backend/loggers/handlers.py, so it is not logged at full volume.

If the page only needs the queue while something is queued, stopping the poll once the queue is empty would also keep it out of the idle budget.

On the same run, studiobench CI / Real-path session, every action ran missed 6 action slots against a slack of 2 (keystroke reached its slot 4 s late, delete_message 3.6 s late). That one may just be a slow runner. It is worth a look, though, if the queue poll keeps running on pages that have nothing queued.

…I pins

- GET /images/queue joins the declared idle polls and the quiet 2xx paths; its mutations still log.
- The Stop-state reset is one helper, so the source pin on handleGenerate's finally finds its own block.
- A test file read names utf-8; the Reuse last seed pin follows the guarded update.

[skip ci]
…a recovered run's seed too

- Following a running queued job from an idle page resets the Stop state and run token, like the busy path.
- A run recovered after a lost response updates Reuse last seed only when the records it gained are at least as new as the stored seed's run.

[skip ci]
@danielhanchen

Copy link
Copy Markdown
Member

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member

@codex review

danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Nov 7, 2026

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: dc49108f69

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

Comment on lines +51042 to +51043
_direct_sequences.clear()
_direct_stops += 1

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 Preserve unrelated sequence holds when stopping one run

With two clients on the same account, sequence A can be holding the queue between requests while another client's run B is active. Stopping B clears A's hold too, allowing queued work to start after the 1.5-second settling period and slip into A's batch if its next request is delayed. The shared _direct_stops counter also prevents an unrelated successful run already in flight from rearming its hold. Scope cancellation bookkeeping to the affected sequence rather than clearing process-wide state.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Not changing: it needs two clients on one account, each mid multi-run Generate, with one stopping. All images still render; only the order of a queued job can move. Out of scope for this queue.

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Nov 8, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Nov 8, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Nov 8, 2026
danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Nov 8, 2026
chatgpt-codex-connector[bot]

This comment was marked as resolved.

danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Nov 8, 2026
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Breezy!

Reviewed commit: 319e23d5ac

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

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Nov 8, 2026
danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Nov 8, 2026
@danielhanchen
danielhanchen marked this pull request as ready for review November 8, 2026 16:29
@danielhanchen
danielhanchen merged commit 3c51fdc into unslothai:main Nov 8, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants