Repository navigation
Multi-LoRA: per-adapter LoRA on fused MoE experts - #15742
Merged
Merged
Conversation
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. |
…adapters in the graph [skip ci]
… folded experts rank-major [skip ci]
…eights itself [skip ci]
Member
Author
|
@codex review |
1 similar comment
Member
Author
|
@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". |
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.
debojyoti-dev
pushed a commit
to debojyoti-dev/unsloth
that referenced
this pull request
Oct 29, 2026
…s kernels (unslothai#16012) Batched multi-LoRA training on fused MoE experts (Studio training several queued jobs together on Qwen3 MoE, Qwen3.5 / Qwen3.6 MoE such as Qwen3.6-35B-A3B, unslothai#15742 and unslothai#15733) now runs every adapter's expert LoRA in one grouped pass, on the same Unsloth Zoo grouped GEMM kernels a single job uses, instead of running the experts once per adapter. 1.3x to 2.1x faster per MoE layer with 2 to 8 jobs, bit-identical results. Until now `MultiLoraExperts.forward` looped over the adapters in the batch and ran the experts module on each adapter's tokens: per MoE layer and step, one routing sort, gather, unpermute and set of grouped GEMM launches per adapter, and one read (with QLoRA, one dequantize) of the frozen expert stacks per adapter. ### How it works * Routes are sorted once by `expert * (U + 1) + adapter`, with fixed-size counts (no `bincount`, so no host sync and a static shape under compile). Each expert's rows stay contiguous, so the same permuted rows serve two group layouts: E groups for the frozen base and E x (U + 1) groups for LoRA. Rows of no adapter go to slot U, whose LoRA factors are zero; dropped routes (expert id outside the table) read a zero row with weight 0, so they add exactly nothing and cannot overflow into a gradient. * Base: Unsloth Zoo's own base GEMM, with the weight provider, recompute in backward and selective 4-bit dequant its single-job MoE forward uses, called once per projection for every adapter together. * LoRA: two of Zoo's grouped GEMMs per projection (its Triton kernels where they apply) over the E x (U + 1) pair groups, on every adapter's factors stacked, zero-padded to the largest rank rounded up to 8, with each adapter's scale (alpha / r or rsLoRA alpha / sqrt(r)) folded in. The factor orientation is the per-adapter stash path's, so every PEFT version and input-major stacks work unchanged. * Routes are combined as Zoo's forward does: its gate-gradient identity and fused weighted unpermute (deterministic fallback without Triton). Gradients reach hidden states, routing weights and every adapter's A and B; adapters absent from a batch get exact zero gradients and stay in the graph for DDP. So a call is 2 base + 4 LoRA grouped GEMMs whatever the number of jobs, and the expert stacks are read and dequantized once. An earlier version of this PR called `torch._grouped_mm` directly; on A100 / L4 that op runs one matmul per group (21,504 launches in three steps at Qwen3.6 shapes), which was 7x to 15x slower than the per-adapter path. Building on Zoo's kernels fixed that and keeps the numerics identical to a single job. ### When it runs Decided per layer on the first call, after the existing stash / fold check: fused 3D `gate_up_proj` / `down_proj` with an `act_fn`, no biases, not interleaved (GPT-OSS), no custom gate, not MXFP4, LoRA only on those two stacks, 16-byte aligned rows, a Zoo with its grouped MoE GEMMs and a grouped GEMM kernel for the device and dtype (Zoo's Triton kernels, else torch's grouped GEMM), then a no-grad parity check on a few rows per adapter against the per-adapter path. After that, a batch where only one adapter has tokens runs that adapter's own pass (nothing to fuse; it is faster there), and inside a compiled graph non-bf16 calls run per adapter (torch's grouped GEMM only traces in bf16). Anything else keeps the per-adapter path exactly as before and logs why once; `UNSLOTH_MULTI_LORA_MOE_GROUPED=0` forces it. A single job never reaches this module (it only exists in batched multi-LoRA training) and Zoo's MoE forward is unchanged, so single-GPU single-job training is not touched. The saved adapter's layout follows how a lone PEFT load applies LoRA, not the training mode, so adapters trained grouped reload exactly as before. `UNSLOTH_ENABLE_LOGGING=1` prints one line per experts class when the grouped pass engages. ### Speed and memory One Qwen3.6-35B-A3B MoE layer (hidden 2048, expert intermediate 512, 256 experts, top 8), forward + backward, 2048 tokens per job, rank 16, bf16, A100 80GB, a fresh process per measurement, ABBA order, 3 repeats (A/A noise under 0.2%); per-adapter path vs this PR: | jobs | 16-bit ms | speedup | 4-bit ms | speedup | peak memory 16-bit / 4-bit | |---|---|---|---|---|---| | 1 | 5.59 vs 6.52 | 0.86x | 7.90 vs 8.43 | 0.94x | 0.96x / 1.00x | | 2 | 11.87 vs 9.03 | 1.31x | 16.18 vs 11.70 | 1.38x | 1.03x / 1.03x | | 4 | 23.01 vs 14.73 | 1.56x | 32.84 vs 17.37 | 1.89x | 1.16x / 1.07x | | 8 | 45.92 vs 29.11 | 1.58x | 67.00 vs 31.70 | 2.11x | 1.30x / 1.12x | Skewed (Zipf) routing gives the same speedups. Mixed ranks 8 / 16 / 32 / 64 (padded to 64): 1.19x with 4 jobs, 1.25x with 8. In every cell the two paths give bit-identical outputs, input gradients and LoRA gradients. The one-job row is why a batch with a single adapter's tokens now runs that adapter's own pass. Peak memory per layer grows with the number of jobs (up to 1.3x at 8 jobs in 16-bit), since every job's stacked factors and intermediates live for the one fused pass. ### Tests `tests/test_multi_lora_experts.py` (36, CPU; also run on GPUs below): * Existing tests run in grouped, stash and fold modes: parity with a lone PEFT run, gradients, isolation (other adapters' rows bit-identical when one adapter changes), absent adapter with NaN weights, input-major layout, autocast, gradient checkpointing against eager. * float64 oracle for grouped: non-square dims, ranks 2 / 4 / 3 with unequal alpha, rsLoRA, rows of no adapter, an expert never routed, skewed routing, a dropped route, an absent adapter; output and gradients for hidden states, routing weights and every A and B. * One pass: 2 base + 4 LoRA GEMMs per call for 2 and 3 jobs; one present adapter runs its own pass with the same result; real bitsandbytes NF4 stacks through Zoo's provider; a dropped route with a NaN weight changes nothing forward or backward; empty top-k; `torch.compile(fullgraph=True)` in bf16 and fp32 on the test device. * Engagement counters (`MULTI_LORA_MOE_STATS`) and fallback for expert biases or a wrong grouped result. * Negative controls: swapping adapter slots, not folding the scale, sending rows of no adapter to adapter 0, removing the dropped-route zeroing, removing the compile dtype gate, or removing the empty top-k guard each turns a test red. `tests/test_multi_lora.py`, `tests/test_multi_lora_absent_nan_a_dx.py`: unchanged, pass. torch 2.6, 2.8, 2.10 (CPU): 35 passed each. GPU, an independent float64 oracle per mode, dtype and scenario, each with a negative control that must disagree: grouped matches the oracle with the same error as the existing stash path on T4 (fp32, fp16), L4, A100 and G4 (fp32, bf16). Under bf16 autocast, grouped logits are as close to an fp32 run as the per-adapter path's (max 0.0045, mean 0.0005 on A100 and G4). Unaligned dims decline grouped; the fp16 fold path on unaligned dims errors on main too (Zoo's grouped GEMM stride rule), unchanged here. Studio end to end through the fine-tuning API (tiny Qwen3.6 MoE, a job trained alone, then batched beside another, 20 steps, LoRA and QLoRA), with the grouped pass engaged in every batched run (its log line in both batched runs on each GPU) and both packed and batched as before: | GPU | mode | step 1 loss alone / batched | step 20 | learning rate | |---|---|---|---|---| | L4 (bf16) | 16-bit | 12.3844 / 12.3843 | 12.1696 / 12.1679 | identical every step | | L4 (bf16) | 4-bit | 12.3861 / 12.3862 | 12.1698 / 12.1669 | identical every step | | T4 (fp16) | 16-bit | 12.3844 / 12.3844 | 12.1696 / 12.1679 | identical every step | | T4 (fp16) | 4-bit | 12.3861 / 12.3861 | 12.1697 / 12.1669 | identical every step |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Adds per-adapter LoRA on fused MoE experts to the multi-LoRA kernels (
unsloth/kernels/multi_lora.py), so a batch of LoRA jobs on a MoE model (Qwen3 MoE, Qwen3.5 / Qwen3.6 MoE such as Qwen3.6-35B-A3B) can train expert LoRAs, each job on its own adapter.How it works:
inject_multi_lora_experts(model, target_parameters, num_adapters, r, lora_alpha, use_rslora)wraps each matched fused experts module (for examplemlp.expertswithgate_up_proj/down_proj) inMultiLoraExperts. Each adapter gets its own expert LoRA per parameter: A(E, r, in)and B(E, out, r), B zero-initialised as in PEFT. Which axis of the stack isinis probed once from the installed PEFT, since PEFT 0.18.x, 0.19.0 and 0.19.1+ read 3D stacks differently, so shapes and exports load on every supported PEFT.stash: the adapter's factors go on the module the way Unsloth Zoo'spatch_param_wrapper_for_moestashes PEFT's, and Unsloth Zoo's patched experts forward applies them (grouped GEMM path, 4-bit experts included). The stash is used only after the forward is seen reading every stashed parameter; otherwise the call is retried infoldmode.fold:torch.func.functional_callwith the delta folded in by onebaddbmmin the weight's dtype with autocast off, as PEFT's ParamWrapper folds it (dense bf16 / fp32 experts only; refuses quantized ones)._unsloth_grouped_mm_format(Qwen3-VL-MoE, GPT-OSS) stash their factors with the roles Unsloth Zoo's extractor gives a lone PEFT run.adapter_state_dictexports expert adapters as PEFTtarget_parametersLoRA (lora_A(E*r, in)expert-major,lora_B(out, r*E)in Unsloth Zoo's layout), nested in parameter registration order exactly as PEFT nests itsParamWrappers, so the export loads withPeftModel.from_pretrained/set_peft_model_state_dict.Tests (
tests/test_multi_lora_experts.py, tinytrl-internal-testing/tiny-Qwen3_5MoeForConditionalGeneration-3.6, three adapters of different ranks, dense and expert targets):Negative controls: a wrong B layout fails 3 tests, shifted adapter routing fails 4, the previous stash orientation fails the input-major test with
mat1 and mat2 shapes cannot be multiplied, the bf16 fold fails the autocast test, and the previous adapter sizing fails the lone-load on PEFT 0.18.1 with a size mismatch.All 10 expert tests pass on PEFT 0.18.1, 0.19.0, 0.19.1, 0.20.0 and 0.21.2 (CPU), and on an L4 GPU inside each of Unsloth Studio's transformers environments (5.3.0, 5.5.0, 5.10.2).
GPU runs (torch 2.14.1, transformers 5.17.0, PEFT 0.21.2): A100 80 GB 42/42 passed (expert tests plus the existing multi-LoRA tests). T4: the 4 expert tests pass;
test_compiles_fullgraph_without_recompiling_per_batchfails the same way on main on a T4 (pre-existing, unrelated).