peft icon indicating copy to clipboard operation
peft copied to clipboard

LoRA Embedding max_norm changes merged output and prevents restoring base weights on unmerge

Open galleonli opened this issue 2 months ago • 3 comments

System Info

  • PEFT: 0.21.1.dev0, unmodified main at b8674c86183a5dee38d0c3ede392e189593025e5
  • PyTorch: 2.14.0; Transformers: 5.17.0; Accelerate: 1.15.0
  • Python: 3.12.3; macOS 26.6.2, arm64
  • CPU, float64, evaluation mode; no checkpoint downloads or quantization

Reproduction

LoRA accepts an nn.Embedding with max_norm=1.0, but a forward pass after merge_adapter() changes its output. After unmerge_adapter(), the original base weights and output are not restored. safe_merge=True behaves the same way.

import torch
from torch import nn
from peft import LoraConfig, get_peft_model


class TinyModel(nn.Module):
    def __init__(self):
        super().__init__()
        self.embed = nn.Embedding(4, 2, max_norm=1.0)

    def forward(self, input_ids):
        return self.embed(input_ids)


model = get_peft_model(
    TinyModel(),
    LoraConfig(r=1, lora_alpha=1, target_modules=["embed"], lora_dropout=0),
).double().eval()
layer = model.base_model.model.embed
ids = torch.tensor([0, 1])

with torch.no_grad():
    layer.base_layer.weight.copy_(torch.tensor([[0.6, 0.0]] * 4, dtype=torch.float64))
    layer.lora_embedding_A["default"].fill_(0.5)
    layer.lora_embedding_B["default"].copy_(torch.tensor([[0.0], [2.0]]))
    before = model(ids).clone()
    weight_before = layer.base_layer.weight.clone()
    model.merge_adapter(safe_merge=True)
    merged = model(ids).clone()
    model.unmerge_adapter()
    weight_after = layer.base_layer.weight.clone()
    after = model(ids).clone()

print("before:", before[0].tolist())
print("merged:", merged[0].tolist())
print("after unmerge:", after[0].tolist())
print("base weight error:", (weight_after - weight_before).abs().max().item())
torch.testing.assert_close(after, before)

The initial output is [0.6, 1.0]; the merged and post-unmerge outputs are approximately [0.514496, 0.857493]. The maximum base-weight difference after unmerging is approximately 0.142507, and the assertion fails.

Controls checked with fresh models:

max_norm Forward between merge and unmerge safe_merge Maximum post-unmerge output/base-weight difference
None No or yes False or true 0.0
1.0 No False or true 0.0
1.0 Yes False or true approximately 0.142507

The base embedding row and the LoRA A row are each below the norm limit before merging. The difference arises when the combined row exceeds it: PyTorch's embedding forward renormalizes the merged weight in place. Subtracting the LoRA delta during unmerge then cannot recover the original base weight. This is separate from dropout, quantization, and ordinary floating-point merge error.

Expected behavior

If this configuration supports merging, merging and unmerging should preserve the unmerged model's behavior within numerical tolerance. If the max_norm semantics make that unsupported, an explicit rejection before modifying weights would be preferable to silently changing predictions and leaving altered base weights after unmerge.

I did not find an existing report for this case in the max_norm and embedding/merge searches. The max_norm mentions in #1436 and #2376 concern other embedding implementations.

I would like to contribute a focused guard and regression tests if maintainers agree that rejecting this merge is the right scope. I have not implemented a library change or opened a PR; I will wait for the approval required by the contribution policy. A different supported behavior may be more appropriate, so I would appreciate guidance on the intended semantics.

AI assistance was used for the investigation, reproducer, and this report. All reported results come from local CPU runs; no human code review or GPU validation is claimed.

galleonli avatar Sep 28 '26 21:09 galleonli

Thanks for reporting. This sounds like a very theoretical problem, I have never seen that option being used in the wild. Did you encounter a model that uses this option or aware that such model architectures exist, for instance, in Transformers? I didn't find anything after a quick search.

BenjaminBossan avatar Sep 29 '26 08:09 BenjaminBossan

Thanks for checking. I found this through a synthetic test of LoRA embedding merge/unmerge behavior, not from a failure in an actual training run. I don't currently have a concrete model that enables this option.

I checked Transformers at ebd5de0. I-BERT's QuantEmbedding accepts max_norm=None, but its model constructors leave the option unset. Idefics explicitly documents max_norm as unsupported. I haven't found a supported architecture configuring a non-None value.

The reproduction establishes the behavior for an explicitly configured embedding, but I haven't established practical user impact. I haven't implemented a fix or opened a PR; I'll keep this at the issue-discussion stage.

galleonli avatar Sep 29 '26 09:09 galleonli

Okay, so I think this is not an issue in practice. Straight out rejecting to apply PEFT to the embedding might also be too strict of a solution, it's quite possible that the user is aware and knows what they're doing. I think there is thus nothing further to do here.

BenjaminBossan avatar Sep 29 '26 11:09 BenjaminBossan