Repository navigation
Batched MoE LoRA: every job's expert LoRA in one grouped pass on Zoo's kernels - #16012
Conversation
MultiLoraExperts gains a grouped mode: routes are sorted by (expert, adapter), the frozen expert stacks run as E-group grouped GEMMs and every adapter's LoRA as E*(U+1)-group grouped GEMMs over the same rows, so a step reads (and dequantizes) the base experts once whatever the number of adapters. bnb 4-bit stacks are dequantized a chunk of experts at a time, in forward and again in backward. The mode is chosen on the first call when the layout is supported and grouped GEMM runs natively, after a parity probe against the per-adapter path; UNSLOTH_MULTI_LORA_MOE_GROUPED=0 keeps the per-adapter path. Export layout now follows how a lone PEFT run applies LoRA, not the training mode.
|
@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. |
|
Codex Review: Didn't find any major issues. More of your lovely PRs 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". |
…on-bf16 graphs per adapter, empty top-k
…2 under autocast)
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: f6d25dadc9
ℹ️ 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".
| slot = torch.where(adapter_ids < 0, U, adapter_ids).to(index.device).unsqueeze(1) | ||
| key = (torch.where(valid, index, 0) * Ug + torch.where(valid, slot, U)).reshape(-1) | ||
| order = torch.argsort(key, stable = True) | ||
| offs_pair = torch.cumsum(torch.bincount(key, minlength = E * Ug), 0).to(torch.int32) |
There was a problem hiding this comment.
Use fixed-size counting in the compiled grouped path
When a warmed-up grouped layer runs under torch.compile(..., fullgraph=True) in bfloat16, this torch.bincount introduces a data-dependent output shape: minlength is only a lower bound, so it does not make the operation statically sized for Dynamo. Consequently, the newly enabled compiled grouped path can fail tracing instead of executing, including the bfloat16 case in test_grouped_under_torch_compile; with graph breaks allowed, it instead interrupts compilation at every MoE layer. Since key is already bounded to [0, E * Ug), accumulate into a fixed-size integer tensor with scatter_add_ before taking the cumulative sum.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Agreed and fixed in the latest commit: the pair counts are now a fixed-size scatter_add_ into E * (U + 1) int32 slots, then the cumulative sum. Besides the data-dependent shape under compile, bincount also syncs the host on CUDA to learn the output size, once per MoE layer per step, so this removes that too. The compile test now runs on the test device (CUDA on a GPU host) with fullgraph=True for bfloat16 and float32.
…orch has no grouped GEMM
… test on the test device, bf16 autocast test skips on T4
|
@codex review |
…Triton kernels, base recompute and selective dequant)
|
@codex review |
|
Codex Review: Didn't find any major issues. Hooray! 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". |
…ntity, fused weighted unpermute), dropped routes read a zero row
|
@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". |
|
@codex review |
|
Codex Review: Didn't find any major issues. Keep them coming! 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 cross-platform
Only the
|
…n deterministic hosts)
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: ace1a156ad
ℹ️ 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".
| if T * k == 0: | ||
| return hidden_states.new_zeros(hidden_states.shape) |
There was a problem hiding this comment.
Preserve the autograd graph for empty routing
When a grouped training call has an empty top-k dimension, this early return produces a tensor with no autograd connection to either hidden_states or the adapter parameters. Consequently, backpropagating through this output alone raises an error, and in a larger model the expert adapters become unused parameters rather than receiving the zero gradients required by the default DDP path. The new test_grouped_empty_top_k_gives_zeros exercises this supported input but only checks the forward result; preserve zero-valued graph connections here and extend that test to cover backward.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Agreed, fixed in the latest commit: with nothing routed, the zeros now carry an exact-zero connection to the hidden states and to every adapter's A and B (sums over empty slices, so an inf / NaN adapter still gives exactly 0), the same construction the per-adapter path uses for absent adapters. The empty top-k test now runs backward and checks every gradient exists and is zero; it fails against the previous early return.
… and every adapter
|
@codex review |
|
Codex Review: Didn't find any major issues. More of your lovely PRs 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". |
…CPU BLAS row by an ulp
|
@codex review |
|
Codex Review: Didn't find any major issues. 🎉 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". |
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, #15742 and #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.forwardlooped 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
expert * (U + 1) + adapter, with fixed-size counts (nobincount, 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.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_mmdirectly; 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_projwith anact_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=0forces 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=1prints 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:
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):torch.compile(fullgraph=True)in bf16 and fp32 on the test device.MULTI_LORA_MOE_STATS) and fallback for expert biases or a wrong grouped result.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: