Skip to content

Add batched multi-LoRA training kernels - #14648

Merged
danielhanchen merged 25 commits into
mainfrom
multi-lora-batched-training
Oct 27, 2026
Merged

danielhanchen merged 25 commits into
mainfrom
multi-lora-batched-training

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Oct 22, 2026 •

Copy link
Copy Markdown
Member

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

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

Copy link
Copy Markdown
Member Author

@codex review

@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-26T18:25:49.391310Z 151e406 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 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: 3e36de3d8d

ℹ️ 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 thread unsloth/kernels/multi_lora.py Outdated
Comment on lines +72 to +74
HAS_TRITON
and X.device.type in ("cuda", "xpu")
and os.environ.get("UNSLOTH_MULTI_LORA_TRITON", "1") != "0"

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 Keep float64 inputs off the Triton path

For a CUDA/XPU model converted to float64, _use_triton still returns true even though these kernels call tl.dot, whose supported floating-point operand types do not include float64. Thus a model that works through the reference path on CPU fails when moved to an accelerator; restrict this dispatch to the kernel-supported dtypes so unsupported types use the PyTorch fallback.

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: fp64 training on a GPU is not a supported LoRA setup here; fp32, fp16 and bf16 are.

continue
parent_name, _, child = name.rpartition(".")
parent = model.get_submodule(parent_name) if parent_name else model
setattr(parent, child, MultiLoraLinear(module, num_adapters, r, lora_alpha, use_rslora))

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P3 Badge Materialize rank and alpha iterables before wrapping layers

When r or lora_alpha is a one-shot iterable such as a generator, the first matched layer consumes it in MultiLoraLinear, and the second layer sees an empty iterable and raises Need one rank and one alpha per adapter. Because the public annotation accepts any Iterable, normalize these values once before the replacement loop instead of passing the same potentially exhausted object to every layer.

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: ranks and alphas are an int or a list; a one-shot generator is not an expected input.

seq_len: Optional[int] = None,
) -> "MultiLoraBatch":
"""``adapter_ids``: one id per token (any shape), or one per row with ``seq_len`` tokens each."""
ids = adapter_ids.reshape(-1).to(torch.int64)

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 Reject fractional adapter IDs before integer conversion

When adapter_ids is floating-point and contains a fractional value, this cast silently truncates it before validation—for example, 1.9 routes to adapter 1 and -0.5 routes to adapter 0. The subsequent range check therefore accepts the altered IDs, which can train the wrong adapters without an error; validate that values are integral (or require an integer dtype) before converting to int64.

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: adapter ids are integer labels; fractional float ids are not an input this API takes.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

…optimizer step, per-device routing

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

This comment was marked as resolved.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

…collectives, zero-gradient adapters skip the step

[skip ci]
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
chatgpt-codex-connector[bot]

This comment was marked as resolved.

Triton 3.9 defaults enable_fp_fusion to False; every Unsloth launch requests it
(tests/test_triton_fp_fusion.py).

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

This comment was marked as resolved.

per_adapter_loss takes num_items_in_batch, each adapter's valid tokens over the
accumulation window (adapter_token_counts summed over it), like transformers'
num_items_in_batch, so microbatches with fewer tokens are no longer over-weighted.

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

This comment was marked as resolved.

set_multi_lora_batch shares one routing table per device, sized by the first
layer, and the per-adapter helpers assume one adapter count.

[skip ci]
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Another round soon, please!

Reviewed commit: b17d537f91

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

A packed row holds several adapters' sequences, so per_adapter_loss and
adapter_token_counts also take one adapter id per token (B, T). A test packs 8
adapters' sequences into 2 rows with position_ids restarting per sequence and
checks each adapter's loss and LoRA grads match that sequence trained alone
(sdpa and eager), with a no-restart negative control.

[skip ci]
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. What shall we delve into next?

Reviewed commit: b1cb77f5eb

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

The fallback multiplied every adapter's delta by a 0 / 1 routing mask, so an absent adapter whose
weights overflow in fp16 or hold inf / nan turned every token's output into nan (0 * inf = nan).

[skip ci]
@danielhanchen

Copy link
Copy Markdown
Member Author

Follow-up in 232ecc8: the PyTorch reference path (CPU, or set_multi_lora_triton(False)) ran every adapter on every token and summed with a 0 / 1 routing mask, so a non-finite or fp16-overflowing adapter that no token in the batch uses turned every token's output into NaN (0 * inf and 0 * nan are NaN). It now selects each adapter's contribution per token with torch.where, on the intermediate X @ A[u].T and on the output; same compute, no host syncs or data-dependent shapes. The Triton path only computes adapters present in the batch and was not affected. New test_an_absent_adapter_cannot_corrupt_present_tokens_in_the_reference_path (nan_A, nan_B, inf_B, fp16_overflow) fails on the previous head and passes now; tests/test_multi_lora.py 27 passed on CPU and 38 passed on one GPU, including the fullgraph no-recompile test. Not covered: a NaN in an absent adapter's A still reaches X.grad through dH @ A[u]; the present adapters' own gradients stay finite.

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Keep it up!

Reviewed commit: 232ecc849d

ℹ️ About Codex in GitHub

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

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

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@danielhanchen

Copy link
Copy Markdown
Member Author

Follow-up in 151e406: the gap the previous comment left open is closed. In the reference path, X is now selected per adapter too (torch.where(own, X, 0) @ A[u].T), so an absent adapter's non-finite lora_A no longer reaches dX through dH @ A[u] (where it then corrupted the present adapters' gradients in every earlier layer). The nan_A exemption in the absent-adapter test is gone, and new tests/test_multi_lora_absent_nan_a_dx.py checks that the earlier layer's present-adapter gradients are bit-identical with and without the poisoned absent adapter (with a negative control that poisons a present adapter). Clean-case outputs and gradients are bit-identical to the previous head; the reference path goes from 3.20 to 3.72 ms on the sim's shape. CPU: 29 passed, 11 skipped (GPU-only). The Triton path was not affected.

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: 151e406fe6

ℹ️ 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 3c78905 into main Oct 27, 2026
@danielhanchen
danielhanchen deleted the multi-lora-batched-training branch October 27, 2026 07:59
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 |
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