Skip to content

Studio: train compatible queued fine-tuning jobs together with multi-LoRA - #15344

Merged
danielhanchen merged 30 commits into
mainfrom
studio-ft-multi-lora-batching
Oct 27, 2026
Merged

danielhanchen merged 30 commits into
mainfrom
studio-ft-multi-lora-batching

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Oct 26, 2026 •

Copy link
Copy Markdown
Member

Part of #13603. Builds on the OpenAI fine-tuning queue (#14645) and the multi-LoRA kernels (#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

…queued events, ride out transient 409s

[skip ci]
… admission races, queue creates during transient conflicts
…LoRA

When two or more compatible OpenAI-API fine-tuning jobs are waiting, the queue
starts them as one training process: the base model loads once and each job
trains its own LoRA adapter through the fused multi-LoRA kernels, keeping its
own dataset, rank, learning rate, epochs, seed, run record, metrics, output and
cancellation. A single job, an incompatible job, every run started outside the
queue, and installs without the multi-LoRA kernels keep today's path.
UNSLOTH_STUDIO_FT_BATCH_MAX (default 4, 1 disables) caps a batch.
@danielhanchen danielhanchen self-assigned this Oct 26, 2026
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 26, 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-27T14:16:08.582412Z 1951430 Manual request
🔒 Security Review 🔄 Running since 2026-10-26T08:37:34.319515Z 5a9cb94 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.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex security review

chatgpt-codex-connector[bot]

This comment was marked as resolved.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 26, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 26, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 26, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 26, 2026
… into studio-ft-multi-lora-batching

# Conflicts:
#	studio/backend/core/training/training.py
#	studio/backend/routes/training.py
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 27, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 27, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 27, 2026
chatgpt-codex-connector[bot]

This comment was marked as resolved.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 27, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 27, 2026
chatgpt-codex-connector[bot]

This comment was marked as resolved.

Base automatically changed from studio-openai-fine-tuning-queue to main October 27, 2026 14:14
…batching

# Conflicts:
#	studio/backend/routes/openai_fine_tuning.py
#	studio/backend/tests/test_openai_fine_tuning.py
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. 🚀

Reviewed commit: 195143084c

ℹ️ 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 Oct 27, 2026
@danielhanchen
danielhanchen merged commit 3e3c2fd into main Oct 27, 2026
@danielhanchen
danielhanchen deleted the studio-ft-multi-lora-batching branch October 27, 2026 16:53
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 added a commit to Etherll/unsloth that referenced this pull request Oct 28, 2026
…t's path guard (unslothai#15727)

When compatible OpenAI fine-tuning jobs are queued, `_start_queued`
probes the head job's model (`_trains_alone`) to decide whether it can
join a multi-LoRA batch. That probe ran with the raw `model_name`,
before the account's path guard and outside the job's account context. A
managed account could queue two batchable jobs whose model is a UNC path
(`\\host\share\model` or `//host/share/model`); on a Windows host the
probe's file checks then open that share, which makes the Studio service
account sign in over SMB and hands its NetNTLM response to that host.

`account_path` already refuses share and device paths for managed
accounts before touching the filesystem, and `start_training` applies
it, but the batch probe ran first.

## Fix

- The probe calls `account_path(model_name, reference = True)` first. A
path the account may not use makes the job train alone, so the normal
single start refuses it with the usual 403.
- `_start_queued` runs the probe under `arun_as(entry.account, ...)`, so
it sees the job's account rather than the drain loop's.

Owners, Desktop and notebooks are unaffected (`account_path` returns
early for the owner). Managed accounts still batch Hub ids and workspace
paths exactly as before. The check is a pure lookup, so repeated drains
behave the same.

## Tests

