OFT Conv2d forward is wrong for kernels larger than 1x1: identity init changes the output and does not match the merged model
System Info
peft 0.21.1.dev0 (main @ b8674c8) and peft 0.21.0, torch 2.14.0+cpu, transformers 5.17.0, Python 3.13, Linux
Information
- The official example scripts
- My own modified scripts
Tasks
- An officially supported task in the
examplesfolder - My own task or dataset (give details below)
Reproduction
The unmerged forward of the OFT Conv2d layer rotates the input instead of the weight. OFTRotationModule.forward unfolds the input into kh x kw patches (stride 1, no padding), rotates every patch and folds the patches back into an image with F.fold, and the base conv then runs on that image. F.fold sums the overlapping patches, so for any kernel larger than 1x1 and any input larger than the kernel this is not a convolution with the rotated weight. It is not even the identity at initialization: with init_weights=True the rotation is the identity, but fold(unfold(x)) multiplies every interior pixel by kh * kw.
import copy
import torch
from torch import nn
from peft import OFTConfig, get_peft_model
class M(nn.Module):
def __init__(self, **kw):
super().__init__()
self.conv = nn.Conv2d(4, 6, **kw)
def forward(self, x):
return self.conv(x)
torch.manual_seed(0)
x = torch.randn(2, 4, 8, 8)
for kw in [dict(kernel_size=1), dict(kernel_size=3, padding=1), dict(kernel_size=5, padding=2)]:
base = M(**kw).eval()
expected = base(x)
for init_weights in [True, False]:
config = OFTConfig(r=2, oft_block_size=0, target_modules=["conv"], init_weights=init_weights)
model = get_peft_model(copy.deepcopy(base), config).eval()
with torch.no_grad():
unmerged = model(x)
model.merge_adapter()
merged = model(x)
print(
f"{kw} init_weights={init_weights}: "
f"max|unmerged - base| = {(unmerged - expected).abs().max():.2f}, "
f"max|merged - base| = {(merged - expected).abs().max():.2f}, "
f"max|unmerged - merged| = {(unmerged - merged).abs().max():.2f}"
)Output on main (same on 0.21.0):
{'kernel_size': 1} init_weights=True: max|unmerged - base| = 0.00, max|merged - base| = 0.00, max|unmerged - merged| = 0.00
{'kernel_size': 1} init_weights=False: max|unmerged - base| = 0.38, max|merged - base| = 0.38, max|unmerged - merged| = 0.00
{'kernel_size': 3, 'padding': 1} init_weights=True: max|unmerged - base| = 7.49, max|merged - base| = 0.00, max|unmerged - merged| = 7.49
{'kernel_size': 3, 'padding': 1} init_weights=False: max|unmerged - base| = 6.04, max|merged - base| = 1.61, max|unmerged - merged| = 5.68
{'kernel_size': 5, 'padding': 2} init_weights=True: max|unmerged - base| = 5.60, max|merged - base| = 0.00, max|unmerged - merged| = 5.60
{'kernel_size': 5, 'padding': 2} init_weights=False: max|unmerged - base| = 6.03, max|merged - base| = 2.14, max|unmerged - merged| = 5.58So a freshly created OFT adapter on a 3x3 conv changes the model output by more than the output magnitude (max|base| is 1.9 here), training optimizes a function that is not the rotated convolution, and the merged model (which is correct, merge rotates the weight) does not reproduce what was trained. The 1x1 case is fine because the patches do not overlap.
The test suite does not catch this because ModelConv2D and ModelConv2D2 in tests/test_custom_models.py feed a 3x3 image into a 3x3 kernel, which produces a single patch, and the diffusers tests only target linear layers.
Two smaller problems sit in the same code path: update_layer, merge and unmerge compute the filter dimension as in_features * kernel_size[0] * kernel_size[0], so a non-square kernel (Conv2d(4, 6, (3, 5))) fails with RuntimeError: shape '[6, 36]' is invalid for input of size 360 in forward and merge, and a grouped conv (groups=2) fails with the same kind of error because the weight only holds in_channels // groups.
Expected behavior
With init_weights=True the OFT model returns the same output as the base model, and the unmerged forward matches the merged model, for every kernel size, stride, padding, padding_mode and groups that nn.Conv2d accepts.
The fix I have is to rotate the weight instead of the input, the same way merge already does and the same way the BOFT Conv2d.forward works: weight_2d = base_layer.weight.view(out_features, -1), weight_2d = (oft_mat @ weight_2d.T).T for every active adapter, then base_layer._conv_forward(x, weight, bias), which applies the base layer's own stride, padding, dilation and padding_mode. Using weight[0].numel() as the filter dimension and view(out_features, -1) / view(orig_shape) in merge and unmerge removes the square-kernel assumption and makes groups > 1 work with the same code. OFTRotationModule.get_weight had to use self.weight instead of the projected no-grad copy in the COFT branch, otherwise the result carries no gradient (test_training_custom_models[Conv2d 3 OFT] fails with element 0 of tensors does not require grad). Applying the adapters to the weight in order also makes the unmerged forward agree with merge when two adapters are active, which for Linear is still not the case (forward computes x R_a R_b W^T, merge gives x R_b R_a W^T), but I left Linear alone here.
Checks I ran with the change:
- the reproduction above: every
max|unmerged - base|withinit_weights=Trueand everymax|unmerged - merged|becomes 0.00 - 56 configurations in float64 (kernel 3x3, 1x1, 3x5, stride (1, 2) with padding (1, 0),
groups=2,padding_mode="circular",bias=False, each withcofton/off,block_shareon/off,use_cayley_neumannon/off, two active adapters): worstmax|unmerged - merged|is 4.4e-16 - the cases where main is already right (3x3 kernel on a 3x3 input, 1x1 kernel on 8x8) agree with main to 3.6e-7 in float32 and the merged weights are bit-identical
- training on a 3x3 conv: the gradient reaches
oft_R, the base weight gets no gradient,mergeafter training still matches the unmerged output; float16 and bfloat16 forward on CPU match the merged model exactly pytest tests/test_custom_models.py -k "OFT and not BOFT": 1495 passed, 59 skipped;tests/test_initialization.py -k oft: 12 passed;tests/regression/test_state_dict.py --regression -k "oft and not boft": 6 passed, 2 skipped;ruff checkandruff format --checkclean- the new
tests/test_oft.py(identity init matches the base model; unmerged matches merged and unmerge restores the output, with and withoutcoft, over five conv configurations) fails 15/15 on main and passes with the change - the rotation now costs one
(d x d) @ (d x out)matmul per forward instead of unfolding the whole input, forward+backward on a 64->64 3x3 conv with a 64x64 input goes from 42 ms to 13 ms on my CPU
OFTRotationModule._unfold and _fold become unused with this change; I left them in place and would remove them in the PR if you prefer. I intend to provide the PR for this if you agree with the approach.
Patch
The complete change is below so that nobody has to redo it; I will open it as the PR as soon as this issue is approved.
git diff against main (2 files, +104 -29)diff --git a/src/peft/tuners/oft/layer.py b/src/peft/tuners/oft/layer.py
index 2bcc09b..d631716 100644
--- a/src/peft/tuners/oft/layer.py
+++ b/src/peft/tuners/oft/layer.py
@@ -290,15 +290,13 @@ class OFTRotationModule(nn.Module):
Returns:
`torch.Tensor`: The delta weight applied by this OFT layer.
"""
- weight = self.weight
-
if self.coft:
with torch.no_grad():
- weight = self._project_batch(weight, eps=self.eps)
- self.weight.copy_(weight)
+ self.weight.copy_(self._project_batch(self.weight, eps=self.eps))
+ # use the parameter itself, not the projected copy, so that the result stays differentiable
orth_rotate = self._cayley_batch(
- weight, self.block_size, self.use_cayley_neumann, self.num_cayley_neumann_terms
+ self.weight, self.block_size, self.use_cayley_neumann, self.num_cayley_neumann_terms
)
rank = self.r if not self.block_share else self.in_features // self.block_size
@@ -723,7 +721,8 @@ class Conv2d(nn.Module, OFTLayer):
if base_layer.dilation[0] > 1:
raise ValueError("Conv2d with dilation > 1 is not supported by OFT.")
- conv_filter_dim = self.in_features * base_layer.kernel_size[0] * base_layer.kernel_size[0]
+ # the rotation acts on the flattened filter of one output channel, i.e. on (in_channels // groups) * kh * kw
+ conv_filter_dim = base_layer.weight[0].numel()
if r == 0 and oft_block_size != 0:
if conv_filter_dim % oft_block_size != 0 or oft_block_size > conv_filter_dim:
@@ -797,16 +796,13 @@ class Conv2d(nn.Module, OFTLayer):
# quantized layers need dequantize -> modify -> re-quantize.
orig_weight = self.get_base_weight()
orig_dtype = orig_weight.dtype
+ orig_shape = orig_weight.shape
- orig_weight = orig_weight.view(
- self.out_features, self.in_features * base_layer.kernel_size[0] * base_layer.kernel_size[0]
- )
+ orig_weight = orig_weight.view(self.out_features, -1)
orig_weight = torch.transpose(orig_weight, 0, 1)
orig_weight = torch.mm(oft_mat, orig_weight.to(oft_mat.dtype))
orig_weight = torch.transpose(orig_weight, 0, 1)
- orig_weight = orig_weight.view(
- self.out_features, self.in_features, base_layer.kernel_size[0], base_layer.kernel_size[0]
- )
+ orig_weight = orig_weight.view(orig_shape)
if safe_merge:
# Note that safe_merge will be slower than the normal merge
@@ -821,9 +817,7 @@ class Conv2d(nn.Module, OFTLayer):
# Non-quantized unsafe merge: write the result directly into the
# existing weight storage to avoid the extra copy that
# set_base_weight would create via .contiguous().
- weight = base_layer.weight.data.view(
- self.out_features, self.in_features * base_layer.kernel_size[0] * base_layer.kernel_size[0]
- )
+ weight = base_layer.weight.data.view(self.out_features, -1)
result = torch.mm(oft_mat, weight.t().to(oft_mat.dtype))
weight.copy_(result.t())
@@ -849,19 +843,12 @@ class Conv2d(nn.Module, OFTLayer):
orig_weight = self.get_base_weight()
orig_dtype = orig_weight.dtype
- orig_weight = orig_weight.view(
- self.out_features,
- self.in_features * base_layer.kernel_size[0] * base_layer.kernel_size[0],
- )
+ orig_shape = orig_weight.shape
+ orig_weight = orig_weight.view(self.out_features, -1)
orig_weight = torch.transpose(orig_weight, 0, 1)
orig_weight = torch.mm(torch.linalg.inv(oft_mat).to(previous_dtype), orig_weight.to(previous_dtype))
orig_weight = torch.transpose(orig_weight, 0, 1)
- orig_weight = orig_weight.view(
- self.out_features,
- self.in_features,
- base_layer.kernel_size[0],
- base_layer.kernel_size[0],
- )
+ orig_weight = orig_weight.view(orig_shape)
self.set_base_weight(orig_weight.to(orig_dtype))
@@ -903,15 +890,23 @@ class Conv2d(nn.Module, OFTLayer):
elif self.merged:
result = self.base_layer(x, *args, **kwargs)
else:
+ # Rotate the weight, not the input: rotating unfolded input patches and folding them back is only
+ # equivalent to a convolution with the rotated weight when the patches do not overlap. Applying the
+ # adapters to the weight in order also matches what merge() does.
+ base_layer = self.get_base_layer()
+ weight = base_layer.weight
+ weight_2d = weight.view(self.out_features, -1)
for active_adapter in self.active_adapters:
if active_adapter not in self.oft_R.keys():
continue
- oft_R = self.oft_R[active_adapter]
- x = self._cast_input_dtype(x, oft_R.weight.dtype)
- x = oft_R(x)
+ oft_mat = self.oft_R[active_adapter].get_weight()
+ weight_2d = torch.mm(oft_mat, weight_2d.t().to(oft_mat.dtype)).t()
+ weight = weight_2d.view(weight.shape).to(weight.dtype)
- result = self.base_layer(x.to(previous_dtype), *args, **kwargs)
+ x = self._cast_input_dtype(x, weight.dtype)
+ bias = self._cast_input_dtype(base_layer.bias, weight.dtype)
+ result = base_layer._conv_forward(x, weight, bias)
result = result.to(previous_dtype)
return result
diff --git a/tests/test_oft.py b/tests/test_oft.py
new file mode 100644
index 0000000..79a129b
--- /dev/null
+++ b/tests/test_oft.py
@@ -0,0 +1,80 @@
+# Copyright 2026-present the HuggingFace Inc. team.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import copy
+
+import pytest
+import torch
+from torch import nn
+
+from peft import OFTConfig, get_peft_model
+from peft.utils import infer_device
+
+
+class ConvModel(nn.Module):
+ def __init__(self, **conv_kwargs):
+ super().__init__()
+ self.conv2d = nn.Conv2d(4, 6, **conv_kwargs)
+
+ def forward(self, X):
+ return self.conv2d(X)
+
+
+# inputs larger than the kernel, so that the unfolded patches overlap
+CONV_KWARGS = [
+ {"kernel_size": 3, "padding": 1},
+ {"kernel_size": (3, 5), "padding": (1, 2)},
+ {"kernel_size": 3, "stride": (1, 2), "padding": (1, 0)},
+ {"kernel_size": 3, "padding": 1, "groups": 2},
+ {"kernel_size": 3, "padding": 1, "padding_mode": "reflect"},
+]
+
+
+class TestOft:
+ device = infer_device()
+
+ def get_model_and_input(self, **conv_kwargs):
+ torch.manual_seed(0)
+ model = ConvModel(**conv_kwargs).to(self.device).eval()
+ X = torch.randn(2, 4, 8, 8, device=self.device)
+ return model, X
+
+ @pytest.mark.parametrize("conv_kwargs", CONV_KWARGS)
+ def test_oft_conv2d_identity_init_matches_base_model(self, conv_kwargs):
+ model, X = self.get_model_and_input(**conv_kwargs)
+ output_base = model(X)
+
+ config = OFTConfig(r=2, oft_block_size=0, target_modules=["conv2d"])
+ peft_model = get_peft_model(copy.deepcopy(model), config).eval()
+ output_peft = peft_model(X)
+
+ assert output_peft.shape == output_base.shape
+ assert torch.allclose(output_peft, output_base, atol=1e-6, rtol=1e-6)
+
+ @pytest.mark.parametrize("conv_kwargs", CONV_KWARGS)
+ @pytest.mark.parametrize("coft", [False, True])
+ def test_oft_conv2d_forward_matches_merged_model(self, conv_kwargs, coft):
+ model, X = self.get_model_and_input(**conv_kwargs)
+
+ config = OFTConfig(r=2, oft_block_size=0, target_modules=["conv2d"], init_weights=False, coft=coft)
+ peft_model = get_peft_model(model, config).eval()
+ output_unmerged = peft_model(X)
+
+ peft_model.merge_adapter()
+ output_merged = peft_model(X)
+ assert torch.allclose(output_unmerged, output_merged, atol=1e-6, rtol=1e-6)
+
+ peft_model.unmerge_adapter()
+ output_unmerged_again = peft_model(X)
+ assert torch.allclose(output_unmerged, output_unmerged_again, atol=1e-5, rtol=1e-5)AI disclosure: I used an AI coding agent to find this and to prepare the fix and the tests. I have read the change and the tests myself and I will answer review comments personally.
Source: huggingface/peft