OFT module_dropout has had no effect since #2575: the MultiplicativeDropoutLayer is created but never called
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
OFTConfig.module_dropout is documented as "the multiplicative dropout probability, by setting OFT blocks to identity during training", and update_layer in oft/layer.py still builds a MultiplicativeDropoutLayer(p=module_dropout) per adapter and stores it in self.oft_dropout. Nothing reads it any more: self.oft_dropout[...] is not referenced anywhere in the file, so the forward pass is the same with module_dropout=0.0 and module_dropout=0.5.
import torch
from torch import nn
import peft
from peft import OFTConfig, get_peft_model
class M(nn.Module):
def __init__(self):
super().__init__()
self.lin = nn.Linear(16, 12)
def forward(self, x):
return self.lin(x)
torch.manual_seed(0)
x = torch.randn(3, 16)
config = OFTConfig(r=4, oft_block_size=0, target_modules=["lin"], init_weights=False, module_dropout=0.5)
model = get_peft_model(M(), config)
model.train()
with torch.no_grad():
outputs = [model(x) for _ in range(10)]
diffs = [(outputs[0] - o).abs().max().item() for o in outputs[1:]]
print(f"peft {peft.__version__}: max difference between train-mode forward passes: {max(diffs):.4f}")peft 0.21.1.dev0: max difference between train-mode forward passes: 0.0000
peft 0.21.0: max difference between train-mode forward passes: 0.0000
peft 0.15.0: max difference between train-mode forward passes: 0.2635In 0.15.0 both Linear.forward and Conv2d.forward did orth_rotate = self._cayley_batch(oft_r) followed by orth_rotate = dropout(orth_rotate). #2575 moved the Cayley transform into OFTRotationModule and the dropout(...) call did not come along, so since 0.16.0 the setting is silently ignored. The Embedding layer never created dropout layers, I left it alone.
Expected behavior
With module_dropout > 0 and the model in train mode, a fraction of the rotation blocks is replaced by the identity in every forward pass, as before #2575 and as the config docstring says. In eval mode and when merging, no dropout is applied.
The fix I have passes the dropout module from the OFT layer into the rotation module: OFTRotationModule.forward(x, dropout=None) and OFTRotationModule.get_weight(dropout=None) apply it to orth_rotate right after the Cayley transform when it is given. Linear.forward calls oft_R(x, dropout=self.oft_dropout[active_adapter]), Conv2d.forward calls get_weight(dropout=self.oft_dropout[active_adapter]), and merge keeps calling get_weight() without it, so test_merge_layers_is_deterministic_in_train_mode (#3586) keeps holding. MultiplicativeDropoutLayer already skips block_share=True (a single shared block) and eval mode itself.
This change is stacked on top of the Conv2d.forward rewrite from #3829, because the conv forward there is the place that has to receive the dropout as well; the diff below is against that branch (fix/oft-conv2d-forward), not against main. If you prefer, I can fold both into the one PR.
Checks I ran with the change:
- the reproduction above prints 0.3640 with the change (0.0000 on main), and a
Conv2d(4, 6, 3, padding=1)target behaves the same way - in eval mode two forward passes are identical and equal to the merged model (0.0 for Conv2d, 2.4e-7 for Linear in float32)
pytest tests/test_custom_models.py -k "OFT and not BOFT": 1495 passed, 59 skipped, including the four test cases that setmodule_dropout=0.1andtest_merge_layers_is_deterministic_in_train_mode;tests/test_initialization.py -k oft: 12 passed;ruff checkandruff format --checkclean- the new
test_oft_module_dropout_is_applied_in_train_mode(Linear and Conv2d: ten train-mode forward passes are not all equal, eval mode is deterministic and matches the merged model) fails on main and on the #3829 branch, and passes with this change
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; it applies on top of the #3829 branch.
git diff against fix/oft-conv2d-forward (2 files, +52 -4)diff --git a/src/peft/tuners/oft/layer.py b/src/peft/tuners/oft/layer.py
index d631716..2bb95fc 100644
--- a/src/peft/tuners/oft/layer.py
+++ b/src/peft/tuners/oft/layer.py
@@ -242,7 +242,7 @@ class OFTRotationModule(nn.Module):
return x_folded
- def forward(self, x):
+ def forward(self, x, dropout: Optional[nn.Module] = None):
# This module doesn't need to implement the orthogonal transform
# It's primarily a container for the parameter
# The actual transformation logic stays in your OFTLayer
@@ -260,6 +260,8 @@ class OFTRotationModule(nn.Module):
orth_rotate = self._cayley_batch(
self.weight, self.block_size, self.use_cayley_neumann, self.num_cayley_neumann_terms
)
+ if dropout is not None:
+ orth_rotate = dropout(orth_rotate)
# Unfold the input for Conv2d layer
if len(orig_shape) == 4:
@@ -283,10 +285,14 @@ class OFTRotationModule(nn.Module):
return x_rotated.to(required_dtype)
- def get_weight(self):
+ def get_weight(self, dropout: Optional[nn.Module] = None):
"""
Compute the delta weight for the current layer.
+ Args:
+ dropout (`nn.Module`, *optional*):
+ Multiplicative dropout to apply to the rotation blocks; pass it from the forward pass, not when merging.
+
Returns:
`torch.Tensor`: The delta weight applied by this OFT layer.
"""
@@ -298,6 +304,8 @@ class OFTRotationModule(nn.Module):
orth_rotate = self._cayley_batch(
self.weight, self.block_size, self.use_cayley_neumann, self.num_cayley_neumann_terms
)
+ if dropout is not None:
+ orth_rotate = dropout(orth_rotate)
rank = self.r if not self.block_share else self.in_features // self.block_size
return self._block_diagonal(orth_rotate, rank)
@@ -649,7 +657,7 @@ class Linear(nn.Module, OFTLayer):
oft_R = self.oft_R[active_adapter]
x = self._cast_input_dtype(x, oft_R.weight.dtype)
- x = oft_R(x)
+ x = oft_R(x, dropout=self.oft_dropout[active_adapter])
result = self.base_layer(x.to(previous_dtype), *args, **kwargs)
@@ -900,7 +908,7 @@ class Conv2d(nn.Module, OFTLayer):
if active_adapter not in self.oft_R.keys():
continue
- oft_mat = self.oft_R[active_adapter].get_weight()
+ oft_mat = self.oft_R[active_adapter].get_weight(dropout=self.oft_dropout[active_adapter])
weight_2d = torch.mm(oft_mat, weight_2d.t().to(oft_mat.dtype)).t()
weight = weight_2d.view(weight.shape).to(weight.dtype)
diff --git a/tests/test_oft.py b/tests/test_oft.py
index 79a129b..c0c0864 100644
--- a/tests/test_oft.py
+++ b/tests/test_oft.py
@@ -31,6 +31,15 @@ class ConvModel(nn.Module):
return self.conv2d(X)
+class LinearModel(nn.Module):
+ def __init__(self):
+ super().__init__()
+ self.lin0 = nn.Linear(16, 12)
+
+ def forward(self, X):
+ return self.lin0(X)
+
+
# inputs larger than the kernel, so that the unfolded patches overlap
CONV_KWARGS = [
{"kernel_size": 3, "padding": 1},
@@ -78,3 +87,34 @@ class TestOft:
peft_model.unmerge_adapter()
output_unmerged_again = peft_model(X)
assert torch.allclose(output_unmerged, output_unmerged_again, atol=1e-5, rtol=1e-5)
+
+ @pytest.mark.parametrize("model_cls, target_module", [(LinearModel, "lin0"), (ConvModel, "conv2d")])
+ def test_oft_module_dropout_is_applied_in_train_mode(self, model_cls, target_module):
+ # module_dropout replaces a fraction of the rotation blocks by the identity during training, it must not be a
+ # no-op in train mode and it must not leak into eval mode or into merging
+ torch.manual_seed(0)
+ model = model_cls(kernel_size=3, padding=1) if model_cls is ConvModel else model_cls()
+ model = model.to(self.device)
+ X = (
+ torch.randn(2, 4, 8, 8, device=self.device)
+ if model_cls is ConvModel
+ else torch.randn(3, 16, device=self.device)
+ )
+
+ config = OFTConfig(
+ r=4, oft_block_size=0, target_modules=[target_module], init_weights=False, module_dropout=0.5
+ )
+ peft_model = get_peft_model(model, config)
+
+ peft_model.train()
+ with torch.no_grad():
+ outputs = [peft_model(X) for _ in range(10)]
+ assert not all(torch.allclose(outputs[0], output) for output in outputs[1:])
+
+ peft_model.eval()
+ with torch.no_grad():
+ output_eval = peft_model(X)
+ assert torch.allclose(output_eval, peft_model(X))
+ peft_model.merge_adapter()
+ output_merged = peft_model(X)
+ assert torch.allclose(output_eval, output_merged, atol=1e-6, rtol=1e-6)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