Skip to content

Studio: queue OpenAI fine-tuning jobs while the GPU is busy - #14645

Merged
danielhanchen merged 11 commits into
mainfrom
studio-openai-fine-tuning-queue
Oct 27, 2026
Merged

danielhanchen merged 11 commits into
mainfrom
studio-openai-fine-tuning-queue

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

Follow-up to #14496 for #13603.

Until now a second POST /v1/fine_tuning/jobs while another training run held the GPU was refused with a 400 ("Training already active"). OpenAI's API instead accepts the job and reports it as queued, and clients written against it poll until it runs. This makes Studio do the same.

What changes

  • A job created while training (or a diffusion LoRA run) is active, or while other jobs are already waiting, is accepted with status: "queued" and an ftjob_q... id.
  • Jobs start first in, first out once training is idle. Each one starts through the same start_training handler as before, as the account that created it, so every existing guard and refusal still applies.
  • retrieve, list, events (queue position), checkpoints and cancel all accept the queued id, both before and after the job starts. After it starts, the id resolves to the real training run.
  • Cancelling a queued job removes it from the queue; it never starts.
  • A queued job whose start is refused (bad model, resume mismatch, a 409 that keeps happening while the GPU is idle) is marked failed with the reason instead of retrying forever.
  • Queued jobs are visible only to their own account, like runs.

