Skip to content

Keep LoRA on dense Linears sharing a name with fused MoE experts in PEFT's v5 conversion - #12281

Merged
danielhanchen merged 10 commits into
mainfrom
peft-moe-linear-targets
Sep 29, 2026
Merged

danielhanchen merged 10 commits into
mainfrom
peft-moe-linear-targets

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Sep 29, 2026 •

Copy link
Copy Markdown
Member

Summary

On transformers 5, PEFT rewrites MoE LoRA configs written for transformers 4 (_convert_peft_config_moe). Every gate_proj / up_proj / down_proj target is moved onto the fused expert parameters. Many MoE models also keep ordinary nn.Linear layers under those names: the shared experts and the first_k_dense_replace dense 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:

  • loading an adapter trained on transformers 4 (per-expert gate_proj keys, no target_parameters) with FastModel.from_pretrained(adapter) or PeftModel.from_pretrained. The LoRA weights of the dense and shared-expert layers are dropped.
  • calling PEFT's get_peft_model directly with target_modules=["gate_proj", "up_proj", "down_proj", ...] or "all-linear". Those layers are not trained.

FastModel.get_peft_model was not affected: it passes target_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:

  1. Keep Linear targets. convert_peft_config_for_transformers is wrapped. After PEFT converts, any target it removed is put back into target_modules if the modules it names are linear layers PEFT can wrap (nn.Linear and bnb, plus GPTQ, AWQ, HQQ and Megatron linears, read the way PEFT's _get_in_out_features does, or by a class name containing Linear such as EETQ) and their weights are not now parameter targets. The router gate and the expert containers are not nn.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.
  2. Map qwen2_moe onto itself. transformers maps the other families onto the qwen2_moe pattern but has no entry for qwen2_moe itself, and PEFT only adds mixtral. 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 lone gate_proj without up_proj.
  3. PEFT 0.19 string targets. PEFT 0.19 turns a string target_modules into a set of characters and then fails with Target 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:

model LoRA Linears built, main -> PR relative error vs hand-merged, main -> PR
GLM-4.7-Flash 2 / 8 -> 8 / 8 0.165 -> 0.0
DeepSeek-V3 2 / 8 -> 8 / 8 0.122 -> 0.0
Ernie 4.5 2 / 8 -> 8 / 8 NaN on main (see below) -> 0.0
Qwen2-MoE 8 / 8 -> 8 / 8 0.047 -> 0.0 (experts now converted)
Qwen3-MoE (no dense namesakes) 2 / 2 1e-6, unchanged

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_model with bare gate_proj / up_proj / down_proj or "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 fused gate_up_proj for these legacy targets. With explicit target_parameters (the FastModel.get_peft_model path), the config and modules are identical to main. The same holds for FastVisionModel.get_peft_model on 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.Linear4bit modules, and all of their LoRA tensors get gradients. Only qwen2_moe is 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):

  • GLM-4.7-Flash and Qwen2-MoE adapters saved on main or on this branch reload with no missing or unexpected keys and identical logits on both.
  • A Qwen2-MoE adapter saved on main has no expert LoRA. Loaded here, its experts get a new zero-initialised LoRA, so the output is unchanged.

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_parameters left 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_proj namesake not blocking the Linear ones;

  • a lone gate_proj on 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.Linear subclasses 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).

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.
@danielhanchen danielhanchen self-assigned this Sep 29, 2026
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Sep 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-09-29T16:00:29.100779Z acd20fe 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.

@chatgpt-codex-connector

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 🔄 Running since 2026-09-29T13:55:27.952115Z a3c8875 PR opened
ℹ️ 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.

… 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.
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 29, 2026
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex security review

chatgpt-codex-connector[bot]

This comment was marked as resolved.

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.
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 29, 2026
chatgpt-codex-connector[bot]

This comment was marked as resolved.

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.
chatgpt-codex-connector[bot]

This comment was marked as resolved.

@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: acd20fee39

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

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 29, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 29, 2026
@unslothai unslothai deleted a comment from shimmyshimmer Sep 29, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 29, 2026
@danielhanchen
danielhanchen merged commit 7eb3de3 into main Sep 29, 2026
19 of 24 checks passed
@danielhanchen
danielhanchen deleted the peft-moe-linear-targets branch September 29, 2026 19:46
danielhanchen added a commit that referenced this pull request Nov 19, 2026
…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.
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