Repository navigation
Keep LoRA on dense Linears sharing a name with fused MoE experts in PEFT's v5 conversion - #12281
Conversation
PEFT's transformers v5 MoE config conversion moves every gate_proj / up_proj / down_proj target onto the fused expert parameters. On DeepSeek-V3, GLM-4.7-Flash, Ernie 4.5 and other models whose shared experts or first_k_dense layers keep nn.Linear layers under those names, those layers silently lost their LoRA, and loading a transformers v4 adapter dropped their weights. Put such targets back after the conversion, and skip the string conversion PEFT 0.19 cannot do.
transformers maps other families onto qwen2_moe but not qwen2_moe itself, and PEFT only adds the mixtral self-entry, so Qwen2-MoE v4 adapters loaded with their experts unconverted and bare gate/up/down targets never reached the fused experts.
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 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. |
… lone gate_proj working on Qwen2-MoE A regex now restores the module names it matched instead of their leaf names, a non-Linear module sharing a target's name no longer stops the Linears from being restored, and a Qwen2-MoE target PEFT cannot fuse (gate_proj without up_proj) stays unconverted as it was before qwen2_moe was mapped. Restoration failures log a warning. The test fixture also restores the conversion map.
|
@codex security review |
transformers <= 5.5 already maps qwen2_moe onto itself, so PEFT raises for gate_proj without up_proj there. Drop the fallback that kept it unconverted only where this patch added the entry, so every transformers release behaves the same.
GPTQ, AWQ, HQQ and Megatron linears are not nn.Linear, yet PEFT's LoRA layer reads their in/out features and wraps them. Accept the same shapes when restoring targets.
|
Codex Review: Didn't find any major issues. Breezy! 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". |
…get scope, classifier DDP default (#18499) ## Summary PEFT 0.22.0 was released today, and CI installs the latest PEFT, so every PR now fails several shards (seen on #18486, #18487 and others): - `Repo tests (CPU, gloo)`, `gloo-tp`, `gloo-tp-env`: tensor parallel parity tests, e.g. `test_qwen4exp_parallel_matches_one_process[tp2]`, `test_deepseek_v41_parallel_matches_one_process[tp4]`, `test_tp2_matches_one_process[llama]`. The saved adapter is missing keys, or is empty. - `Repo tests (CPU, rest)`: `test_peft_moe_linear_targets.py::test_regex_keeps_its_scope`. - `Repo tests (CPU, rest-2)`: `test_ddp_find_unused_default.py::test_sequence_classification_head_defaults_to_false` and `..._trainable_embeddings_default_to_false`. All of them pass with PEFT 0.21.2 and fail with 0.22.0 on `main`, locally. These are not test problems: each one is a real behaviour change for users on PEFT 0.22. ## Root causes and fixes ### 1. Tensor parallel `save_pretrained` drops every sharded LoRA factor (`tp_native.py`, `pp_native.py`) `_peft_state_dict` asks PEFT which entries to save by passing the model's state dict and matching PEFT's selection back by tensor identity, then gathers the selected DTensors itself (`_full`, which also puts fused tensor parallel layouts back in their 1-GPU order). PEFT 0.22 now gathers selected DTensors inside `get_peft_model_state_dict` (`_gather_state_dict_for_save`), returning new plain tensors. None of them match by identity, so every sharded factor was silently left out. Only replicated tensors survived, and the adapter written by `save_tp_adapter` was partial or empty. Fix: PEFT now selects over each DTensor's local shard (`to_local()`), which it does not gather, and each selection maps back to its key. The gather and fused-layout handling stay in Unsloth as before. The pipeline parallel adapter gather (`adapter_state_dict` in `pp_native.py`) had the same exposure for FSDP2 / tensor parallel stages: PEFT's own gather would skip the fused-layout lookup. It gets the same change. On PEFT 0.21 both paths behave exactly as before. ### 2. A regex `target_modules` loses its scope on MoE models (`import_fixes.py`) PEFT 0.22 rewrote the v5 MoE target conversion so that dense Linears that share an expert name keep LoRA (what #12281 patched in for older PEFT). It converts a regex `target_modules` to the bare leaf names it resolves to, so a regex scoped to one layer's projections, e.g. `model\Wlayers\W1\Wmlp\Wshared_experts\W(gate_proj|up_proj|down_proj)`, now puts LoRA on every layer's `gate_proj` / `up_proj` / `down_proj`. PEFT's own code carries a TODO noting it "may match too broadly if only specific layers are targeted". Fix: after conversion, a bare leaf target that names only Linears, some of which the regex did not match, goes back to exactly the module names the regex matched. Parameter targets and `all-linear` are untouched. ### 3. DDP `find_unused_parameters` default for sequence classification (`_ddp_defaults.py`) PEFT 0.22 adds DistilBERT's `pre_classifier` to the default SEQ_CLS `modules_to_save` (`classifier`, `score`, `pre_classifier`). Unsloth's list of classifier heads that run every forward was `("score", "classifier")`, so a plain classifier LoRA no longer counted as safe and DDP fell back to `find_unused_parameters=True`, which crashes reentrant checkpointing ("ready only once"). `pre_classifier` runs every forward too, so it joins the list. ## Testing | | PEFT 0.21.2 | PEFT 0.22.0 | |---|---|---| | `main` | passes | 5 tensor parallel parity cells, the regex scope test and 2 DDP default tests fail (the CI failures) | | this branch | 336 passed, 9 skipped | 336 passed, 9 skipped | The 336 cover the tensor and pipeline parallel gloo set (`test_qwen4exp_parallel_gloo.py`, `test_parallel_deepseek_v41_gloo.py`, `test_tp_native_oracle.py`, `test_tp_kv_replicated_gloo.py`, `test_pp_fsdp2_gloo.py`, `test_pp_native_gloo.py`, `test_pp_env_gloo.py`, `test_pp_schedules_gloo.py`, `test_frozen_table_tp_gloo.py`, `test_frozen_table_pp_gloo.py`), `test_ddp_find_unused_default.py`, `test_peft_moe_linear_targets.py` and `tests/version_compat/test_peft_conversion_symbol_backfill.py`. The existing parity tests are the guard: each compares the saved adapter and the LoRA targets with a single-process reference, and they fail on `main` under PEFT 0.22.0.
Summary
On transformers 5, PEFT rewrites MoE LoRA configs written for transformers 4 (
_convert_peft_config_moe). Everygate_proj/up_proj/down_projtarget is moved onto the fused expert parameters. Many MoE models also keep ordinarynn.Linearlayers under those names: the shared experts and thefirst_k_dense_replacedense layers. The conversion takes their LoRA away with no warning. Affected families include DeepSeek-V3, GLM-4.7-Flash, GLM-4.5, Ernie 4.5 and Qwen2-MoE. Inside an Unsloth process this hits:gate_projkeys, notarget_parameters) withFastModel.from_pretrained(adapter)orPeftModel.from_pretrained. The LoRA weights of the dense and shared-expert layers are dropped.get_peft_modeldirectly withtarget_modules=["gate_proj", "up_proj", "down_proj", ...]or"all-linear". Those layers are not trained.FastModel.get_peft_modelwas not affected: it passestarget_parameters, and the existing patch already skips the conversion then.This PR adds three monkey patches in
import_fixes.py, next to the existing_patch_peft_moe_target_conversion:convert_peft_config_for_transformersis wrapped. After PEFT converts, any target it removed is put back intotarget_modulesif the modules it names are linear layers PEFT can wrap (nn.Linearand bnb, plus GPTQ, AWQ, HQQ and Megatron linears, read the way PEFT's_get_in_out_featuresdoes, or by a class name containingLinearsuch as EETQ) and their weights are not now parameter targets. The routergateand the expert containers are notnn.Linear, so their conversion stays as it is. If a target also names a non-Linear module, only the Linear modules' full names are restored."all-linear"restores the leaf names, since PEFT resolves it to leaf names too. A regex restores exactly the module names it matched, so a regex scoped to one layer stays scoped.qwen2_moeonto itself. transformers maps the other families onto theqwen2_moepattern but has no entry forqwen2_moeitself, and PEFT only addsmixtral. So Qwen2-MoE v4 adapters loaded with their experts unconverted, and bare targets never reached the fused experts. transformers 5.5 and older still carry that entry, so this only brings later releases back to the 5.5 behaviour. That includes PEFT's error for a lonegate_projwithoutup_proj.target_modulesinto a set of characters and then fails withTarget modules {'n', 'e', 'l', ...} not found. The string conversion is now skipped on 0.19, which behaves like 0.18 (the experts are not converted).Results (transformers 5.17, PEFT 0.21)
A synthetic transformers 4 adapter (r 4, dense + shared + per-expert keys) was loaded into a tiny checkpoint in an Unsloth process. Output was compared with the same model with every delta added to the weights by hand, in fp32:
FastModel.from_pretrained(adapter)gives the same numbers for GLM-4.7-Flash and Qwen2-MoE. The DeepSeek-V3 and Ernie 4.5 tiny checkpoints route through near-ties, so their plain transformers output already differs by 0.2 to 0.3 between fp32 and bf16, with or without this PR. Ernie 4.5 sometimes produces NaN on CPU in both arms for the same reason.get_peft_modelwith baregate_proj/up_proj/down_projor"all-linear": GLM-4.7-Flash, DeepSeek-V3 and Ernie 4.5 go from 6 of 6 dense / shared-expert Linears without LoRA to 0 of 6. Expert ranks are unchanged, including PEFT's rank-2r fusedgate_up_projfor these legacy targets. With explicittarget_parameters(theFastModel.get_peft_modelpath), the config and modules are identical to main. The same holds forFastVisionModel.get_peft_modelon Qwen3.5-MoE.bnb 4-bit GLM-4.7-Flash and DeepSeek-V3, same bare targets: the shared-expert and dense layers go from no LoRA on main to 6
lora.bnb.Linear4bitmodules, and all of their LoRA tensors get gradients. Onlyqwen2_moeis added to the conversion map. The conversion takes 0.18 ms per adapter instead of 0.17 ms.Save / reload across versions (plain
get_peft_model, bare targets):Tests
tests/test_peft_moe_linear_targets.py(CPU) runs on real PEFT and transformers. It covers:dense and shared-expert Linears keeping LoRA for list and
"all-linear"targets, with the experts still converted;explicit
target_parametersleft alone;Qwen3-MoE converting exactly as PEFT does;
a transformers 4 adapter for DeepSeek-V3 and Qwen2-MoE reloading to the hand-merged output within 1e-5;
a dot-free regex keeping its one-layer scope;
a non-Linear
down_projnamesake not blocking the Linear ones;a lone
gate_projon Qwen2-MoE raising PEFT's fused-pair error, as it does on transformers 5.5.GPTQ-style and EETQ-style layers that are not
nn.Linearsubclasses being restored.On main (transformers 5.17), 9 of the 11 fail. With this PR, all 11 pass on PEFT 0.19.1, 0.20.0 and 0.21.1, and on transformers 5.5.0 and 5.17. PEFT 0.18.1 has no conversion, so the module skips. The PEFT converter, symbol backfill, drift and version_compat suites pass as before. The tiny-model regression smoke A/B shows 0 regressions (66 passed on both sides).