Repository navigation
Add batched multi-LoRA training kernels - #14648
Conversation
|
@codex review |
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
There was a problem hiding this comment.
💡 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".
| HAS_TRITON | ||
| and X.device.type in ("cuda", "xpu") | ||
| and os.environ.get("UNSLOTH_MULTI_LORA_TRITON", "1") != "0" |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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)) |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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) |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
Not changing: adapter ids are integer labels; fractional float ids are not an input this API takes.
[skip ci]
…T-style qualified targets [skip ci]
…optimizer step, per-device routing [skip ci]
…r-adapter means, XPU device guard
…collectives, zero-gradient adapters skip the step [skip ci]
Triton 3.9 defaults enable_fp_fusion to False; every Unsloth launch requests it (tests/test_triton_fp_fusion.py). [skip ci]
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]
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]
|
Codex Review: Didn't find any major issues. Another round soon, please! Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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]
|
Codex Review: Didn't find any major issues. What shall we delve into next? Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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]
|
Follow-up in 232ecc8: the PyTorch reference path (CPU, or @codex review |
|
Codex Review: Didn't find any major issues. Keep it up! Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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". |
…lora_A cannot reach dX [skip ci]
|
Follow-up in 151e406: the gap the previous comment left open is closed. In the reference path, X is now selected per adapter too ( @codex review |
|
Codex Review: Didn't find any major issues. Bravo. Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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". |
[skip ci]
…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 |
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:-1). The base matmul runs once for the whole batch; each adapter's update only touches its own tokens.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_uanddX += dH @ A_u._seg_wgrad_kernel:dA_u = dH_u.T @ X_uanddB_u = s * dY_u.T @ H_u, each reduced over that adapter's tokens only.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), plusper_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 passnum_items_in_batch, each adapter's valid tokens over the window fromadapter_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_andadapter_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.torch.library.triton_op, sotorch.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:
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 6seg_mmand 2seg_wgradvariants 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_idsrestarting 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):flash-attn-4, B200)transformers' flash path only reads
position_idsrestarts as varlen when the batch is a single flattened row (_is_packed_sequencechecksbatch_size == 1; a plain model without multi-LoRA leaks the same way), which is what TRLpadding_free/DataCollatorWithFlatteningproduce. sdpa and eager build a block mask fromposition_idsat any batch size. Packing needsuse_cache=False(training), else no packed mask is built.tests/test_multi_lora.py::test_packed_rows_of_eight_adapters_match_each_sequence_alonecovers the eager and sdpa cases on CPU.Prior art
Punica's SGMV and vLLM's
lora_shrink/lora_expandgroup 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 adapteru'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:
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:
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:
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_Wonce per adapter):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 underTRITON_INTERPRET=1with a negative control. The GPU cases (kernel oracle, 4-bit base, and afullgraph=Truecompile 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=1cases, whose interpreter build there cannot take a runtime loop bound), including the kernel oracle and thefullgraph=Truecompile test.Not covered yet: LoRA dropout (unsupported, Unsloth's default is 0).