#3842·peft

Trainable Tokens adapters with different target modules raise KeyError on forward and merge

Author: DaoyuanLi2816Created Sep 29, 2026Updated Sep 29, 2026

System Info

PEFT main b8674c86183a5dee38d0c3ede392e189593025e5, Python 3.11, PyTorch 2.13.0+cpu, Windows. CPU reproduction; no model downloads.

Reproduction

Adding a Trainable Tokens adapter targeting a different embedding layer breaks forward for both adapters. Merging also fails.

python
import torch
from torch import nn
from peft import TrainableTokensConfig, get_peft_model

class Model(nn.Module):
    def __init__(self):
        super().__init__()
        self.emb0 = nn.Embedding(8, 4)
        self.emb1 = nn.Embedding(8, 4)

    def forward(self, ids):
        return self.emb0(ids) + self.emb1(ids)

def config(target):
    return TrainableTokensConfig(token_indices=[0, 1], target_modules=[target])

model = get_peft_model(Model(), config("emb0"))
ids = torch.tensor([[0, 1, 2]])
model(ids)  # works before adding the second adapter
model.add_adapter("other", config("emb1"))

for name in ["default", "other"]:
    model.set_adapter(name)
    try:
        model(ids)
    except KeyError as exc:
        print(name, repr(exc))

try:
    model.merge_adapter()
except KeyError as exc:
    print("merge", repr(exc))

Output:

default KeyError('default')
other KeyError('other')
merge KeyError('other')

set_adapter activates the name across tuner layers, but TrainableTokensLayer.get_merged_weights and merge directly index token_indices[adapter_name] even where that adapter is absent. The overlap check also assumes all requested adapters exist on each layer.

Controls: targeting emb0 with both Trainable Tokens adapters works; LoRA adapters targeting these two separate embeddings also forward and merge successfully. Disabling both token adapters restores the base forward. This does not involve tied weights or the wrapper nesting addressed by #3820.

Expected behavior / proposed contribution

Each layer should apply only adapters present on that layer, leaving other layers unchanged, as LoRA does. Forward and merge should support adapters with different target modules.

I would like to implement this fix myself after maintainer approval: consistently exclude absent adapters from the Trainable Tokens forward, overlap-check and merge paths, with regression coverage for disjoint and shared targets, adapter switching, and merge/unmerge. I have not changed the library or opened a PR. Is this scope acceptable?