layers_to_transform without layers_pattern matches nothing when the layer list is at the model root
System Info
peft main (0.21.3.dev0), transformers 5.22.1, torch 2.15.0 (CPU), Python 3.12, macOS.
Who can help?
@BenjaminBossan
Reproduction
With layers_to_transform set and no layers_pattern, a model whose layer ModuleList is at the root (e.g. LlamaModel → layers.1.self_attn.q_proj, GPT2Model → h.1.attn.c_attn, as loaded with AutoModel) matches no modules:
import torch.nn as nn
from peft import LoraConfig, get_peft_model
class Block(nn.Module):
def __init__(self):
super().__init__()
self.lin = nn.Linear(4, 4)
class M(nn.Module):
def __init__(self):
super().__init__()
self.layers = nn.ModuleList([Block() for _ in range(3)])
get_peft_model(M(), LoraConfig(target_modules=["lin"], layers_to_transform=[1]))
# NoMatchingPeftModuleError: Target modules {'lin'} not found in the base model. ...
# Note: You specified 'layers_to_transform': [1].
Passing layers_pattern="layers" makes the same config work (adapter on layers.1.lin).
Cause: in check_target_module_exists (src/peft/tuners/tuners_utils.py), the default branch uses r".*?\.[^.]*\.(?P<idx>\d+)\.", which needs at least one module name before the layer container. The layers_pattern branch already makes that prefix optional ((?:^|.*?\.), from #2158). Without the prefix, keys like layers.1.lin don't match, and in layers.1.experts.0.lin the only reachable index is the expert index 0 rather than the layer index 1.
Expected behavior
layers_to_transform=[1] selects layer 1 for root-level layer containers too, consistent with the layers_pattern branch and with prefixed keys (model.layers.1.lin).
I'd like to provide the PR: make the prefix optional in the default regex, r"(?:^|.*?\.)[^.]*\.(?P<idx>\d+)\.", plus root-level cases (including a nested MoE index) in REGEX_TEST_CASES in tests/test_tuners_utils.py. I have this ready locally; tests/test_tuners_utils.py passes with it and the new cases fail on main. AI assistance was used to find and prepare this; I reviewed the change and ran the tests.
This works though, right?
get_peft_model(M(), LoraConfig(target_modules=["lin"], layers_pattern="layers", layers_to_transform=[1]))
Hi! I can confirm layers_pattern="layers" is a workaround, but the default branch of check_target_module_exists (r".*?\.[^.]*\.(?P<idx>\d+)\.") requires a prefix, so root-level keys like layers.1.lin never match without it. I'd like to make the prefix optional ((?:^|.*?\.)) like the layers_pattern branch does, make sure nested keys like layers.1.experts.0.lin still pick the layer index, and add tests. If you consider the current behavior intended, I could instead clarify it in the docs. Could you approve with /peft-triage approved shupandee if either works?
Hi @udsy19 — adding a data point and an offer, since you mentioned you'd like to provide the PR yourself.
I reproduced this on peft main (65e7758, torch 2.15.0 CPU, transformers 5.22.1): the snippet from the report raises NoMatchingPeftModuleError, and layers_pattern="layers" targets layers.1.lin. The cause is the default-branch regex in check_target_module_exists requiring a module prefix before the layer container, so root-level keys like layers.1.lin never match.
I also have your proposed one-line fix working locally (optional prefix, same shape as the layers_pattern branch), with root-level REGEX_TEST_CASES added — including layers.1.experts.0.lin and the layers.2.experts.1.lin trap — plus two end-to-end tests. The new cases fail on unpatched main; with the change they pass.
@shupandee confirmed the same above. @udsy19, if you're still planning to open your PR, I'll step back — you reported it and offered first. If you'd rather not, I'm happy to open mine instead, or share the patch and tests with whoever takes it.
Thanks @0xABCD01, since you and @udsy19 already have this covered, I'll step back.
@BenjaminBossan Yes, with layers_pattern="layers" it targets layers.1.lin as expected. The issue is only the default (no layers_pattern) path, which behaves differently for the same module depending on whether there's a prefix:
model.layers.1.linmatches, butlayers.1.lindoesn't, soLoraConfig(target_modules=..., layers_to_transform=[1])works on a*ForCausalLMbut raisesNoMatchingPeftModuleErroron the bareAutoModel(LlamaModel,GPT2Model, ...) of the same checkpoint;- for
layers.1.experts.0.linthe only index the regex can reach is the expert index0, so it would select by the wrong number once it does match.
The fix is making the prefix optional in the default regex, the same shape the layers_pattern branch already uses ((?:^|.*?\.)), plus root-level cases in REGEX_TEST_CASES (including the nested-MoE one). If that sounds right, I'll open the PR. Thanks @0xABCD01 and @shupandee for confirming.
I wouldn't say that supplying layers_pattern is a "workaround", it's the intended behavior and documented as such. Still, I see an argument to be made that the behavior is inconsistent, so I'm open to see a fix. In this fix, I would like to see:
- Ensure that the fix is backwards compatible (existing working examples shouldn't change what modules are targeted), possibly requiring new test cases to ensure this.
- Ensure that the fix works with all PEFT methods that support this argument.
- The docstrings for
layers_patternand especiallylayers_to_transformcould need some work (typos, clarifying when the argument is needed). It could also be useful to extend thedocs/with a few concrete examples.
LMK if this sounds good to you @udsy19 and I will assign the issue to you, since you initially proposed it.
@BenjaminBossan sounds good, thanks. Fair point about calling it a workaround: layers_pattern is the intended, documented way. Plan for the PR:
- Backwards compatibility. Patterns that already match (any
<prefix>.<name>.<idx>.key, with or withoutlayers_pattern) will target exactly the same modules. The only change is that a root-level<name>.<idx>.key now also matches whenlayers_patternis unset. I'll add parametrized tests that pin the currently targeted modules for the existinglayers_to_transformcases, plus the new root-level case. - Coverage. The fix will cover every PEFT method that accepts
layers_to_transform/layers_pattern, with a test across all of them. - Docs. I'll tidy the
layers_pattern/layers_to_transformdocstrings, saying whenlayers_patternis needed, and add a short example todocs/.
Happy to take it.
Okay, sounds good. Regarding 2: We don't necessarily need test for all PEFT methods: if they all use the same mechanism, it's enough to check one method (like LoRA in the existing tests).
/peft-triage approved @udsy19