Repository navigation
Fused LoRA kernels: support lora_dropout and lora_bias - #13898
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: f2b732e72d
ℹ️ 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 adapter is None or dropout is None or adapter not in dropout: | ||
| return 0.0 |
There was a problem hiding this comment.
Fall back when the active adapter is absent
When adapters have different target-module sets and the model switches to an adapter that is absent from one projection, _active_lora_adapter returns None here and this path treats that as zero dropout, allowing the fused call to continue. The subsequent get_lora_parameters(proj) indexes proj.lora_A[adapter] unconditionally, so QKV/MLP execution raises KeyError instead of letting PEFT use the base projection for that module. This becomes reachable for dropout/bias configurations because this change now installs the fused methods for them; return the fallback sentinel when no active adapter exists.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 75116fd: _lora_dropout_and_bias now returns the PEFT fallback sentinel when an enabled, unmerged projection does not contain the active adapter, so PEFT runs the base layer for that module instead of get_lora_parameters raising KeyError. test_active_adapter_absent_from_projection_falls_back uses a second adapter that targets only q_proj and covers no dropout or bias, dropout 0.3, and lora_bias.
|
@codex review |
|
Codex Review: Didn't find any major issues. You're on a roll. 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". |
|
pre-commit.ci run |
1 similar comment
|
pre-commit.ci run |
…-bias # Conflicts: # tests/test_lora_dropout_patch_summary.py
|
@codex review |
1 similar comment
|
@codex review |
|
Codex Review: Didn't find any major issues. Nice work! 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". |
…h dropout/bias kernels)
Zero dropout and no lora_B bias now return straight from _lora_dropout_and_bias after reading PEFT's instance state per projection, so default training and prefill do less host work per layer than before the dropout / bias kernels (no _has_active_lora_bias scan, no getattr chains). Other configs take the general routing unchanged. [skip ci]
|
@codex review |
|
Codex Review: Didn't find any major issues. You're on a roll. 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". |
…-bias # Conflicts: # unsloth/kernels/fast_lora.py
…-GaLore offload, GRPO truncated support, CP save on transformers 4.x (unslothai#14226) ## Summary Fixes for four problems found when re-reviewing recently merged PRs. Each one still reproduced on main, and each has a test that fails on main and passes here. Default configs are unchanged. 1. **Fused LoRA with dropout or a `lora_B` bias (unslothai#13898).** - **Graph breaks:** before torch 2.11 the fused LoRA function runs with Dynamo disabled. unslothai#13898 moved dropout and bias projections from PEFT onto that path, so compiling them hit a graph break each and `fullgraph = True` failed. While compiling on torch < 2.11 those projections now run PEFT again, as they did before unslothai#13898. Plain LoRA, eager fusion and torch 2.11+ are unchanged. - **Memory:** on 4-bit weights the dropout and bias path dequantized into the shared global buffer, so one dense weight stayed resident; PEFT never keeps one. That path now dequantizes into a temporary, including in eval, where dropout is a no-op. `matmul_lora` gets a `use_global_buffer` keyword, default `True`, so every other caller is unchanged. 2. **Q-GaLore optimizer state offload (unslothai#14025).** If a step pre-hook registered after the offloader created a gradient, that parameter's state stayed on CPU and the step crashed with a device mismatch. State is now restored inside the step, after every pre-hook has run. 3. **GRPO truncated-support scoring (unslothai#13900).** This needs the scored policy to be the sampler. That is not the case with a reference model (`beta != 0`), with rollouts reused across optimizer steps, or when vLLM weight sync is skipped (LoRA or quantized without `fast_inference`). In those cases the new policy's implied probabilities did not sum to 1, which made the PPO ratio wrong. Those cases now warn once and score the full vocabulary; on-policy runs with `beta = 0` keep the feature. 4. **Context-parallel save on transformers 4.x (unslothai#14028).** With `SHARDED_STATE_DICT` the sharded save wrote no adapter, and with `FULL_STATE_DICT` it gathered the frozen base weights. The save now gathers only the adapter and rank 0 writes it. Transformers 5 is unchanged. The routing replay part of the same review is in unslothai/unsloth-zoo#1874. ## Tests | Test | main | this PR | |---|---|---| | `tests/test_fused_lora_dropout_bias_compile_memory.py` | 18 failed | 18 passed | | `tests/test_fused_lora_dropout_bias.py` (eval keeps the dropout route) | failed | passed | | `tests/test_optimizer_state_offload.py` | 2 failed | 38 passed | | `tests/test_grpo_truncated_support_policy_gate.py` | 4 failed | passed | | `tests/test_context_parallel_fsdp2_save_gloo.py` (transformers 4.57.6, 2 gloo ranks) | 2 failed | passed | unslothai#13898 base vs head, Llama block at 4096 / 11008, 3 arms. "PEFT" is main with fused dropout and bias turned off, i.e. the routing before unslothai#13898: | torch | Graph breaks on dropout / bias configs (main / this PR) | 4-bit dropout / bias peak MiB (main / PEFT / this PR) | |---|---|---| | 2.10, T4 | 6 / 0, fullgraph fails on main | 293.0 to 294.3 / 209.8 to 211.0 / 207.0 to 208.3 | | 2.13, B200 | 0 / 0 | 340.6 to 341.1 / 257.5 to 257.7 / 254.6 to 255.1 | | 2.14, T4 | 0 / 0 | 292.9 to 293.3 / 209.7 to 210.0 / 206.9 to 207.3 | 16-bit and default configs give the same memory and graph break counts in all three arms. Plain LoRA on 2.10 has 6 graph breaks in every arm; that is older than unslothai#13898 and is left as is. ## Not covered here - Torch 2.11 and 2.12 were not run. Items 2 to 4 ran on torch 2.13 only. - No full-model training or throughput run; the unslothai#13898 memory numbers are per block. - No vLLM end-to-end GRPO run, no NCCL multi-GPU save, no `push_to_hub`. - Off-policy truncated support falls back to full-vocabulary scoring rather than the sampler's kept token set.
…rs, trainable bases and autocast dtype mismatches (unslothai#14806) The fused LoRA kernels (apply_lora_qkv, apply_lora_o, apply_lora_mlp_*) only compute plain LoRA over a frozen base weight in the input dtype. Routing let four other configurations through, and unslothai#13898 widened their reach to lora_dropout > 0 and lora_bias configs: 1. PEFT LoRA variants. Routing never checked `lora_variant`, so a variant adapter (KaSA, MoNTeCLoRA, VeLoRA, BD-LoRA, ...) trained as plain LoRA with no error. 2. Disabled or merged adapters. The fused backward dereferenced the missing LoRA weights and raised `'NoneType' object has no attribute 'to'` whenever the input required grad. 3. Trainable base weights. The fused backward returns None for the base weight, so a base projection unfrozen after attaching LoRA silently got no gradient. 4. Autocast dtype other than the input dtype (fp16 input under bf16 autocast, bf16 under fp16, fp32 under fp16). The matmuls return the autocast dtype, but the in-place LoRA accumulation does not autocast, so the forward raised `self and mat2 must have the same dtype`. All four reproduce on main and, for the default dropout = 0 / no bias config, on the commit before unslothai#13898. Change: `_lora_dropout_and_bias` now returns None (PEFT's own forward) for variants, trainable base weights, and autocast in a dtype other than the input's. Disabled or merged adapters fall back only when a gradient is needed (grad enabled and the input or base weight requires grad). The no-grad DPO / GRPO reference forward stays on the fused base matmul, bitwise equal to PEFT's base_layer, including on a 4-bit NF4 base. The added checks are attribute reads and mode queries: no tensor ops, no syncs, and they compile with fullgraph=True. The patch summary names a LoRA variant adapter. Eligible configurations take the same branches and make the same fused calls with the same arguments as before. Tests: tests/test_fused_lora_peft_fallbacks.py checks that no fused Function runs for each case and that outputs, input grads and every parameter grad match PEFT bitwise (float64 on CPU, float32 on CUDA). It covers o, qkv and mlp, dropout 0 / 0.3, and lora_bias on / off, and includes a real PEFT KaSA adapter. On main 110 of these fail; with this change 181 pass and 10 skip (merging a lora_B bias, which PEFT refuses). Guards confirm that eligible configs and no-grad disabled / merged adapters still fuse. The neighbouring fused LoRA, QLoRA, FSDP and QAT suites go from 366 passed on main to 547 passed with the new file, with no new failures.
Unsloth only installed its fused LoRA kernels (QKV, O, and the SwiGLU / GeGLU MLP) when
lora_dropout == 0and no adapter hadlora_bias = True. Anything else dropped every layer back to PEFT's per-projection forward, which on a small 4-bit Llama withlora_dropout = 0.05costs about 28% more time per step (39.1 ms vs 30.5 ms median, exclusive B200, 3 repeats each) and slightly more memory.This PR runs both inside the fused autograd functions with PEFT's semantics:
nn.Dropoutmakes (native_dropouton CUDA / XPU,bernoulli_noise on CPU). On 4-bit (bitsandbytes) bases under autocast, masks and the RNG state afterwards are therefore identical to PEFT's from the same seed. On 16-bit bases PEFT casts the input to the fp32 adapter dtype before dropout and so draws its masks on an fp32 copy; the fused path draws on the bf16 / fp16 activations, so the masks differ there while both are valid Bernoulli draws. Gradient checkpointing recompute replays the masks in both cases. Only the boolean masks are saved for backward; the dropped-out input is rebuilt from them.lora_bias: the bias onlora_Bis added as(lora_B(x) + bias) * scaling, PEFT's order, and its gradient is returned.UNSLOTH_FUSED_LORA_DROPOUT=0andUNSLOTH_FUSED_LORA_BIAS=0restore the old fallback. DoRA still falls back to PEFT.Testing:
tests/test_fused_lora_dropout_bias.py(new): fused vs PEFT from the same seed on CPU and CUDA, fp32 / bf16 / fp16, each scored against an fp64 PEFT run on PEFT's own masks; masks and RNG state are bit-identical; checkpoint recompute is bit-identical; eval mode and the kill switches behave like PEFT. 49 of its cases fail on main (fused path not taken, or dropout ignored when the kernels are called directly).While doing this, Inductor on torch 2.13 produced wrong values for
add(..., alpha=float)inside these autograd functions (eager and aot_eager were correct), so the new code multiplies explicitly.Without autocast (fp32 adapters in a hand-written loop) PEFT draws its masks on an fp32 copy, so the masks differ from the fused path there; both are valid dropout. Trainer runs on 4-bit bases under bf16 / fp16 autocast match PEFT's masks exactly.
Composes with #13868 (both touch the
LoRA_MLP/LoRA_QKVsave_for_backward lines; a trivial merge keeps both, and the backward rebuilds the dropped-out input before dX is written into X's buffer).Not covered: DoRA (still falls back), torch 2.6 to 2.10, T4 / L4 / A100 / AMD / XPU,
lora_biastiming.