- `test_batch_probe_never_touches_a_managed_share_path` (both UNC
spellings): fails on main (the diffusion, LoRA and config probes all
receive the share path), passes here.
- `test_batch_probe_unchanged_for_the_owner`: the owner's jobs still
probe and batch.
- `test_openai_fine_tuning.py`: the same 10 tests fail as on main, all
multi-LoRA batching tests that fail since packing became the default
(unslothai#15478 landed before unslothai#15344); 67 pass. Account path suites: 880 passed.
danielhanchen added a commit to Etherll/unsloth that referenced this pull request Oct 28, 2026
…documents (unslothai#15733)

Since unslothai#15478 turned packing on by default, every queued fine-tuning job
asks for packing, and unslothai#15344 sent packing jobs to train alone. So
compatible jobs stopped batching at all, and three batching tests in
`studio/backend/tests/test_openai_fine_tuning.py` fail on main
(`test_compatible_queued_jobs_start_as_one_batch`,
`test_jobs_differing_only_in_member_fields_batch_in_queue_order`,
`test_only_plain_dense_models_batch[dense]`).

This PR lets packing jobs batch, with packing kept per job so a job's
documents never meet another job's:

* Each member packs only its own documents, with TRL's default packing
strategy at the run's max length, the same packing its single run would
get. Pre-tokenized datasets stay unpacked, as in the single run.
* Once any member packs, each micro-batch is one padding-free row, as in
the single packed run: positions restart at every document,
`packed_seq_lengths` is passed to the model, every token is routed to
its own member's adapter, and the label opening each document is masked
so nothing is predicted across a boundary. A document never spans two
members.
* Packing is used only where the single job's Unsloth SFTTrainer would
pack: not on padding-free blocklisted models, encoder-decoders, forwards
that cannot take `packed_seq_lengths`, or hybrid linear-attention models
whose varlen kernels are not available (their recurrent state would
carry across documents). Elsewhere packing is ignored, as the single job
ignores it.
* Packing is also used only where a packed forward provably keeps
documents apart: before packing, one forward of a short document after
another in one packed row is compared with that document alone, and a
model whose packed documents see each other trains unpacked with a
warning. Qwen3.5 on transformers 5.3 (Studio's tier for it) passes every
static check above, yet its full attention layers let packed documents
attend across the boundary (logits off by up to 14.7 against 0.36
elsewhere); the root cause is fixed in core by unslothai#15771, and this check
keeps batched jobs isolated on any install that lacks it.
* Vision-language models (Qwen3.5, Qwen3.6) tokenize their text through
the processor's tokenizer, as the single job does; the full processor is
still what gets saved.
* `packing` is now a per-member field, so packed and unpacked jobs can
share a batch; an unpacked member in a packed batch trains exactly as it
would alone.

Tests (CPU, tiny Qwen3;
`studio/backend/tests/test_multi_lora_trainer.py`):

* a packing member's losses and saved adapter are the same with a
different neighbour and alone, and every packed document holds one
adapter's tokens with positions restarting at each;
* an unpacked member beside packed ones matches its own run;
* packing is ignored when the model cannot pack; a hybrid packs only
with its varlen kernels;
* packed rows keep each document's labels with its tokens.

Negative control: with positions not restarting per document, the
isolation checks fail. All of `test_multi_lora_trainer.py`,
`test_openai_fine_tuning.py` and `test_training_batch_backend.py` pass
(113).

GPU, through the OpenAI-compatible API on a fresh `install.sh --local`
Studio (Qwen3-0.6B, 4-bit and 16-bit; a job trained alone, then the same
job batched beside another while a third holds the GPU; 16 documents, 20
steps, packing on by default):

| GPU | mode | batched job packed | steps alone / batched | step 1 loss
alone / batched | final loss alone / batched | learning rate |
|---|---|---|---|---|---|---|
| RTX PRO 6000 (bf16) | 4-bit | 16 documents into 1 row | 20 / 20 |
2.2689 / 2.2807 | 0.00017 / 0.00027 | identical every step |
| RTX PRO 6000 (bf16) | 16-bit | 16 documents into 1 row | 20 / 20 |
2.6012 / 2.5983 | 0.00016 / 0.00019 | identical every step |
| T4 (fp16) | 4-bit | 16 documents into 1 row | 20 / 20 | 2.2761 /
2.2772 | 0.00058 / 0.00020 | see below |
| T4 (fp16) | 16-bit | 16 documents into 1 row | 20 / 20 | 2.6012 /
2.6012 | 0.00017 / 0.00015 | see below |

The single run packed too ("Unsloth: Packing enabled") on every arm. On
the T4 the learning-rate schedules drift apart after the single run
skips a step on an fp16 overflow while the batched job does not; that
comes from the batch sharing one fp16 loss scale, which is on main
already and is fixed separately in unslothai#15741.
danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Oct 28, 2026
…i#15809)

Queued LoRA / QLoRA fine-tuning jobs on fused-expert MoE models (Qwen3
MoE, Qwen3.5 / Qwen3.6 MoE such as Qwen3.6-35B-A3B) now batch together
like dense models, with each job's expert LoRA on its own adapter
through the expert multi-LoRA kernel from unslothai#15742. Until now every MoE
job trained alone.

What batches:

* `qwen3_moe`, `qwen3_5_moe` and `qwen3_5_moe_text` on transformers 5.x
(expert-only targets such as just `gate_up_proj` included), where their
experts are fused stacks that Unsloth Zoo's MoE forward reads LoRA for.
Each job gets the expert LoRA its single run gets: the same PEFT
`target_parameters` (from `get_moe_target_parameters`), the same
per-expert init (fan-in over the input dimension, as PEFT inits its
`(E*r, in)` matrix) and the same rank and alpha. Its saved adapter is
the PEFT `target_parameters` adapter the single run saves.
* Everything else that is MoE still trains alone, as before: other MoE
layouts (per-expert Linears, transformers 4.57, packed or remote
experts), jobs with a router auxiliary loss (the load-balancing loss
would average every job's tokens together), and an installed Unsloth
without the expert kernel.
* State-space and short-convolution mixers (Mamba, Jamba, Zamba,
Falcon-H1, Nemotron-H, LFM2 and similar) are now refused for batching up
front by config and train alone; their recurrent and conv state is not
checked batched. Qwen3.5's Gated DeltaNet layers are not matched by this
and keep batching.

Tests (CPU, `studio/backend/tests/test_multi_lora_trainer.py`,
`test_openai_fine_tuning.py`): a batched MoE member's losses, gradients
and saved adapter (dense and expert LoRA) match its single run and do
not move with its neighbour; every expert `lora_B` trains; MoE layouts
and configs outside the list, router aux loss and SSM mixers are routed
to train alone. 128 pass.

GPU, through the OpenAI-compatible API on a fresh `install.sh --local`
Studio (tiny Qwen3.6 MoE,
`trl-internal-testing/tiny-Qwen3_5MoeForConditionalGeneration-3.6`; a
job trained alone, then the same job batched beside another while a
third holds the GPU; 16 documents, 20 steps):

| mode (L4, bf16) | step 1 loss alone / batched | step 10 | step 20 |
learning rate | saved adapter |
|---|---|---|---|---|---|
| 4-bit | 12.3861 / 12.3862 | 12.1959 / 12.1939 | 12.1697 / 12.1669 |
identical every step | same 28 tensors and shapes |
| 16-bit | 12.3844 / 12.3843 | 12.1952 / 12.1944 | 12.1696 / 12.1678 |
identical every step | same 28 tensors and shapes |

On a T4 (fp16, each job with its own loss scale): 4-bit step 1 12.3861 /
12.3861, step 20 12.1697 / 12.1669; 16-bit step 1 12.3844 / 12.3844,
step 20 12.1696 / 12.1679; learning rate identical every step, no
skipped steps.

Every run trained all 20 steps on the same 8240 tokens, and the same
with packing off. Step 1 gradient norms differ (0.64 alone, 0.55
batched) while the step 1 losses match: a batched member draws its LoRA
A from its own seed (the same Kaiming distribution PEFT uses,
independent of batch order, as dense members already do since unslothai#15344),
so the random A differs from the single run's draw and with it the first
gradient; the saved adapters hold the same tensors with norms within 5%.

Expert kernel tests (`tests/test_multi_lora_experts.py`, from unslothai#15742)
pass on an L4 inside each of Studio's transformers environments.
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