Skip to content

Batched MoE LoRA: every job's expert LoRA in one grouped pass on Zoo's kernels - #16012

Merged
danielhanchen merged 14 commits into
mainfrom
multi-lora-moe-grouped
Oct 29, 2026
Merged

danielhanchen merged 14 commits into
mainfrom
multi-lora-moe-grouped

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Oct 29, 2026 •

Copy link
Copy Markdown
Member

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

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.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 29, 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-29T21:17:40.016793Z 56beaf0 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 danielhanchen self-assigned this Oct 29, 2026
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. More of your lovely PRs please.

Reviewed commit: 89b3ef2586

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

@codex review

@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: 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".

Comment thread unsloth/kernels/multi_lora.py Outdated
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)

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 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 👍 / 👎.

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.

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.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Hooray!

Reviewed commit: 377083130f

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

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: 81c652fa83

ℹ️ 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 changed the title Batched MoE LoRA: run every adapter's expert LoRA in one grouped GEMM pass Batched MoE LoRA: every job's expert LoRA in one grouped pass on Zoo's kernels Oct 29, 2026
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Keep them coming!

Reviewed commit: 86c77a819d

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

The cross-platform test legs fail on all three OSes in this PR's own new test:

tests/test_multi_lora_experts.py:178: in test_another_adapter_cannot_move_a_row
    torch.testing.assert_close(after[1:], before[1:], atol = 0, rtol = 0)
E   AssertionError: Tensor-likes are not equal!
Leg Mismatched elements Greatest abs diff
ubuntu-24.04 156688 / 2979840 (5.3%) 2.98e-08
macos-15 18448 / 2979840 (0.6%) 2.98e-08
windows-2025 311483 / 2979840 (10.5%) 5.96e-08

Only the [grouped] parametrization fails. The differences are one or two float32 ulps, so the rows are not being moved. The grouped path computes them with a different reduction order once another adapter's rows change the grouped GEMM's shape or blocking. atol = 0, rtol = 0 is stricter than the grouped kernel guarantees on CPU. Two options:

  • If row isolation is meant to be bitwise, the grouped path needs a fixed per-row reduction order.
  • Otherwise, compare at float32 ulp scale (for example rtol = 1e-6, atol = 1e-7). Keep the bitwise check for the loop path, where it holds.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

shimmyshimmer pushed a commit to shimmyshimmer/unsloth-staging-4 that referenced this pull request Oct 29, 2026

@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: 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".

Comment thread unsloth/kernels/multi_lora.py Outdated
Comment on lines +1195 to +1196
if T * k == 0:
return hidden_states.new_zeros(hidden_states.shape)

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 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 👍 / 👎.

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.

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.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. More of your lovely PRs please.

Reviewed commit: 9d1889bd80

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

shimmyshimmer pushed a commit to shimmyshimmer/unsloth-staging-4 that referenced this pull request Oct 29, 2026
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: 56beaf03da

ℹ️ 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 69117f1 into main Oct 29, 2026
3 of 34 checks passed
@danielhanchen
danielhanchen deleted the multi-lora-moe-grouped branch October 29, 2026 21:31
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant