micro_sam.v1.models.peft_sam
1from typing import List, Union, Optional 2 3from segment_anything.modeling import Sam 4 5import torch.nn as nn 6 7from micro_sam.models.peft import ( # noqa 8 MLPLoRA, AdaptFormer, FacTSurgery, AttentionLoRA, BiasSurgery, ScaleShiftLayer, ClassicalSurgery, 9 AttentionSurgery, SelectiveSurgery, LayerNormSurgery, quantize_linear_layers, 10) 11 12 13class LoRASurgery(nn.Module): 14 """Operates on the linear layers (attention and/or other feed forward) for performing low-rank adaptation. 15 16 (Inspired from: https://github.com/JamesQFreeman/Sam_LoRA/) 17 18 In SAM, it is implemented as: 19 ```python 20 self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias) 21 B, N, C = x.shape 22 qkv = self.qkv(x).reshape(B, N, 3, self.num_heads, self.head_dim).permute(2, 0, 3, 1, 4) 23 q, k, v = qkv.unbind(0) 24 ``` 25 26 Args: 27 rank: The rank of the decomposition matrices for updating weights in each attention layer. 28 block: The chosen attention blocks for implementing LoRA. 29 update_matrices: Which specific matrices to update in the attention layer. Choice of "q", "k", "v", "mlp". 30 """ 31 def __init__(self, rank: int, block: nn.Module, update_matrices: List[str] = ["q", "v"]): 32 super().__init__() 33 # Check whether all values for "update_matrices" are as expected. 34 if set(update_matrices) - set(["q", "k", "v", "mlp"]): 35 raise ValueError(f"Some of the expected keys for updating matrics in '{update_matrices}' are not expected.") 36 37 self.block = block 38 block.attn.qkv = AttentionLoRA(rank=rank, block=block.attn.qkv, update_matrices=update_matrices) 39 40 if "mlp" in update_matrices: 41 # SAM stores its MLP layers in `lin1` and `lin2`. 42 block.mlp = MLPLoRA(rank=rank, mlp_layer=block.mlp, get_layers=lambda m: (m.lin1, m.lin2, m.act)) 43 44 def forward(self, x): 45 return x 46 47 48class SSFSurgery(nn.Module): 49 """Operates on all layers in the transformer block for adding learnable scale and shift parameters. 50 51 Args: 52 rank: This parameter is not used in `SSFSurgery`. This is kept here for consistency. 53 block: The chosen attention blocks for implementing ssf. 54 """ 55 def __init__(self, rank: int, block: nn.Module): 56 super().__init__() 57 self.block = block 58 59 # If we get a transformer block (w. multiple sub-layers), we perform surgery on each layer. 60 if hasattr(block, "attn"): # the minimum assumption is to verify the attention layers. 61 block.attn.qkv = ScaleShiftLayer(block.attn.qkv, block.attn.qkv.in_features*3) 62 block.attn.proj = ScaleShiftLayer(block.attn.proj, block.attn.proj.in_features) 63 block.mlp.lin1 = ScaleShiftLayer(block.mlp.lin1, block.mlp.lin1.out_features) 64 block.mlp.lin2 = ScaleShiftLayer(block.mlp.lin2, block.mlp.lin2.out_features) 65 block.norm1 = ScaleShiftLayer(block.norm1, block.norm1.normalized_shape[0]) 66 block.norm2 = ScaleShiftLayer(block.norm2, block.norm2.normalized_shape[0]) 67 68 # If we get the embedding block, add one ScaleShiftLayer 69 elif hasattr(block, "patch_embed"): 70 block.proj = ScaleShiftLayer(block.proj, block.proj.out_channels) 71 72 def forward(self, x): 73 return x 74 75 76class PEFT_Sam(nn.Module): 77 """Wraps the Segment Anything model's image encoder to different parameter efficient finetuning methods. 78 79 Args: 80 model: The Segment Anything model. 81 rank: The rank for low-rank adaptation. 82 peft_module: Wrapper to operate on the image encoder blocks for the PEFT method. 83 attention_layers_to_update: Which specific layers we apply PEFT methods to. 84 For reference, the total number of blocks for 'vit_b' is 12, for 'vit_l' is 24 and for 'vit_h' is 32. 85 By default, applies the PEFT method to all attention layers. 86 quantize: Whether to quantize the model for lower precision training. By default, does not quantize the model. 87 module_kwargs: The additional arguments for the respective PEFT modules. 88 """ 89 90 def __init__( 91 self, 92 model: Sam, 93 rank: Optional[int] = None, 94 peft_module: nn.Module = LoRASurgery, 95 attention_layers_to_update: Optional[List[int]] = None, 96 quantize: bool = False, 97 **module_kwargs 98 ): 99 super().__init__() 100 101 if issubclass(peft_module, Union[LoRASurgery, FacTSurgery]) and (not rank or rank <= 0): 102 raise RuntimeError("The chosen PEFT method cannot run without a valid rank choice.") 103 104 assert issubclass(peft_module, Union[LoRASurgery, FacTSurgery, SelectiveSurgery, SSFSurgery, AdaptFormer]), ( 105 "Invalid PEFT module" 106 ) 107 if attention_layers_to_update: 108 self.peft_layers = attention_layers_to_update 109 else: # Applies PEFT to the image encoder by default 110 self.peft_layers = list(range(len(model.image_encoder.blocks))) 111 112 self.peft_module = peft_module 113 self.peft_blocks = [] 114 115 # Whether to quantize the linear layers to 4 bit precision. 116 # NOTE: This is currently supported for CUDA-supported devices only. 117 if quantize: 118 quantize_linear_layers(model.image_encoder) 119 120 # Let's freeze all the pretrained image encoder layers first 121 for param in model.image_encoder.parameters(): 122 param.requires_grad = False 123 124 # Add scale and shift parameters to the patch embedding layers. 125 if issubclass(self.peft_module, SSFSurgery): 126 self.peft_blocks.append(self.peft_module(rank=rank, block=model.image_encoder.patch_embed)) 127 128 # If specified, the attention layers to update should match the available blocks. 129 if attention_layers_to_update and ( 130 set(attention_layers_to_update) - set(list(range(len(model.image_encoder.blocks)))) 131 ): 132 raise ValueError("The chosen layer(s) to apply PEFT method is not a valid transformer block id.") 133 134 for t_layer_i, blk in enumerate(model.image_encoder.blocks): 135 136 # If we only want specific layers with PEFT instead of all 137 if t_layer_i not in self.peft_layers: 138 continue 139 140 if issubclass(self.peft_module, SelectiveSurgery): 141 self.peft_blocks.append(self.peft_module(block=blk)) 142 else: 143 self.peft_blocks.append(self.peft_module(rank=rank, block=blk, **module_kwargs)) 144 145 self.peft_blocks = nn.ModuleList(self.peft_blocks) 146 self.sam = model 147 148 def forward(self, batched_input, multimask_output): 149 return self.sam(batched_input, multimask_output)
14class LoRASurgery(nn.Module): 15 """Operates on the linear layers (attention and/or other feed forward) for performing low-rank adaptation. 16 17 (Inspired from: https://github.com/JamesQFreeman/Sam_LoRA/) 18 19 In SAM, it is implemented as: 20 ```python 21 self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias) 22 B, N, C = x.shape 23 qkv = self.qkv(x).reshape(B, N, 3, self.num_heads, self.head_dim).permute(2, 0, 3, 1, 4) 24 q, k, v = qkv.unbind(0) 25 ``` 26 27 Args: 28 rank: The rank of the decomposition matrices for updating weights in each attention layer. 29 block: The chosen attention blocks for implementing LoRA. 30 update_matrices: Which specific matrices to update in the attention layer. Choice of "q", "k", "v", "mlp". 31 """ 32 def __init__(self, rank: int, block: nn.Module, update_matrices: List[str] = ["q", "v"]): 33 super().__init__() 34 # Check whether all values for "update_matrices" are as expected. 35 if set(update_matrices) - set(["q", "k", "v", "mlp"]): 36 raise ValueError(f"Some of the expected keys for updating matrics in '{update_matrices}' are not expected.") 37 38 self.block = block 39 block.attn.qkv = AttentionLoRA(rank=rank, block=block.attn.qkv, update_matrices=update_matrices) 40 41 if "mlp" in update_matrices: 42 # SAM stores its MLP layers in `lin1` and `lin2`. 43 block.mlp = MLPLoRA(rank=rank, mlp_layer=block.mlp, get_layers=lambda m: (m.lin1, m.lin2, m.act)) 44 45 def forward(self, x): 46 return x
Operates on the linear layers (attention and/or other feed forward) for performing low-rank adaptation.
(Inspired from: https://github.com/JamesQFreeman/Sam_LoRA/)
In SAM, it is implemented as:
self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias)
B, N, C = x.shape
qkv = self.qkv(x).reshape(B, N, 3, self.num_heads, self.head_dim).permute(2, 0, 3, 1, 4)
q, k, v = qkv.unbind(0)
Arguments:
- rank: The rank of the decomposition matrices for updating weights in each attention layer.
- block: The chosen attention blocks for implementing LoRA.
- update_matrices: Which specific matrices to update in the attention layer. Choice of "q", "k", "v", "mlp".
32 def __init__(self, rank: int, block: nn.Module, update_matrices: List[str] = ["q", "v"]): 33 super().__init__() 34 # Check whether all values for "update_matrices" are as expected. 35 if set(update_matrices) - set(["q", "k", "v", "mlp"]): 36 raise ValueError(f"Some of the expected keys for updating matrics in '{update_matrices}' are not expected.") 37 38 self.block = block 39 block.attn.qkv = AttentionLoRA(rank=rank, block=block.attn.qkv, update_matrices=update_matrices) 40 41 if "mlp" in update_matrices: 42 # SAM stores its MLP layers in `lin1` and `lin2`. 43 block.mlp = MLPLoRA(rank=rank, mlp_layer=block.mlp, get_layers=lambda m: (m.lin1, m.lin2, m.act))
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.
49class SSFSurgery(nn.Module): 50 """Operates on all layers in the transformer block for adding learnable scale and shift parameters. 51 52 Args: 53 rank: This parameter is not used in `SSFSurgery`. This is kept here for consistency. 54 block: The chosen attention blocks for implementing ssf. 55 """ 56 def __init__(self, rank: int, block: nn.Module): 57 super().__init__() 58 self.block = block 59 60 # If we get a transformer block (w. multiple sub-layers), we perform surgery on each layer. 61 if hasattr(block, "attn"): # the minimum assumption is to verify the attention layers. 62 block.attn.qkv = ScaleShiftLayer(block.attn.qkv, block.attn.qkv.in_features*3) 63 block.attn.proj = ScaleShiftLayer(block.attn.proj, block.attn.proj.in_features) 64 block.mlp.lin1 = ScaleShiftLayer(block.mlp.lin1, block.mlp.lin1.out_features) 65 block.mlp.lin2 = ScaleShiftLayer(block.mlp.lin2, block.mlp.lin2.out_features) 66 block.norm1 = ScaleShiftLayer(block.norm1, block.norm1.normalized_shape[0]) 67 block.norm2 = ScaleShiftLayer(block.norm2, block.norm2.normalized_shape[0]) 68 69 # If we get the embedding block, add one ScaleShiftLayer 70 elif hasattr(block, "patch_embed"): 71 block.proj = ScaleShiftLayer(block.proj, block.proj.out_channels) 72 73 def forward(self, x): 74 return x
Operates on all layers in the transformer block for adding learnable scale and shift parameters.
Arguments:
- rank: This parameter is not used in
SSFSurgery. This is kept here for consistency. - block: The chosen attention blocks for implementing ssf.
56 def __init__(self, rank: int, block: nn.Module): 57 super().__init__() 58 self.block = block 59 60 # If we get a transformer block (w. multiple sub-layers), we perform surgery on each layer. 61 if hasattr(block, "attn"): # the minimum assumption is to verify the attention layers. 62 block.attn.qkv = ScaleShiftLayer(block.attn.qkv, block.attn.qkv.in_features*3) 63 block.attn.proj = ScaleShiftLayer(block.attn.proj, block.attn.proj.in_features) 64 block.mlp.lin1 = ScaleShiftLayer(block.mlp.lin1, block.mlp.lin1.out_features) 65 block.mlp.lin2 = ScaleShiftLayer(block.mlp.lin2, block.mlp.lin2.out_features) 66 block.norm1 = ScaleShiftLayer(block.norm1, block.norm1.normalized_shape[0]) 67 block.norm2 = ScaleShiftLayer(block.norm2, block.norm2.normalized_shape[0]) 68 69 # If we get the embedding block, add one ScaleShiftLayer 70 elif hasattr(block, "patch_embed"): 71 block.proj = ScaleShiftLayer(block.proj, block.proj.out_channels)
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.
77class PEFT_Sam(nn.Module): 78 """Wraps the Segment Anything model's image encoder to different parameter efficient finetuning methods. 79 80 Args: 81 model: The Segment Anything model. 82 rank: The rank for low-rank adaptation. 83 peft_module: Wrapper to operate on the image encoder blocks for the PEFT method. 84 attention_layers_to_update: Which specific layers we apply PEFT methods to. 85 For reference, the total number of blocks for 'vit_b' is 12, for 'vit_l' is 24 and for 'vit_h' is 32. 86 By default, applies the PEFT method to all attention layers. 87 quantize: Whether to quantize the model for lower precision training. By default, does not quantize the model. 88 module_kwargs: The additional arguments for the respective PEFT modules. 89 """ 90 91 def __init__( 92 self, 93 model: Sam, 94 rank: Optional[int] = None, 95 peft_module: nn.Module = LoRASurgery, 96 attention_layers_to_update: Optional[List[int]] = None, 97 quantize: bool = False, 98 **module_kwargs 99 ): 100 super().__init__() 101 102 if issubclass(peft_module, Union[LoRASurgery, FacTSurgery]) and (not rank or rank <= 0): 103 raise RuntimeError("The chosen PEFT method cannot run without a valid rank choice.") 104 105 assert issubclass(peft_module, Union[LoRASurgery, FacTSurgery, SelectiveSurgery, SSFSurgery, AdaptFormer]), ( 106 "Invalid PEFT module" 107 ) 108 if attention_layers_to_update: 109 self.peft_layers = attention_layers_to_update 110 else: # Applies PEFT to the image encoder by default 111 self.peft_layers = list(range(len(model.image_encoder.blocks))) 112 113 self.peft_module = peft_module 114 self.peft_blocks = [] 115 116 # Whether to quantize the linear layers to 4 bit precision. 117 # NOTE: This is currently supported for CUDA-supported devices only. 118 if quantize: 119 quantize_linear_layers(model.image_encoder) 120 121 # Let's freeze all the pretrained image encoder layers first 122 for param in model.image_encoder.parameters(): 123 param.requires_grad = False 124 125 # Add scale and shift parameters to the patch embedding layers. 126 if issubclass(self.peft_module, SSFSurgery): 127 self.peft_blocks.append(self.peft_module(rank=rank, block=model.image_encoder.patch_embed)) 128 129 # If specified, the attention layers to update should match the available blocks. 130 if attention_layers_to_update and ( 131 set(attention_layers_to_update) - set(list(range(len(model.image_encoder.blocks)))) 132 ): 133 raise ValueError("The chosen layer(s) to apply PEFT method is not a valid transformer block id.") 134 135 for t_layer_i, blk in enumerate(model.image_encoder.blocks): 136 137 # If we only want specific layers with PEFT instead of all 138 if t_layer_i not in self.peft_layers: 139 continue 140 141 if issubclass(self.peft_module, SelectiveSurgery): 142 self.peft_blocks.append(self.peft_module(block=blk)) 143 else: 144 self.peft_blocks.append(self.peft_module(rank=rank, block=blk, **module_kwargs)) 145 146 self.peft_blocks = nn.ModuleList(self.peft_blocks) 147 self.sam = model 148 149 def forward(self, batched_input, multimask_output): 150 return self.sam(batched_input, multimask_output)
Wraps the Segment Anything model's image encoder to different parameter efficient finetuning methods.
Arguments:
- model: The Segment Anything model.
- rank: The rank for low-rank adaptation.
- peft_module: Wrapper to operate on the image encoder blocks for the PEFT method.
- attention_layers_to_update: Which specific layers we apply PEFT methods to. For reference, the total number of blocks for 'vit_b' is 12, for 'vit_l' is 24 and for 'vit_h' is 32. By default, applies the PEFT method to all attention layers.
- quantize: Whether to quantize the model for lower precision training. By default, does not quantize the model.
- module_kwargs: The additional arguments for the respective PEFT modules.
91 def __init__( 92 self, 93 model: Sam, 94 rank: Optional[int] = None, 95 peft_module: nn.Module = LoRASurgery, 96 attention_layers_to_update: Optional[List[int]] = None, 97 quantize: bool = False, 98 **module_kwargs 99 ): 100 super().__init__() 101 102 if issubclass(peft_module, Union[LoRASurgery, FacTSurgery]) and (not rank or rank <= 0): 103 raise RuntimeError("The chosen PEFT method cannot run without a valid rank choice.") 104 105 assert issubclass(peft_module, Union[LoRASurgery, FacTSurgery, SelectiveSurgery, SSFSurgery, AdaptFormer]), ( 106 "Invalid PEFT module" 107 ) 108 if attention_layers_to_update: 109 self.peft_layers = attention_layers_to_update 110 else: # Applies PEFT to the image encoder by default 111 self.peft_layers = list(range(len(model.image_encoder.blocks))) 112 113 self.peft_module = peft_module 114 self.peft_blocks = [] 115 116 # Whether to quantize the linear layers to 4 bit precision. 117 # NOTE: This is currently supported for CUDA-supported devices only. 118 if quantize: 119 quantize_linear_layers(model.image_encoder) 120 121 # Let's freeze all the pretrained image encoder layers first 122 for param in model.image_encoder.parameters(): 123 param.requires_grad = False 124 125 # Add scale and shift parameters to the patch embedding layers. 126 if issubclass(self.peft_module, SSFSurgery): 127 self.peft_blocks.append(self.peft_module(rank=rank, block=model.image_encoder.patch_embed)) 128 129 # If specified, the attention layers to update should match the available blocks. 130 if attention_layers_to_update and ( 131 set(attention_layers_to_update) - set(list(range(len(model.image_encoder.blocks)))) 132 ): 133 raise ValueError("The chosen layer(s) to apply PEFT method is not a valid transformer block id.") 134 135 for t_layer_i, blk in enumerate(model.image_encoder.blocks): 136 137 # If we only want specific layers with PEFT instead of all 138 if t_layer_i not in self.peft_layers: 139 continue 140 141 if issubclass(self.peft_module, SelectiveSurgery): 142 self.peft_blocks.append(self.peft_module(block=blk)) 143 else: 144 self.peft_blocks.append(self.peft_module(rank=rank, block=blk, **module_kwargs)) 145 146 self.peft_blocks = nn.ModuleList(self.peft_blocks) 147 self.sam = model
Initialize internal Module state, shared by both nn.Module and ScriptModule.
149 def forward(self, batched_input, multimask_output): 150 return self.sam(batched_input, multimask_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.