What does not change

  • The Studio UI and /api/train/* are untouched. A training run started from the UI still starts immediately when the GPU is free; the queue only waits for it.
  • With the GPU idle and nothing queued, create starts the job right away, exactly as before.

The queue lives in the server process, so queued (not yet started) jobs do not survive a Studio restart. That is stated in the module docstring.

Tests

  • tests/test_openai_fine_tuning.py: 14 passed (4 new: FIFO start order, cancel before start, refused start fails the job, another account cannot see or cancel a queued job). Module state is now reset per test.
  • tests/multi_account/test_alice_bob_matrix.py -k "openai or fine_tun or training": 144 passed.

@danielhanchen danielhanchen self-assigned this Oct 22, 2026
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 22, 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 ✅ Completed 2026-10-27T12:57:11.135464Z 3bc3dca 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.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@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: 859a119a88

ℹ️ 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 +749 to +753
jobs = [
job
for e, job in pending
if e.status in ("queued", "starting") or job["created_at"] > newest
] + jobs

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 Merge waiting jobs into chronological list order

When a queued job waits through the drainer's polling interval and a newer Studio UI run starts while the GPU is temporarily free, this condition always prepends the older queued job ahead of the newer run. The UI route intentionally bypasses this queue, so this interleaving is possible and violates the endpoint's newest-first ordering; waiting entries need to be merged by created_at rather than unconditionally placed first.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Not changing: this needs a UI run started inside the few seconds between queue polls while API jobs wait; a waiting job listed first is the useful order there.

…queued events, ride out transient 409s

[skip ci]
chatgpt-codex-connector[bot]

This comment was marked as resolved.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

… admission races, queue creates during transient conflicts
chatgpt-codex-connector[bot]

This comment was marked as resolved.

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 22, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 22, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 22, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 22, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 22, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 22, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 22, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 22, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 22, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 22, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 22, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 22, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 22, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 22, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 22, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 22, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 22, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 22, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 22, 2026
@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: 200eea780e

ℹ️ 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 added a commit that referenced this pull request Oct 27, 2026
Follow-up to #13603: the building block for training many users' LoRA
adapters on one shared base model in one batch, instead of one job after
another.

## What this adds
`unsloth/kernels/multi_lora.py`:
- Fused Triton kernels for a linear layer where every token belongs to
its own adapter (or none, id `-1`). The base matmul runs once for the
whole batch; each adapter's update only touches its own tokens.
- Forward and backward. Tokens are stable-sorted by adapter once per
batch (`MultiLoraBatch`), and every kernel gathers its rows through that
order instead of copying them. Shapes depend only on the token count, so
a new batch never changes a grid.
- `_seg_mm_kernel`: shrink (`X_u @ A_u.T`), expand with the scale and
the add into the base output fused, `dH = s * dY_u @ B_u` and `dX += dH
@ A_u`.
- `_seg_wgrad_kernel`: `dA_u = dH_u.T @ X_u` and `dB_u = s * dY_u.T @
H_u`, each reduced over that adapter's tokens only.
- Works on top of a plain or 4-bit (bitsandbytes) base weight through
the existing `matmul_lora` / `fast_dequantize`.
- `MultiLoraLinear` (one A / B parameter pair per adapter, stacked per
forward, ranks and alphas may differ), `inject_multi_lora` (PEFT-style
target matching), `set_multi_lora_batch` (one routing table per device;
every multi-LoRA layer must have the same number of adapters), plus
`per_adapter_loss` (mean within each adapter, summed; adapter ids per
row (B,) or, for packed rows holding several adapters' sequences, per
token (B, T); under gradient accumulation pass `num_items_in_batch`,
each adapter's valid tokens over the window from `adapter_token_counts`,
so microbatches are weighted by tokens like transformers'
`num_items_in_batch`), `drop_absent_adapter_grads_` (an adapter with no
tokens in the batch gets no gradient, so AdamW leaves its weights,
moments and step count alone), `clip_grad_norm_per_adapter_` and
`adapter_state_dict` (exports one adapter as a PEFT LoRA state dict).
- `UNSLOTH_MULTI_LORA_TRITON=0` (read at import,
`set_multi_lora_triton()` at runtime), or no Triton device, falls back
to a masked PyTorch path with no host sync.
- The kernels are registered with `torch.library.triton_op`, so
`torch.compile(fullgraph=True)` traces through forward and backward with
no graph break.

Nothing existing imports it, so no current training path changes. Wiring
it into a trainer (and Studio's job queue, #14645) is a follow-up.

## torch.compile
Small MLP with 3 multi-LoRA layers (4 adapters, ranks 8 / 16 / 16 / 4,
untagged tokens mixed in), forward + backward vs eager, and a tiny Qwen3
with every projection wrapped:

| torch | GPU | graph breaks (fullgraph, varied sizes, dynamic=True,
fallback) | graphs for 4 batches of the same size, different routing |
max rel diff vs eager (bf16) | tiny Qwen3 graph breaks (plain /
multi-LoRA) |
|---|---|---|---|---|---|
| 2.10.0 | A100 | 0 / 0 / 0 / 0 | 1 | 9.8e-3 (fallback 1.2e-2) | 0 / 0 |
| 2.14.1 | A100 | 0 / 0 / 0 / 0 | 1 | 9.8e-3 (fallback 1.1e-2) | 0 / 0 |
| 2.13.0 | B200 | 0 / 0 / 0 / 0 | 1 | 9.8e-3 (fallback 1.1e-2) | 0 / 0 |

A new routing never recompiles (it is data, not a guard); a new token
count recompiles once without `dynamic=True`, as for any layer. Triton
compiles 6 `seg_mm` and 2 `seg_wgrad` variants for this model (per call
site and layer shape, not per token count).

## Packing (varlen) and per-user isolation
Routing is per token, so a packed row can hold several users' sequences.
Isolation between them is the attention backend's varlen masking,
exactly as for single-adapter packing; multi-LoRA adds no cross-token
path. Checked with 8 adapters, one sequence each, packed with
`position_ids` restarting per sequence: every adapter's loss and LoRA
gradients must match that sequence trained alone, and the same rows
without the restart (negative control) must not. Worst per-adapter
gradient relative difference vs alone (bf16, Triton path):

| attention | bsz 2 (4 sequences per row) | 1 flattened row | control
(no restart) |
|---|---|---|---|
| eager (B200) | 0.0 | 9.4e-5 | 1.82 |
| sdpa (B200 / A100) | 1.8e-2 / 1.7e-2 | 1.8e-2 / 1.7e-2 | 1.82 |
| FlashAttention 2 (kernels hub, B200 / A100) | leaks (2.69) | 0.0 /
1.1e-2 | 1.86 |
| FlashAttention 3 (kernels hub, A100) | leaks (2.69) | 1.1e-2 | 1.86 |
| FlashAttention 4 (`flash-attn-4`, B200) | leaks (2.69) | 0.0 | 1.86 |

transformers' flash path only reads `position_ids` restarts as varlen
when the batch is a single flattened row (`_is_packed_sequence` checks
`batch_size == 1`; a plain model without multi-LoRA leaks the same way),
which is what TRL `padding_free` / `DataCollatorWithFlattening` produce.
sdpa and eager build a block mask from `position_ids` at any batch size.
Packing needs `use_cache=False` (training), else no packed mask is
built.
`tests/test_multi_lora.py::test_packed_rows_of_eight_adapters_match_each_sequence_alone`
covers the eager and sdpa cases on CPU.

## Prior art
Punica's SGMV and vLLM's `lora_shrink` / `lora_expand` group tokens by
adapter the same way (vLLM sorts token indices by adapter and gathers
rows inside the kernel, one program per adapter, with the expand fused
into the base output). Both are inference only. Training adds the input
gradient and the per-adapter weight gradients, which reduce over each
adapter's tokens like MoE expert weight gradients.

Because adapter `u`'s gradients only depend on adapter `u`'s rows, a
per-adapter mean loss, per-adapter clipping, skipping adapters absent
from a batch and an elementwise optimizer (AdamW) train each adapter
exactly as it would alone.

## Verification
Kernels against an fp64 reference (forward, dX, dA, dB; uneven segments,
an adapter with no tokens, tokens with no adapter), relative error vs
the same-dtype PyTorch reference:

| GPU | dtypes | shapes | result |
|---|---|---|---|
| T4 (sm75) | fp32, fp16 | 4, up to 8 adapters x 4096 tokens x 2048 |
all at the PyTorch floor (fp16 2.9e-4 vs 3.2e-4 to 4.9e-4) |
| A100 (sm80) | fp32, fp16, bf16 | same | all at the floor (bf16 2.3e-3
vs 2.4e-3 to 3.2e-3) |
| A100 | fp16, 4-bit NF4 base | 4 x 1000 x 512 x 768 | 2.9e-4 vs 3.4e-4
|

A corrupted segment table is caught (negative control).

Training parity, Qwen3-0.6B, 3 adapters on q/k/v/o/gate/up/down, r=16,
AdamW 2e-4, 20 steps, rows from the 3 adapters shuffled into one batch,
against each adapter trained alone with PEFT from the same init:

| precision | step 1 loss rel diff | step 1 grad norm rel diff | 20 step
trajectory vs alone | noise floor (alone, rows reordered) |
|---|---|---|---|---|
| fp32 (L4) | 2.5e-7 to 4.4e-7 | 5.9e-7 to 1.2e-6 | 1.8e-5 / 4.0e-4 /
1.1e-1 | 9.3e-6 / 6.1e-4 / 3.1e-2 (PyTorch loop: 2.0e-5 / 2.8e-4 /
6.0e-2) |
| bf16 (A100) | 5e-4 to 2.4e-3 | 2.5e-3 to 2.4e-2 | final losses 0.187 /
0.183 / 0.246 vs 0.184 / 0.184 / 0.234 alone | within the PyTorch loop's
own spread |

QLoRA (NF4 4-bit base, Qwen3-0.6B, 3 adapters, same setup as above): all
196 multi-LoRA layers on a 4-bit quant state; on a B200 step 1 matches
each adapter trained alone with PEFT on the same 4-bit base to 0 /
8.7e-8 / 1.9e-7 (loss) and 1.2e-3 / 1.0e-4 / 1.8e-4 (grad norm), and the
20 step trajectories stay within the noise floor. On an A100, plain
bitsandbytes already moves a row's loss by up to 1.3e-2 when the same
rows run in a 12 row batch instead of 4 (no multi-LoRA involved);
multi-LoRA's base forward equals bitsandbytes on the same batch exactly.

Per-layer forward + backward on an A100 40GB, bf16, 2048 tokens per
adapter, r=16, median of 10:

| layer | adapters | batched | each adapter separately | PyTorch loop |
speedup |
|---|---|---|---|---|---|
| 4096x4096 | 1 | 1.35 ms | 1.23 ms | 2.02 ms | 0.91x |
| 4096x4096 | 4 | 3.45 ms | 5.25 ms | 6.94 ms | 1.52x |
| 4096x4096 | 16 | 10.89 ms | 26.88 ms | 36.38 ms | 2.47x |
| 4096x14336 | 1 | 2.31 ms | 2.39 ms | 3.47 ms | 1.04x |
| 4096x14336 | 4 | 8.46 ms | 10.07 ms | 14.50 ms | 1.19x |
| 4096x14336 | 16 | 33.99 ms | 49.23 ms | 82.79 ms | 1.45x |

With one adapter it is not faster than the existing single-LoRA path;
the win is several adapters per batch. Peak extra memory is higher at 16
adapters (1.42 GB vs 0.59 GB on the largest layer), since the whole
batch's activations are live at once.

Small per-adapter batches, where launches and small GEMMs dominate (RTX
PRO 6000 Blackwell, bf16, r=16, exclusive card, forward + backward per
layer; separate = the existing fused single-LoRA `LoRA_W` once per
adapter):

| layer | tokens per adapter | 1 adapter | 4 | 16 | 64 |
|---|---|---|---|---|---|
| 4096x4096 | 64 | 0.55x | 2.11x | 7.54x | 13.51x |
| 4096x4096 | 256 | 0.56x | 1.89x | 3.27x | 8.32x |
| 4096x4096 | 2048 | 1.10x | 1.42x | 2.69x | 6.74x |
| 4096x14336 | 64 | 0.58x | 1.91x | 3.86x | 7.74x |
| 4096x14336 | 256 | 0.77x | 1.54x | 2.07x | 4.13x |
| 4096x14336 | 2048 | 0.98x | 1.10x | 1.52x | 2.93x |

At 64 tokens the batched step stays near 0.5 ms from 1 to 16 adapters
while the separate path grows linearly, so the speedup tracks the
adapter count until the GPU fills; at 2048 tokens per adapter both are
compute bound and the gain is the per-launch and small-GEMM overhead
only. A single adapter should keep using the normal LoRA path.

## Tests
`tests/test_multi_lora.py` (CPU, 19 pass): segment table, reference vs a
per-token definition, per-adapter gradient isolation, batched AdamW +
per-adapter clipping matching each adapter trained alone to 1e-10 in
fp64, per-adapter ranks and PEFT export shapes, an adapter absent from
the batch left untouched by AdamW with weight decay, PEFT-style target
matching, and the Triton kernels against fp64 under `TRITON_INTERPRET=1`
with a negative control. The GPU cases (kernel oracle, 4-bit base, and a
`fullgraph=True` compile test asserting 0 graph breaks and 1 graph
across routings, with and without Triton) run on CUDA hosts.

On AMD (Strix Halo gfx1151, ROCm, Studio's install) the whole file runs
on the GPU: 28 passed, 2 skipped (the `TRITON_INTERPRET=1` cases, whose
interpreter build there cannot take a runtime loop bound), including the
kernel oracle and the `fullgraph=True` compile test.

Not covered yet: LoRA dropout (unsupported, Unsloth's default is 0).

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. More of your lovely PRs please.

Reviewed commit: 3bc3dca30f

ℹ️ 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
danielhanchen merged commit 4d5e78c into main Oct 27, 2026
@danielhanchen
danielhanchen deleted the studio-openai-fine-tuning-queue branch October 27, 2026 14:14
Stanley00 pushed a commit to stanley-fork/unsloth that referenced this pull request Oct 27, 2026
…LoRA (unslothai#15344)

Part of unslothai#13603. Builds on the OpenAI fine-tuning queue (unslothai#14645) and the
multi-LoRA kernels (unslothai#14648), both merged.

When several OpenAI-API fine-tuning jobs are waiting in Studio's queue
and are compatible, they now train together in one training process on
one shared base model, with one LoRA adapter per job. Each job still
behaves like a job that ran alone: its own dataset, rank, alpha,
learning rate, epochs, seed, output folder, status, events, metrics,
trained tokens, `fine_tuned_model` and cancellation.

## When it batches

Batching is automatic and only applies to the OpenAI fine-tuning queue.
When the queue head can start and 2 or more compatible jobs are waiting,
up to `UNSLOTH_STUDIO_FT_BATCH_MAX` (default 4) of them start as one
batch. Nothing waits for more jobs, so there is no added latency.

Everything else is unchanged and takes today's path:
- a single queued job, or a job that starts on an idle GPU;
- any incompatible job (it keeps its place in the queue and starts later
as usual);
- runs started from the Studio UI, Desktop or notebooks;
- `UNSLOTH_STUDIO_FT_BATCH_MAX=1`, or an Unsloth without
`unsloth/kernels/multi_lora.py` (checked on disk before anything
starts).

Compatible means same account and subject, text supervised LoRA / QLoRA,
and the same model, 4-bit / dtype, max sequence length, target modules,
rslora, gradient checkpointing, gradient accumulation, optimizer
(`adamw_8bit` or `adamw_torch`), scheduler type, max grad norm and chat
template. Resume, validation files, packing, LoRA dropout, DoRA, LoftQ,
W&B, TensorBoard, `reduce_lr_on_plateau`, streaming datasets, multi-GPU
runs, Apple Silicon (MLX), text-diffusion models, MoE models and models
that are an existing LoRA adapter always run alone. Dataset, learning
rate multiplier, weight decay, warmup, epochs, batch size, rank, alpha,
seed and suffix may differ per job (each job has its own optimizer
parameter group and its own learning rate schedule).

Known limitation: a batched job's checkpoints hold the adapter (loadable
for chat and export), not optimizer and scheduler state, so a cancelled
batched job cannot be resumed from Studio's history the way a lone run
can. The OpenAI fine-tuning API has no resume, and a cancelled job still
keeps its saved adapter.

## How

- `routes/openai_fine_tuning.py`: picks the batch from the queue in
order (`_batch_for`), starts it with `start_training_batch`, and maps
every member to its own Studio run id and alias. Cancelling one member
stops and saves only that adapter (`stop_member`); cancelling the last
running member is today's stop. Until a member records its first step it
reports `validating_files`.
- `routes/training.py`: the per-request admission of `start_training`
moved into `_admit_training_request` unchanged. `start_training_batch`
admits every member with the same checks, runs the shared checks once,
then starts one worker. The GPU choice and the check for keeping a chat
model loaded size the batch by every member's batch size and LoRA rank.
- `core/training/training.py`: the worker config carries
`batch_members`. Events tagged with a member go to that member's own
history row, metrics and terminal state (monotonic). A process-level end
finalizes only members still running.
- `core/training/multi_lora_trainer.py` (new): loads the base once
through the normal Studio loader, formats each member's dataset the
normal way, injects one adapter per member, and trains them with a TRL
`SFTTrainer` subclass. Each optimizer step gives every running member
its own next rows (tagged with its adapter id), the loss is weighted by
each member's own token count, gradients are clipped per member, and one
optimizer holds a parameter group per member so each keeps its own
learning rate schedule. The trainer handles mixed precision, fp16
gradient scaling, accumulation and checkpoint timing. Each member
exports a normal PEFT adapter folder as soon as it finishes (and
`checkpoint-N` folders on its `save_steps` schedule); the others keep
going.
- `core/training/worker.py`: dispatches `batch_members` to the new
trainer.

## Tests

CPU: `tests/test_openai_fine_tuning.py`,
`tests/test_training_batch_backend.py` and
`tests/test_multi_lora_trainer.py` pass (the route and backend suites
plus the trainer suite). They cover:
- grouping, the cap and the kill switch;
- MLX (Apple Silicon) never batches;
- single and incompatible jobs starting with exactly the same call as
before;
- per-member rows, metrics and terminal states;
- member cancel versus last-member cancel;
- the status of a member before its first step;
- a tiny Qwen3 batch matching each job trained alone, with a negative
control;
- the batch running through `SFTTrainer`, per-member `checkpoint-N`
folders, and the learning rate each step reports;
- pretokenized `assistant_masks` datasets training only the assistant
tokens;
- credentials kept out of persisted configs.

GPU, end to end on a Colab L4 (Studio installed from this branch with
`install.sh --local`, `unsloth/Qwen3-0.6B`, OpenAI client API):

| Job | Rows | Epochs | LR multiplier | Result |
|---|---|---|---|---|
| A | 48 | 1 | 1.0 | started alone on an idle GPU, succeeded (12 steps)
|
| B | 64 | 3 | 1.0 | queued behind A, batched, succeeded (48 steps), own
adapter |
| C | 48 | 3 | 0.5 | queued behind A, batched, succeeded (36 steps), own
adapter |
| D | 400 | 3 | 1.0 | queued behind A, batched, cancelled while B and C
kept training; no adapter, 0 trained tokens |

B, C and D started together in one worker process once A finished. B and
C finished at different times, each with its own
`adapter_model.safetensors`. Cancel of D returned 200, D ended
`cancelled` and its history row `stopped`, and B and C were unaffected.

Batched vs alone through the normal Studio path, same job (16 rows,
batch size 8, accumulation 2, so every step covers the whole dataset and
data order cannot move the loss; 20 steps, `unsloth/Qwen3-0.6B`). The
learning rate per step is identical; LoRA A starts from a different
random draw (PEFT vs the batched layers), so later steps differ
slightly.

| GPU | Load | Step 1 loss (alone / batched) | Final loss (alone /
batched) | Trained tokens |
|---|---|---|---|---|
| A100 (bf16) | 4-bit | 5.0189 / 5.0226 | 0.1173 / 0.1151 | 8240 / 8240
|
| A100 (bf16) | 16-bit | 5.0960 / 5.1068 | 0.1162 / 0.1145 | 8240 / 8240
|
| T4 (fp16) | 4-bit | 5.0219 / 5.0204 | 0.1140 / 0.1141 | 8240 / 8240 |
| T4 (fp16) | 16-bit | 5.0969 / 5.0974 | 0.1158 / 0.1139 | 8240 / 8240 |
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]>
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.

1 participant