micro_sam.models.peft
Shared modules for parameter efficient finetuning (PEFT) of SAM and SAM2.
1"""Shared modules for parameter efficient finetuning (PEFT) of SAM and SAM2.""" 2import math 3from typing import Callable, List, Optional, Union 4 5try: 6 import bitsandbytes as bnb 7 HAVE_BITSANDBYTES = True 8except ImportError: 9 HAVE_BITSANDBYTES = False 10 11import torch 12import torch.nn as nn 13 14 15def quantize_linear_layers(image_encoder: nn.Module): 16 """Replace each linear layer with a 4-bit bitsandbytes layer. 17 18 Args: 19 image_encoder: The image encoder module whose linear layers are quantized in place. 20 """ 21 if not HAVE_BITSANDBYTES: 22 raise ModuleNotFoundError("'bitsandbytes' is not available. Install it with 'pip install bitsandbytes'.") 23 24 for name, module in image_encoder.named_modules(): 25 if isinstance(module, torch.nn.Linear): 26 *parent_path, layer_name = name.split(".") 27 parent_module = image_encoder 28 29 for sub_module in parent_path: 30 parent_module = getattr(parent_module, sub_module) 31 32 linear_q = bnb.nn.Linear4bit( 33 module.in_features, 34 module.out_features, 35 bias=False if module.bias is None else True, 36 ) 37 linear_q.weight = bnb.nn.Params4bit(data=module.weight, requires_grad=False) 38 if module.bias is not None: 39 linear_q.bias = torch.nn.Parameter(module.bias) 40 41 setattr(parent_module, layer_name, linear_q) 42 43 44class AttentionLoRA(nn.Module): 45 """Low-rank adaptation on a fused qkv projection. 46 47 This module supports the symmetric SAM projection and the asymmetric SAM2 Hiera projection. 48 49 Args: 50 rank: The rank of the decomposition matrices for updating weights in each attention layer. 51 block: The chosen qkv projection layer for implementing LoRA. 52 update_matrices: The matrices to update in the attention layer. Choose "q", "k", or "v". 53 """ 54 def __init__(self, rank: int, block: nn.Module, update_matrices: List[str] = ["q", "v"]): 55 super().__init__() 56 self.qkv_proj = block 57 self.in_dim = block.in_features 58 self.out_dim = block.out_features // 3 59 self.alpha = 1 # The experiments gave the best results with alpha set to 1. 60 self.rank = rank 61 62 # By default, we follow LoRA's recommended setup, i.e. update the "q" and "v" matrices. 63 if "q" in update_matrices: 64 self.w_a_linear_q = nn.Linear(self.in_dim, self.rank, bias=False) 65 self.w_b_linear_q = nn.Linear(self.rank, self.out_dim, bias=False) 66 67 if "v" in update_matrices: 68 self.w_a_linear_v = nn.Linear(self.in_dim, self.rank, bias=False) 69 self.w_b_linear_v = nn.Linear(self.rank, self.out_dim, bias=False) 70 71 if "k" in update_matrices: 72 self.w_a_linear_k = nn.Linear(self.in_dim, self.rank, bias=False) 73 self.w_b_linear_k = nn.Linear(self.rank, self.out_dim, bias=False) 74 75 self.reset_parameters() 76 77 def reset_parameters(self): 78 if hasattr(self, "w_a_linear_q"): 79 nn.init.kaiming_uniform_(self.w_a_linear_q.weight, a=math.sqrt(5)) 80 nn.init.zeros_(self.w_b_linear_q.weight) 81 82 if hasattr(self, "w_a_linear_v"): 83 nn.init.kaiming_uniform_(self.w_a_linear_v.weight, a=math.sqrt(5)) 84 nn.init.zeros_(self.w_b_linear_v.weight) 85 86 if hasattr(self, "w_a_linear_k"): 87 nn.init.kaiming_uniform_(self.w_a_linear_k.weight, a=math.sqrt(5)) 88 nn.init.zeros_(self.w_b_linear_k.weight) 89 90 def forward(self, x): 91 qkv = self.qkv_proj(x) # (..., 3 * out_dim) 92 d = self.out_dim 93 94 new_q = self.alpha * self.w_b_linear_q(self.w_a_linear_q(x)) if hasattr(self, "w_a_linear_q") else 0 95 new_v = self.alpha * self.w_b_linear_v(self.w_a_linear_v(x)) if hasattr(self, "w_a_linear_v") else 0 96 new_k = self.alpha * self.w_b_linear_k(self.w_a_linear_k(x)) if hasattr(self, "w_a_linear_k") else 0 97 qkv = torch.cat( 98 [ 99 qkv[..., :d] + new_q, 100 qkv[..., d:2 * d] + new_k, 101 qkv[..., 2 * d:] + new_v, 102 ], 103 dim=-1, 104 ) 105 106 return qkv 107 108 109class MLPLoRA(nn.Module): 110 """Low-rank adaptation on a two-layer feed forward block. 111 112 The `get_layers` function supports the different MLP layouts in SAM and SAM2. 113 114 Args: 115 rank: The rank of the decomposition matrices for updating weights in each feed forward layer. 116 mlp_layer: The chosen MLP layer for implementing LoRA. 117 get_layers: Callable mapping `mlp_layer` to the tuple `(lin1, lin2, activation)`. 118 """ 119 def __init__(self, rank: int, mlp_layer: nn.Module, get_layers: Callable): 120 super().__init__() 121 self.mlp_layer = mlp_layer 122 self.get_layers = get_layers 123 self.rank = rank 124 lin1, lin2, _ = get_layers(mlp_layer) 125 self.w_a_linear_1 = nn.Linear(lin1.in_features, rank, bias=False) 126 self.w_b_linear_1 = nn.Linear(rank, lin1.out_features, bias=False) 127 self.w_a_linear_2 = nn.Linear(lin2.in_features, rank, bias=False) 128 self.w_b_linear_2 = nn.Linear(rank, lin2.out_features, bias=False) 129 130 self.reset_parameters() 131 132 def reset_parameters(self): 133 nn.init.kaiming_uniform_(self.w_a_linear_1.weight, a=math.sqrt(5)) 134 nn.init.kaiming_uniform_(self.w_a_linear_2.weight, a=math.sqrt(5)) 135 nn.init.zeros_(self.w_b_linear_1.weight) 136 nn.init.zeros_(self.w_b_linear_2.weight) 137 138 def forward(self, x): 139 lin1, lin2, activation = self.get_layers(self.mlp_layer) 140 x = lin1(x) + self.w_b_linear_1(self.w_a_linear_1(x)) 141 x = activation(x) 142 x = lin2(x) + self.w_b_linear_2(self.w_a_linear_2(x)) 143 return x 144 145 146class ScaleShiftLayer(nn.Module): 147 """Wraps a layer to apply learnable per-channel scale and shift to its output (used by SSF).""" 148 def __init__(self, layer, dim): 149 super().__init__() 150 self.layer = layer 151 self.scale = nn.Parameter(torch.normal(mean=1.0, std=0.2, size=(dim,))) 152 self.shift = nn.Parameter(torch.normal(mean=0.0, std=0.2, size=(dim,))) 153 154 def forward(self, x): 155 x = self.layer(x) 156 assert self.scale.shape == self.shift.shape 157 if x.shape[-1] == self.scale.shape[0]: 158 return x * self.scale + self.shift 159 elif x.shape[1] == self.scale.shape[0]: 160 return x * self.scale.view(1, -1, 1, 1) + self.shift.view(1, -1, 1, 1) 161 else: 162 raise ValueError( 163 f"The input shape {tuple(x.shape)} does not match the scale shape {tuple(self.scale.shape)}." 164 ) 165 166 167class SelectiveSurgery(nn.Module): 168 """Allow gradient updates for selected parameters.""" 169 def __init__(self, block: nn.Module): 170 super().__init__() 171 self.block = block 172 173 def allow_gradient_update_for_parameters( 174 self, 175 prefix: Optional[List[str]] = None, 176 suffix: Optional[List[str]] = None, 177 infix: Optional[List[str]] = None, 178 ): 179 """Allow gradient updates for parameter names that match the filters. 180 181 Args: 182 prefix: Matches the part of parameter name in front. 183 suffix: Matches the part of parameter name at the end. 184 infix: Matches parts of parameter name occurring in between. 185 """ 186 for k, v in self.block.named_parameters(): 187 if prefix is not None and k.startswith(tuple(prefix)): 188 v.requires_grad = True 189 190 if suffix is not None and k.endswith(tuple(suffix)): 191 v.requires_grad = True 192 193 if infix is not None: 194 for per_infix in infix: 195 if k.find(per_infix) != -1: 196 v.requires_grad = True 197 198 def forward(self, x): 199 return x 200 201 202class AttentionSurgery(SelectiveSurgery): 203 """Allow gradient updates for parameters in attention layers.""" 204 205 def __init__(self, block: nn.Module): 206 super().__init__(block=block) 207 self.allow_gradient_update_for_parameters(prefix=["attn"]) 208 209 210class BiasSurgery(SelectiveSurgery): 211 """Allow gradient updates for bias parameters.""" 212 213 def __init__(self, block: nn.Module): 214 super().__init__(block=block) 215 self.allow_gradient_update_for_parameters(suffix=["bias"]) 216 217 218class LayerNormSurgery(SelectiveSurgery): 219 """Allow gradient updates for parameters in normalization layers.""" 220 221 def __init__(self, block: nn.Module): 222 super().__init__(block=block) 223 self.allow_gradient_update_for_parameters(infix=["norm1", "norm2"]) 224 225 226class ClassicalSurgery(SelectiveSurgery): 227 """Allow gradient updates for all parameters in selected blocks.""" 228 229 def __init__(self, block: nn.Module): 230 super().__init__(block=block) 231 self.block = block 232 233 for k, v in self.block.named_parameters(): 234 v.requires_grad = True 235 236 def forward(self, x): 237 return x 238 239 240class FacTSurgery(nn.Module): 241 """Apply factorized attention to attention layers. 242 243 Based on https://github.com/cchen-cc/MA-SAM/blob/main/MA-SAM/sam_fact_tt_image_encoder.py. 244 This module supports the symmetric SAM projection and the asymmetric SAM2 Hiera projection. 245 246 Args: 247 rank: The rank of the decomposition matrices for updating weights in each attention layer. 248 block: The chosen attention block for implementing fact. 249 dropout: The dropout rate for the factorized attention. 250 """ 251 def __init__(self, rank: int, block: nn.Module, dropout: Optional[float] = 0.1): 252 super().__init__() 253 self.qkv_proj = block.attn.qkv 254 self.in_dim = self.qkv_proj.in_features 255 self.out_dim = self.qkv_proj.out_features // 3 256 257 self.q_FacTs = nn.Linear(rank, rank, bias=False) 258 self.v_FacTs = nn.Linear(rank, rank, bias=False) 259 260 self.dropout = dropout 261 if self.dropout is not None: 262 self.dp_q = nn.Dropout(self.dropout) 263 self.dp_v = nn.Dropout(self.dropout) 264 265 self.FacTu = nn.Linear(self.in_dim, rank, bias=False) 266 self.FacTv = nn.Linear(rank, self.out_dim, bias=False) 267 268 block.attn.qkv = self 269 270 def forward(self, x): 271 qkv = self.qkv_proj(x) 272 d = self.out_dim 273 274 new_q = self.q_FacTs(self.FacTu(x)) 275 new_v = self.v_FacTs(self.FacTu(x)) 276 277 if self.dropout is not None: 278 new_q = self.dp_q(new_q) 279 new_v = self.dp_v(new_v) 280 281 new_q = self.FacTv(new_q) 282 new_v = self.FacTv(new_v) 283 284 # The learning rate controls the scale, so the scaling factor is 1. 285 qkv = torch.cat( 286 [ 287 qkv[..., :d] + new_q, 288 qkv[..., d:2 * d], 289 qkv[..., 2 * d:] + new_v, 290 ], 291 dim=-1, 292 ) 293 294 return qkv 295 296 297class AdaptFormer(nn.Module): 298 """Adds an AdaptFormer module in place of the MLP layers. 299 300 Args: 301 rank: The rank is not used in this class but kept here for consistency. 302 block: The chosen encoder block for implementing AdaptFormer. 303 alpha: The value that scales the adapter path. Pass a number or `"learnable_scalar"`. 304 dropout: The dropout rate for the dropout layer between the down and up projection layer. 305 projection_size: The size of the projection layer. 306 """ 307 def __init__( 308 self, 309 rank: int, 310 block: nn.Module, 311 alpha: Optional[Union[str, float]] = "learnable_scalar", # Preliminary experiments support this value. 312 dropout: Optional[float] = None, # Preliminary experiments show no clear benefit. 313 projection_size: int = 64, # Preliminary experiments support this value. 314 ): 315 super().__init__() 316 317 self.mlp_proj = block.mlp 318 # SAM and SAM2 use different attributes for the first MLP layer. 319 self.n_embd = block.mlp.lin1.in_features if hasattr(block.mlp, "lin1") else block.mlp.layers[0].in_features 320 321 if alpha == 'learnable_scalar': 322 self.alpha = nn.Parameter(torch.ones(1)) 323 else: 324 self.alpha = alpha 325 326 self.projection_size = projection_size 327 self.dropout = dropout 328 329 self.down_proj = nn.Linear(self.n_embd, self.projection_size) 330 self.non_linear_func = nn.ReLU() 331 self.up_proj = nn.Linear(self.projection_size, self.n_embd) 332 333 block.mlp = self 334 335 if self.dropout is not None: 336 self.dropout_layer = nn.Dropout(self.dropout) 337 338 nn.init.kaiming_uniform_(self.down_proj.weight, a=math.sqrt(5)) 339 nn.init.zeros_(self.up_proj.weight) 340 nn.init.zeros_(self.down_proj.bias) 341 nn.init.zeros_(self.up_proj.bias) 342 343 def forward(self, x): 344 mlp_output = self.mlp_proj(x) 345 346 down = self.down_proj(x) 347 down = self.non_linear_func(down) 348 349 if self.dropout is not None: 350 down = self.dropout_layer(down) 351 352 up = self.up_proj(down) 353 up = up * self.alpha 354 output = up + mlp_output 355 356 return output 357 358 359def serialize_peft_kwargs(peft_kwargs: Optional[dict]) -> Optional[dict]: 360 """Convert `peft_kwargs` to a dictionary that a checkpoint can store. 361 362 Args: 363 peft_kwargs: The PEFT keyword arguments, or None. 364 365 Returns: 366 The serialized config, or None if `peft_kwargs` is empty. 367 """ 368 if not peft_kwargs: 369 return None 370 serialized = dict(peft_kwargs) 371 module = serialized.get("peft_module") 372 if module is not None and not isinstance(module, str): 373 serialized["peft_module"] = module.__name__ 374 return serialized 375 376 377def deserialize_peft_kwargs(config: Optional[dict], module_registry: dict) -> Optional[dict]: 378 """Build `peft_kwargs` from a saved configuration. 379 380 Args: 381 config: The serialized config (as produced by `serialize_peft_kwargs`), or None. 382 module_registry: The mapping from each PEFT module name to its class. 383 384 Returns: 385 The deserialized `peft_kwargs`, or None if `config` is empty. 386 """ 387 if not config: 388 return None 389 deserialized = dict(config) 390 module = deserialized.get("peft_module") 391 if isinstance(module, str): 392 if module not in module_registry: 393 raise ValueError(f"Unknown PEFT module '{module}'. Known modules: {sorted(module_registry)}") 394 deserialized["peft_module"] = module_registry[module] 395 return deserialized
16def quantize_linear_layers(image_encoder: nn.Module): 17 """Replace each linear layer with a 4-bit bitsandbytes layer. 18 19 Args: 20 image_encoder: The image encoder module whose linear layers are quantized in place. 21 """ 22 if not HAVE_BITSANDBYTES: 23 raise ModuleNotFoundError("'bitsandbytes' is not available. Install it with 'pip install bitsandbytes'.") 24 25 for name, module in image_encoder.named_modules(): 26 if isinstance(module, torch.nn.Linear): 27 *parent_path, layer_name = name.split(".") 28 parent_module = image_encoder 29 30 for sub_module in parent_path: 31 parent_module = getattr(parent_module, sub_module) 32 33 linear_q = bnb.nn.Linear4bit( 34 module.in_features, 35 module.out_features, 36 bias=False if module.bias is None else True, 37 ) 38 linear_q.weight = bnb.nn.Params4bit(data=module.weight, requires_grad=False) 39 if module.bias is not None: 40 linear_q.bias = torch.nn.Parameter(module.bias) 41 42 setattr(parent_module, layer_name, linear_q)
Replace each linear layer with a 4-bit bitsandbytes layer.
Arguments:
- image_encoder: The image encoder module whose linear layers are quantized in place.
45class AttentionLoRA(nn.Module): 46 """Low-rank adaptation on a fused qkv projection. 47 48 This module supports the symmetric SAM projection and the asymmetric SAM2 Hiera projection. 49 50 Args: 51 rank: The rank of the decomposition matrices for updating weights in each attention layer. 52 block: The chosen qkv projection layer for implementing LoRA. 53 update_matrices: The matrices to update in the attention layer. Choose "q", "k", or "v". 54 """ 55 def __init__(self, rank: int, block: nn.Module, update_matrices: List[str] = ["q", "v"]): 56 super().__init__() 57 self.qkv_proj = block 58 self.in_dim = block.in_features 59 self.out_dim = block.out_features // 3 60 self.alpha = 1 # The experiments gave the best results with alpha set to 1. 61 self.rank = rank 62 63 # By default, we follow LoRA's recommended setup, i.e. update the "q" and "v" matrices. 64 if "q" in update_matrices: 65 self.w_a_linear_q = nn.Linear(self.in_dim, self.rank, bias=False) 66 self.w_b_linear_q = nn.Linear(self.rank, self.out_dim, bias=False) 67 68 if "v" in update_matrices: 69 self.w_a_linear_v = nn.Linear(self.in_dim, self.rank, bias=False) 70 self.w_b_linear_v = nn.Linear(self.rank, self.out_dim, bias=False) 71 72 if "k" in update_matrices: 73 self.w_a_linear_k = nn.Linear(self.in_dim, self.rank, bias=False) 74 self.w_b_linear_k = nn.Linear(self.rank, self.out_dim, bias=False) 75 76 self.reset_parameters() 77 78 def reset_parameters(self): 79 if hasattr(self, "w_a_linear_q"): 80 nn.init.kaiming_uniform_(self.w_a_linear_q.weight, a=math.sqrt(5)) 81 nn.init.zeros_(self.w_b_linear_q.weight) 82 83 if hasattr(self, "w_a_linear_v"): 84 nn.init.kaiming_uniform_(self.w_a_linear_v.weight, a=math.sqrt(5)) 85 nn.init.zeros_(self.w_b_linear_v.weight) 86 87 if hasattr(self, "w_a_linear_k"): 88 nn.init.kaiming_uniform_(self.w_a_linear_k.weight, a=math.sqrt(5)) 89 nn.init.zeros_(self.w_b_linear_k.weight) 90 91 def forward(self, x): 92 qkv = self.qkv_proj(x) # (..., 3 * out_dim) 93 d = self.out_dim 94 95 new_q = self.alpha * self.w_b_linear_q(self.w_a_linear_q(x)) if hasattr(self, "w_a_linear_q") else 0 96 new_v = self.alpha * self.w_b_linear_v(self.w_a_linear_v(x)) if hasattr(self, "w_a_linear_v") else 0 97 new_k = self.alpha * self.w_b_linear_k(self.w_a_linear_k(x)) if hasattr(self, "w_a_linear_k") else 0 98 qkv = torch.cat( 99 [ 100 qkv[..., :d] + new_q, 101 qkv[..., d:2 * d] + new_k, 102 qkv[..., 2 * d:] + new_v, 103 ], 104 dim=-1, 105 ) 106 107 return qkv
Low-rank adaptation on a fused qkv projection.
This module supports the symmetric SAM projection and the asymmetric SAM2 Hiera projection.
Arguments:
- rank: The rank of the decomposition matrices for updating weights in each attention layer.
- block: The chosen qkv projection layer for implementing LoRA.
- update_matrices: The matrices to update in the attention layer. Choose "q", "k", or "v".
55 def __init__(self, rank: int, block: nn.Module, update_matrices: List[str] = ["q", "v"]): 56 super().__init__() 57 self.qkv_proj = block 58 self.in_dim = block.in_features 59 self.out_dim = block.out_features // 3 60 self.alpha = 1 # The experiments gave the best results with alpha set to 1. 61 self.rank = rank 62 63 # By default, we follow LoRA's recommended setup, i.e. update the "q" and "v" matrices. 64 if "q" in update_matrices: 65 self.w_a_linear_q = nn.Linear(self.in_dim, self.rank, bias=False) 66 self.w_b_linear_q = nn.Linear(self.rank, self.out_dim, bias=False) 67 68 if "v" in update_matrices: 69 self.w_a_linear_v = nn.Linear(self.in_dim, self.rank, bias=False) 70 self.w_b_linear_v = nn.Linear(self.rank, self.out_dim, bias=False) 71 72 if "k" in update_matrices: 73 self.w_a_linear_k = nn.Linear(self.in_dim, self.rank, bias=False) 74 self.w_b_linear_k = nn.Linear(self.rank, self.out_dim, bias=False) 75 76 self.reset_parameters()
Initialize internal Module state, shared by both nn.Module and ScriptModule.
78 def reset_parameters(self): 79 if hasattr(self, "w_a_linear_q"): 80 nn.init.kaiming_uniform_(self.w_a_linear_q.weight, a=math.sqrt(5)) 81 nn.init.zeros_(self.w_b_linear_q.weight) 82 83 if hasattr(self, "w_a_linear_v"): 84 nn.init.kaiming_uniform_(self.w_a_linear_v.weight, a=math.sqrt(5)) 85 nn.init.zeros_(self.w_b_linear_v.weight) 86 87 if hasattr(self, "w_a_linear_k"): 88 nn.init.kaiming_uniform_(self.w_a_linear_k.weight, a=math.sqrt(5)) 89 nn.init.zeros_(self.w_b_linear_k.weight)
91 def forward(self, x): 92 qkv = self.qkv_proj(x) # (..., 3 * out_dim) 93 d = self.out_dim 94 95 new_q = self.alpha * self.w_b_linear_q(self.w_a_linear_q(x)) if hasattr(self, "w_a_linear_q") else 0 96 new_v = self.alpha * self.w_b_linear_v(self.w_a_linear_v(x)) if hasattr(self, "w_a_linear_v") else 0 97 new_k = self.alpha * self.w_b_linear_k(self.w_a_linear_k(x)) if hasattr(self, "w_a_linear_k") else 0 98 qkv = torch.cat( 99 [ 100 qkv[..., :d] + new_q, 101 qkv[..., d:2 * d] + new_k, 102 qkv[..., 2 * d:] + new_v, 103 ], 104 dim=-1, 105 ) 106 107 return qkv
Define the computation performed at every call.
Should be overridden by all subclasses.
Although the recipe for forward pass needs to be defined within
this function, one should call the Module instance afterwards
instead of this since the former takes care of running the
registered hooks while the latter silently ignores them.
110class MLPLoRA(nn.Module): 111 """Low-rank adaptation on a two-layer feed forward block. 112 113 The `get_layers` function supports the different MLP layouts in SAM and SAM2. 114 115 Args: 116 rank: The rank of the decomposition matrices for updating weights in each feed forward layer. 117 mlp_layer: The chosen MLP layer for implementing LoRA. 118 get_layers: Callable mapping `mlp_layer` to the tuple `(lin1, lin2, activation)`. 119 """ 120 def __init__(self, rank: int, mlp_layer: nn.Module, get_layers: Callable): 121 super().__init__() 122 self.mlp_layer = mlp_layer 123 self.get_layers = get_layers 124 self.rank = rank 125 lin1, lin2, _ = get_layers(mlp_layer) 126 self.w_a_linear_1 = nn.Linear(lin1.in_features, rank, bias=False) 127 self.w_b_linear_1 = nn.Linear(rank, lin1.out_features, bias=False) 128 self.w_a_linear_2 = nn.Linear(lin2.in_features, rank, bias=False) 129 self.w_b_linear_2 = nn.Linear(rank, lin2.out_features, bias=False) 130 131 self.reset_parameters() 132 133 def reset_parameters(self): 134 nn.init.kaiming_uniform_(self.w_a_linear_1.weight, a=math.sqrt(5)) 135 nn.init.kaiming_uniform_(self.w_a_linear_2.weight, a=math.sqrt(5)) 136 nn.init.zeros_(self.w_b_linear_1.weight) 137 nn.init.zeros_(self.w_b_linear_2.weight) 138 139 def forward(self, x): 140 lin1, lin2, activation = self.get_layers(self.mlp_layer) 141 x = lin1(x) + self.w_b_linear_1(self.w_a_linear_1(x)) 142 x = activation(x) 143 x = lin2(x) + self.w_b_linear_2(self.w_a_linear_2(x)) 144 return x
Low-rank adaptation on a two-layer feed forward block.
The get_layers function supports the different MLP layouts in SAM and SAM2.
Arguments:
- rank: The rank of the decomposition matrices for updating weights in each feed forward layer.
- mlp_layer: The chosen MLP layer for implementing LoRA.
- get_layers: Callable mapping
mlp_layerto the tuple(lin1, lin2, activation).
120 def __init__(self, rank: int, mlp_layer: nn.Module, get_layers: Callable): 121 super().__init__() 122 self.mlp_layer = mlp_layer 123 self.get_layers = get_layers 124 self.rank = rank 125 lin1, lin2, _ = get_layers(mlp_layer) 126 self.w_a_linear_1 = nn.Linear(lin1.in_features, rank, bias=False) 127 self.w_b_linear_1 = nn.Linear(rank, lin1.out_features, bias=False) 128 self.w_a_linear_2 = nn.Linear(lin2.in_features, rank, bias=False) 129 self.w_b_linear_2 = nn.Linear(rank, lin2.out_features, bias=False) 130 131 self.reset_parameters()
Initialize internal Module state, shared by both nn.Module and ScriptModule.
139 def forward(self, x): 140 lin1, lin2, activation = self.get_layers(self.mlp_layer) 141 x = lin1(x) + self.w_b_linear_1(self.w_a_linear_1(x)) 142 x = activation(x) 143 x = lin2(x) + self.w_b_linear_2(self.w_a_linear_2(x)) 144 return x
Define the computation performed at every call.
Should be overridden by all subclasses.
Although the recipe for forward pass needs to be defined within
this function, one should call the Module instance afterwards
instead of this since the former takes care of running the
registered hooks while the latter silently ignores them.
147class ScaleShiftLayer(nn.Module): 148 """Wraps a layer to apply learnable per-channel scale and shift to its output (used by SSF).""" 149 def __init__(self, layer, dim): 150 super().__init__() 151 self.layer = layer 152 self.scale = nn.Parameter(torch.normal(mean=1.0, std=0.2, size=(dim,))) 153 self.shift = nn.Parameter(torch.normal(mean=0.0, std=0.2, size=(dim,))) 154 155 def forward(self, x): 156 x = self.layer(x) 157 assert self.scale.shape == self.shift.shape 158 if x.shape[-1] == self.scale.shape[0]: 159 return x * self.scale + self.shift 160 elif x.shape[1] == self.scale.shape[0]: 161 return x * self.scale.view(1, -1, 1, 1) + self.shift.view(1, -1, 1, 1) 162 else: 163 raise ValueError( 164 f"The input shape {tuple(x.shape)} does not match the scale shape {tuple(self.scale.shape)}." 165 )
Wraps a layer to apply learnable per-channel scale and shift to its output (used by SSF).
149 def __init__(self, layer, dim): 150 super().__init__() 151 self.layer = layer 152 self.scale = nn.Parameter(torch.normal(mean=1.0, std=0.2, size=(dim,))) 153 self.shift = nn.Parameter(torch.normal(mean=0.0, std=0.2, size=(dim,)))
Initialize internal Module state, shared by both nn.Module and ScriptModule.
155 def forward(self, x): 156 x = self.layer(x) 157 assert self.scale.shape == self.shift.shape 158 if x.shape[-1] == self.scale.shape[0]: 159 return x * self.scale + self.shift 160 elif x.shape[1] == self.scale.shape[0]: 161 return x * self.scale.view(1, -1, 1, 1) + self.shift.view(1, -1, 1, 1) 162 else: 163 raise ValueError( 164 f"The input shape {tuple(x.shape)} does not match the scale shape {tuple(self.scale.shape)}." 165 )
Define the computation performed at every call.
Should be overridden by all subclasses.
Although the recipe for forward pass needs to be defined within
this function, one should call the Module instance afterwards
instead of this since the former takes care of running the
registered hooks while the latter silently ignores them.
168class SelectiveSurgery(nn.Module): 169 """Allow gradient updates for selected parameters.""" 170 def __init__(self, block: nn.Module): 171 super().__init__() 172 self.block = block 173 174 def allow_gradient_update_for_parameters( 175 self, 176 prefix: Optional[List[str]] = None, 177 suffix: Optional[List[str]] = None, 178 infix: Optional[List[str]] = None, 179 ): 180 """Allow gradient updates for parameter names that match the filters. 181 182 Args: 183 prefix: Matches the part of parameter name in front. 184 suffix: Matches the part of parameter name at the end. 185 infix: Matches parts of parameter name occurring in between. 186 """ 187 for k, v in self.block.named_parameters(): 188 if prefix is not None and k.startswith(tuple(prefix)): 189 v.requires_grad = True 190 191 if suffix is not None and k.endswith(tuple(suffix)): 192 v.requires_grad = True 193 194 if infix is not None: 195 for per_infix in infix: 196 if k.find(per_infix) != -1: 197 v.requires_grad = True 198 199 def forward(self, x): 200 return x
Allow gradient updates for selected parameters.
Initialize internal Module state, shared by both nn.Module and ScriptModule.
174 def allow_gradient_update_for_parameters( 175 self, 176 prefix: Optional[List[str]] = None, 177 suffix: Optional[List[str]] = None, 178 infix: Optional[List[str]] = None, 179 ): 180 """Allow gradient updates for parameter names that match the filters. 181 182 Args: 183 prefix: Matches the part of parameter name in front. 184 suffix: Matches the part of parameter name at the end. 185 infix: Matches parts of parameter name occurring in between. 186 """ 187 for k, v in self.block.named_parameters(): 188 if prefix is not None and k.startswith(tuple(prefix)): 189 v.requires_grad = True 190 191 if suffix is not None and k.endswith(tuple(suffix)): 192 v.requires_grad = True 193 194 if infix is not None: 195 for per_infix in infix: 196 if k.find(per_infix) != -1: 197 v.requires_grad = True
Allow gradient updates for parameter names that match the filters.
Arguments:
- prefix: Matches the part of parameter name in front.
- suffix: Matches the part of parameter name at the end.
- infix: Matches parts of parameter name occurring in between.
Define the computation performed at every call.
Should be overridden by all subclasses.
Although the recipe for forward pass needs to be defined within
this function, one should call the Module instance afterwards
instead of this since the former takes care of running the
registered hooks while the latter silently ignores them.
203class AttentionSurgery(SelectiveSurgery): 204 """Allow gradient updates for parameters in attention layers.""" 205 206 def __init__(self, block: nn.Module): 207 super().__init__(block=block) 208 self.allow_gradient_update_for_parameters(prefix=["attn"])
Allow gradient updates for parameters in attention layers.
206 def __init__(self, block: nn.Module): 207 super().__init__(block=block) 208 self.allow_gradient_update_for_parameters(prefix=["attn"])
Initialize internal Module state, shared by both nn.Module and ScriptModule.
Inherited Members
211class BiasSurgery(SelectiveSurgery): 212 """Allow gradient updates for bias parameters.""" 213 214 def __init__(self, block: nn.Module): 215 super().__init__(block=block) 216 self.allow_gradient_update_for_parameters(suffix=["bias"])
Allow gradient updates for bias parameters.
214 def __init__(self, block: nn.Module): 215 super().__init__(block=block) 216 self.allow_gradient_update_for_parameters(suffix=["bias"])
Initialize internal Module state, shared by both nn.Module and ScriptModule.
Inherited Members
219class LayerNormSurgery(SelectiveSurgery): 220 """Allow gradient updates for parameters in normalization layers.""" 221 222 def __init__(self, block: nn.Module): 223 super().__init__(block=block) 224 self.allow_gradient_update_for_parameters(infix=["norm1", "norm2"])
Allow gradient updates for parameters in normalization layers.
222 def __init__(self, block: nn.Module): 223 super().__init__(block=block) 224 self.allow_gradient_update_for_parameters(infix=["norm1", "norm2"])
Initialize internal Module state, shared by both nn.Module and ScriptModule.
Inherited Members
227class ClassicalSurgery(SelectiveSurgery): 228 """Allow gradient updates for all parameters in selected blocks.""" 229 230 def __init__(self, block: nn.Module): 231 super().__init__(block=block) 232 self.block = block 233 234 for k, v in self.block.named_parameters(): 235 v.requires_grad = True 236 237 def forward(self, x): 238 return x
Allow gradient updates for all parameters in selected blocks.
230 def __init__(self, block: nn.Module): 231 super().__init__(block=block) 232 self.block = block 233 234 for k, v in self.block.named_parameters(): 235 v.requires_grad = True
Initialize internal Module state, shared by both nn.Module and ScriptModule.
Define the computation performed at every call.
Should be overridden by all subclasses.
Although the recipe for forward pass needs to be defined within
this function, one should call the Module instance afterwards
instead of this since the former takes care of running the
registered hooks while the latter silently ignores them.
Inherited Members
241class FacTSurgery(nn.Module): 242 """Apply factorized attention to attention layers. 243 244 Based on https://github.com/cchen-cc/MA-SAM/blob/main/MA-SAM/sam_fact_tt_image_encoder.py. 245 This module supports the symmetric SAM projection and the asymmetric SAM2 Hiera projection. 246 247 Args: 248 rank: The rank of the decomposition matrices for updating weights in each attention layer. 249 block: The chosen attention block for implementing fact. 250 dropout: The dropout rate for the factorized attention. 251 """ 252 def __init__(self, rank: int, block: nn.Module, dropout: Optional[float] = 0.1): 253 super().__init__() 254 self.qkv_proj = block.attn.qkv 255 self.in_dim = self.qkv_proj.in_features 256 self.out_dim = self.qkv_proj.out_features // 3 257 258 self.q_FacTs = nn.Linear(rank, rank, bias=False) 259 self.v_FacTs = nn.Linear(rank, rank, bias=False) 260 261 self.dropout = dropout 262 if self.dropout is not None: 263 self.dp_q = nn.Dropout(self.dropout) 264 self.dp_v = nn.Dropout(self.dropout) 265 266 self.FacTu = nn.Linear(self.in_dim, rank, bias=False) 267 self.FacTv = nn.Linear(rank, self.out_dim, bias=False) 268 269 block.attn.qkv = self 270 271 def forward(self, x): 272 qkv = self.qkv_proj(x) 273 d = self.out_dim 274 275 new_q = self.q_FacTs(self.FacTu(x)) 276 new_v = self.v_FacTs(self.FacTu(x)) 277 278 if self.dropout is not None: 279 new_q = self.dp_q(new_q) 280 new_v = self.dp_v(new_v) 281 282 new_q = self.FacTv(new_q) 283 new_v = self.FacTv(new_v) 284 285 # The learning rate controls the scale, so the scaling factor is 1. 286 qkv = torch.cat( 287 [ 288 qkv[..., :d] + new_q, 289 qkv[..., d:2 * d], 290 qkv[..., 2 * d:] + new_v, 291 ], 292 dim=-1, 293 ) 294 295 return qkv
Apply factorized attention to attention layers.
Based on https://github.com/cchen-cc/MA-SAM/blob/main/MA-SAM/sam_fact_tt_image_encoder.py. This module supports the symmetric SAM projection and the asymmetric SAM2 Hiera projection.
Arguments:
- rank: The rank of the decomposition matrices for updating weights in each attention layer.
- block: The chosen attention block for implementing fact.
- dropout: The dropout rate for the factorized attention.
252 def __init__(self, rank: int, block: nn.Module, dropout: Optional[float] = 0.1): 253 super().__init__() 254 self.qkv_proj = block.attn.qkv 255 self.in_dim = self.qkv_proj.in_features 256 self.out_dim = self.qkv_proj.out_features // 3 257 258 self.q_FacTs = nn.Linear(rank, rank, bias=False) 259 self.v_FacTs = nn.Linear(rank, rank, bias=False) 260 261 self.dropout = dropout 262 if self.dropout is not None: 263 self.dp_q = nn.Dropout(self.dropout) 264 self.dp_v = nn.Dropout(self.dropout) 265 266 self.FacTu = nn.Linear(self.in_dim, rank, bias=False) 267 self.FacTv = nn.Linear(rank, self.out_dim, bias=False) 268 269 block.attn.qkv = self
Initialize internal Module state, shared by both nn.Module and ScriptModule.
271 def forward(self, x): 272 qkv = self.qkv_proj(x) 273 d = self.out_dim 274 275 new_q = self.q_FacTs(self.FacTu(x)) 276 new_v = self.v_FacTs(self.FacTu(x)) 277 278 if self.dropout is not None: 279 new_q = self.dp_q(new_q) 280 new_v = self.dp_v(new_v) 281 282 new_q = self.FacTv(new_q) 283 new_v = self.FacTv(new_v) 284 285 # The learning rate controls the scale, so the scaling factor is 1. 286 qkv = torch.cat( 287 [ 288 qkv[..., :d] + new_q, 289 qkv[..., d:2 * d], 290 qkv[..., 2 * d:] + new_v, 291 ], 292 dim=-1, 293 ) 294 295 return qkv
Define the computation performed at every call.
Should be overridden by all subclasses.
Although the recipe for forward pass needs to be defined within
this function, one should call the Module instance afterwards
instead of this since the former takes care of running the
registered hooks while the latter silently ignores them.
298class AdaptFormer(nn.Module): 299 """Adds an AdaptFormer module in place of the MLP layers. 300 301 Args: 302 rank: The rank is not used in this class but kept here for consistency. 303 block: The chosen encoder block for implementing AdaptFormer. 304 alpha: The value that scales the adapter path. Pass a number or `"learnable_scalar"`. 305 dropout: The dropout rate for the dropout layer between the down and up projection layer. 306 projection_size: The size of the projection layer. 307 """ 308 def __init__( 309 self, 310 rank: int, 311 block: nn.Module, 312 alpha: Optional[Union[str, float]] = "learnable_scalar", # Preliminary experiments support this value. 313 dropout: Optional[float] = None, # Preliminary experiments show no clear benefit. 314 projection_size: int = 64, # Preliminary experiments support this value. 315 ): 316 super().__init__() 317 318 self.mlp_proj = block.mlp 319 # SAM and SAM2 use different attributes for the first MLP layer. 320 self.n_embd = block.mlp.lin1.in_features if hasattr(block.mlp, "lin1") else block.mlp.layers[0].in_features 321 322 if alpha == 'learnable_scalar': 323 self.alpha = nn.Parameter(torch.ones(1)) 324 else: 325 self.alpha = alpha 326 327 self.projection_size = projection_size 328 self.dropout = dropout 329 330 self.down_proj = nn.Linear(self.n_embd, self.projection_size) 331 self.non_linear_func = nn.ReLU() 332 self.up_proj = nn.Linear(self.projection_size, self.n_embd) 333 334 block.mlp = self 335 336 if self.dropout is not None: 337 self.dropout_layer = nn.Dropout(self.dropout) 338 339 nn.init.kaiming_uniform_(self.down_proj.weight, a=math.sqrt(5)) 340 nn.init.zeros_(self.up_proj.weight) 341 nn.init.zeros_(self.down_proj.bias) 342 nn.init.zeros_(self.up_proj.bias) 343 344 def forward(self, x): 345 mlp_output = self.mlp_proj(x) 346 347 down = self.down_proj(x) 348 down = self.non_linear_func(down) 349 350 if self.dropout is not None: 351 down = self.dropout_layer(down) 352 353 up = self.up_proj(down) 354 up = up * self.alpha 355 output = up + mlp_output 356 357 return output
Adds an AdaptFormer module in place of the MLP layers.
Arguments:
- rank: The rank is not used in this class but kept here for consistency.
- block: The chosen encoder block for implementing AdaptFormer.
- alpha: The value that scales the adapter path. Pass a number or
"learnable_scalar". - dropout: The dropout rate for the dropout layer between the down and up projection layer.
- projection_size: The size of the projection layer.
308 def __init__( 309 self, 310 rank: int, 311 block: nn.Module, 312 alpha: Optional[Union[str, float]] = "learnable_scalar", # Preliminary experiments support this value. 313 dropout: Optional[float] = None, # Preliminary experiments show no clear benefit. 314 projection_size: int = 64, # Preliminary experiments support this value. 315 ): 316 super().__init__() 317 318 self.mlp_proj = block.mlp 319 # SAM and SAM2 use different attributes for the first MLP layer. 320 self.n_embd = block.mlp.lin1.in_features if hasattr(block.mlp, "lin1") else block.mlp.layers[0].in_features 321 322 if alpha == 'learnable_scalar': 323 self.alpha = nn.Parameter(torch.ones(1)) 324 else: 325 self.alpha = alpha 326 327 self.projection_size = projection_size 328 self.dropout = dropout 329 330 self.down_proj = nn.Linear(self.n_embd, self.projection_size) 331 self.non_linear_func = nn.ReLU() 332 self.up_proj = nn.Linear(self.projection_size, self.n_embd) 333 334 block.mlp = self 335 336 if self.dropout is not None: 337 self.dropout_layer = nn.Dropout(self.dropout) 338 339 nn.init.kaiming_uniform_(self.down_proj.weight, a=math.sqrt(5)) 340 nn.init.zeros_(self.up_proj.weight) 341 nn.init.zeros_(self.down_proj.bias) 342 nn.init.zeros_(self.up_proj.bias)
Initialize internal Module state, shared by both nn.Module and ScriptModule.
344 def forward(self, x): 345 mlp_output = self.mlp_proj(x) 346 347 down = self.down_proj(x) 348 down = self.non_linear_func(down) 349 350 if self.dropout is not None: 351 down = self.dropout_layer(down) 352 353 up = self.up_proj(down) 354 up = up * self.alpha 355 output = up + mlp_output 356 357 return output
Define the computation performed at every call.
Should be overridden by all subclasses.
Although the recipe for forward pass needs to be defined within
this function, one should call the Module instance afterwards
instead of this since the former takes care of running the
registered hooks while the latter silently ignores them.
360def serialize_peft_kwargs(peft_kwargs: Optional[dict]) -> Optional[dict]: 361 """Convert `peft_kwargs` to a dictionary that a checkpoint can store. 362 363 Args: 364 peft_kwargs: The PEFT keyword arguments, or None. 365 366 Returns: 367 The serialized config, or None if `peft_kwargs` is empty. 368 """ 369 if not peft_kwargs: 370 return None 371 serialized = dict(peft_kwargs) 372 module = serialized.get("peft_module") 373 if module is not None and not isinstance(module, str): 374 serialized["peft_module"] = module.__name__ 375 return serialized
Convert peft_kwargs to a dictionary that a checkpoint can store.
Arguments:
- peft_kwargs: The PEFT keyword arguments, or None.
Returns:
The serialized config, or None if
peft_kwargsis empty.
378def deserialize_peft_kwargs(config: Optional[dict], module_registry: dict) -> Optional[dict]: 379 """Build `peft_kwargs` from a saved configuration. 380 381 Args: 382 config: The serialized config (as produced by `serialize_peft_kwargs`), or None. 383 module_registry: The mapping from each PEFT module name to its class. 384 385 Returns: 386 The deserialized `peft_kwargs`, or None if `config` is empty. 387 """ 388 if not config: 389 return None 390 deserialized = dict(config) 391 module = deserialized.get("peft_module") 392 if isinstance(module, str): 393 if module not in module_registry: 394 raise ValueError(f"Unknown PEFT module '{module}'. Known modules: {sorted(module_registry)}") 395 deserialized["peft_module"] = module_registry[module] 396 return deserialized
Build peft_kwargs from a saved configuration.
Arguments:
- config: The serialized config (as produced by
serialize_peft_kwargs), or None. - module_registry: The mapping from each PEFT module name to its class.
Returns:
The deserialized
peft_kwargs, or None ifconfigis empty.