micro_sam.v2.models.peft_sam2

  1from typing import List, Optional
  2
  3import torch.nn as nn
  4
  5from micro_sam.models.peft import (
  6    MLPLoRA, AdaptFormer, FacTSurgery, AttentionLoRA, BiasSurgery, ScaleShiftLayer, ClassicalSurgery,
  7    AttentionSurgery, SelectiveSurgery, LayerNormSurgery, quantize_linear_layers,
  8)
  9
 10
 11class LoRASurgery(nn.Module):
 12    """Apply low-rank adaptation to the linear layers of a SAM2 Hiera block.
 13
 14    Based on https://github.com/JamesQFreeman/Sam_LoRA/.
 15
 16    Args:
 17        rank: The rank of the decomposition matrices for updating weights in each block.
 18        block: The chosen Hiera block for implementing LoRA.
 19        update_matrices: The matrices to update in the block. Choose "q", "k", "v", or "mlp".
 20    """
 21    def __init__(self, rank: int, block: nn.Module, update_matrices: List[str] = ["q", "v"]):
 22        super().__init__()
 23        invalid_matrices = set(update_matrices) - {"q", "k", "v", "mlp"}
 24        if invalid_matrices:
 25            raise ValueError(f"The update matrix names {sorted(invalid_matrices)} are not valid.")
 26
 27        self.block = block
 28        block.attn.qkv = AttentionLoRA(rank=rank, block=block.attn.qkv, update_matrices=update_matrices)
 29
 30        if "mlp" in update_matrices:
 31            block.mlp = MLPLoRA(
 32                rank=rank, mlp_layer=block.mlp, get_layers=lambda m: (m.layers[0], m.layers[1], m.act)
 33            )
 34
 35    def forward(self, x):
 36        return x
 37
 38
 39class SSFSurgery(nn.Module):
 40    """Add scale and shift parameters to each sublayer of a SAM2 Hiera block.
 41
 42    Args:
 43        rank: The unused rank. This argument keeps the PEFT module signatures consistent.
 44        block: The Hiera block or PatchEmbed to change.
 45    """
 46    def __init__(self, rank: int, block: nn.Module):
 47        super().__init__()
 48        self.block = block
 49
 50        if hasattr(block, "attn"):
 51            block.attn.qkv = ScaleShiftLayer(block.attn.qkv, block.attn.qkv.out_features)
 52            block.attn.proj = ScaleShiftLayer(block.attn.proj, block.attn.proj.out_features)
 53            block.mlp.layers[0] = ScaleShiftLayer(block.mlp.layers[0], block.mlp.layers[0].out_features)
 54            block.mlp.layers[1] = ScaleShiftLayer(block.mlp.layers[1], block.mlp.layers[1].out_features)
 55            block.norm1 = ScaleShiftLayer(block.norm1, block.norm1.normalized_shape[0])
 56            block.norm2 = ScaleShiftLayer(block.norm2, block.norm2.normalized_shape[0])
 57
 58        elif hasattr(block, "proj"):
 59            block.proj = ScaleShiftLayer(block.proj, block.proj.out_channels)
 60
 61    def forward(self, x):
 62        return x
 63
 64
 65class PEFT_Sam2(nn.Module):
 66    """Wrap the SAM2 Hiera image encoder for parameter efficient finetuning.
 67
 68    This class freezes the pretrained encoder parameters. It then applies the PEFT method to the selected Hiera blocks.
 69
 70    Args:
 71        model: The Segment Anything 2 model.
 72        rank: The rank for low-rank adaptation.
 73        peft_module: The wrapper for the PEFT method.
 74        attention_layers_to_update: The blocks that use the PEFT method. The default is all blocks.
 75        quantize: The flag that enables 4-bit encoder precision. This option needs CUDA and bitsandbytes.
 76        module_kwargs: The extra arguments for the PEFT module.
 77    """
 78
 79    def __init__(
 80        self,
 81        model: nn.Module,
 82        rank: Optional[int] = None,
 83        peft_module: nn.Module = LoRASurgery,
 84        attention_layers_to_update: Optional[List[int]] = None,
 85        quantize: bool = False,
 86        **module_kwargs,
 87    ):
 88        super().__init__()
 89
 90        if issubclass(peft_module, (LoRASurgery, FacTSurgery)) and (not rank or rank <= 0):
 91            raise RuntimeError(f"The rank {rank} is not valid for {peft_module.__name__}. Pass a positive integer.")
 92
 93        valid_modules = (LoRASurgery, FacTSurgery, SelectiveSurgery, SSFSurgery, AdaptFormer)
 94        if not issubclass(peft_module, valid_modules):
 95            raise ValueError(f"The PEFT module {peft_module.__name__} is not valid.")
 96
 97        blocks = model.image_encoder.trunk.blocks
 98
 99        if attention_layers_to_update:
100            self.peft_layers = attention_layers_to_update
101        else:
102            self.peft_layers = list(range(len(blocks)))
103
104        self.peft_module = peft_module
105        self.peft_blocks = []
106
107        if quantize:
108            quantize_linear_layers(model.image_encoder)
109
110        for param in model.image_encoder.parameters():
111            param.requires_grad = False
112
113        if issubclass(self.peft_module, SSFSurgery):
114            self.peft_blocks.append(self.peft_module(rank=rank, block=model.image_encoder.trunk.patch_embed))
115
116        if attention_layers_to_update and (set(attention_layers_to_update) - set(list(range(len(blocks))))):
117            raise ValueError(
118                f"The Hiera block ids {attention_layers_to_update} are not valid for a model with {len(blocks)} blocks."
119            )
120
121        for t_layer_i, blk in enumerate(blocks):
122
123            if t_layer_i not in self.peft_layers:
124                continue
125
126            if issubclass(self.peft_module, SelectiveSurgery):
127                self.peft_blocks.append(self.peft_module(block=blk))
128            else:
129                self.peft_blocks.append(self.peft_module(rank=rank, block=blk, **module_kwargs))
130
131        self.peft_blocks = nn.ModuleList(self.peft_blocks)
132        self.sam = model
133
134    def forward(self, *args, **kwargs):
135        return self.sam(*args, **kwargs)
136
137
138PEFT_MODULES = {
139    cls.__name__: cls
140    for cls in (
141        LoRASurgery, FacTSurgery, SSFSurgery, AdaptFormer,
142        ClassicalSurgery, AttentionSurgery, BiasSurgery, LayerNormSurgery,
143    )
144}
class LoRASurgery(torch.nn.modules.module.Module):
12class LoRASurgery(nn.Module):
13    """Apply low-rank adaptation to the linear layers of a SAM2 Hiera block.
14
15    Based on https://github.com/JamesQFreeman/Sam_LoRA/.
16
17    Args:
18        rank: The rank of the decomposition matrices for updating weights in each block.
19        block: The chosen Hiera block for implementing LoRA.
20        update_matrices: The matrices to update in the block. Choose "q", "k", "v", or "mlp".
21    """
22    def __init__(self, rank: int, block: nn.Module, update_matrices: List[str] = ["q", "v"]):
23        super().__init__()
24        invalid_matrices = set(update_matrices) - {"q", "k", "v", "mlp"}
25        if invalid_matrices:
26            raise ValueError(f"The update matrix names {sorted(invalid_matrices)} are not valid.")
27
28        self.block = block
29        block.attn.qkv = AttentionLoRA(rank=rank, block=block.attn.qkv, update_matrices=update_matrices)
30
31        if "mlp" in update_matrices:
32            block.mlp = MLPLoRA(
33                rank=rank, mlp_layer=block.mlp, get_layers=lambda m: (m.layers[0], m.layers[1], m.act)
34            )
35
36    def forward(self, x):
37        return x

Apply low-rank adaptation to the linear layers of a SAM2 Hiera block.

Based on https://github.com/JamesQFreeman/Sam_LoRA/.

Arguments:
  • rank: The rank of the decomposition matrices for updating weights in each block.
  • block: The chosen Hiera block for implementing LoRA.
  • update_matrices: The matrices to update in the block. Choose "q", "k", "v", or "mlp".
LoRASurgery( rank: int, block: torch.nn.modules.module.Module, update_matrices: List[str] = ['q', 'v'])
22    def __init__(self, rank: int, block: nn.Module, update_matrices: List[str] = ["q", "v"]):
23        super().__init__()
24        invalid_matrices = set(update_matrices) - {"q", "k", "v", "mlp"}
25        if invalid_matrices:
26            raise ValueError(f"The update matrix names {sorted(invalid_matrices)} are not valid.")
27
28        self.block = block
29        block.attn.qkv = AttentionLoRA(rank=rank, block=block.attn.qkv, update_matrices=update_matrices)
30
31        if "mlp" in update_matrices:
32            block.mlp = MLPLoRA(
33                rank=rank, mlp_layer=block.mlp, get_layers=lambda m: (m.layers[0], m.layers[1], m.act)
34            )

Initialize internal Module state, shared by both nn.Module and ScriptModule.

block
def forward(self, x):
36    def forward(self, x):
37        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.

class SSFSurgery(torch.nn.modules.module.Module):
40class SSFSurgery(nn.Module):
41    """Add scale and shift parameters to each sublayer of a SAM2 Hiera block.
42
43    Args:
44        rank: The unused rank. This argument keeps the PEFT module signatures consistent.
45        block: The Hiera block or PatchEmbed to change.
46    """
47    def __init__(self, rank: int, block: nn.Module):
48        super().__init__()
49        self.block = block
50
51        if hasattr(block, "attn"):
52            block.attn.qkv = ScaleShiftLayer(block.attn.qkv, block.attn.qkv.out_features)
53            block.attn.proj = ScaleShiftLayer(block.attn.proj, block.attn.proj.out_features)
54            block.mlp.layers[0] = ScaleShiftLayer(block.mlp.layers[0], block.mlp.layers[0].out_features)
55            block.mlp.layers[1] = ScaleShiftLayer(block.mlp.layers[1], block.mlp.layers[1].out_features)
56            block.norm1 = ScaleShiftLayer(block.norm1, block.norm1.normalized_shape[0])
57            block.norm2 = ScaleShiftLayer(block.norm2, block.norm2.normalized_shape[0])
58
59        elif hasattr(block, "proj"):
60            block.proj = ScaleShiftLayer(block.proj, block.proj.out_channels)
61
62    def forward(self, x):
63        return x

Add scale and shift parameters to each sublayer of a SAM2 Hiera block.

Arguments:
  • rank: The unused rank. This argument keeps the PEFT module signatures consistent.
  • block: The Hiera block or PatchEmbed to change.
SSFSurgery(rank: int, block: torch.nn.modules.module.Module)
47    def __init__(self, rank: int, block: nn.Module):
48        super().__init__()
49        self.block = block
50
51        if hasattr(block, "attn"):
52            block.attn.qkv = ScaleShiftLayer(block.attn.qkv, block.attn.qkv.out_features)
53            block.attn.proj = ScaleShiftLayer(block.attn.proj, block.attn.proj.out_features)
54            block.mlp.layers[0] = ScaleShiftLayer(block.mlp.layers[0], block.mlp.layers[0].out_features)
55            block.mlp.layers[1] = ScaleShiftLayer(block.mlp.layers[1], block.mlp.layers[1].out_features)
56            block.norm1 = ScaleShiftLayer(block.norm1, block.norm1.normalized_shape[0])
57            block.norm2 = ScaleShiftLayer(block.norm2, block.norm2.normalized_shape[0])
58
59        elif hasattr(block, "proj"):
60            block.proj = ScaleShiftLayer(block.proj, block.proj.out_channels)

Initialize internal Module state, shared by both nn.Module and ScriptModule.

block
def forward(self, x):
62    def forward(self, x):
63        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.

class PEFT_Sam2(torch.nn.modules.module.Module):
 66class PEFT_Sam2(nn.Module):
 67    """Wrap the SAM2 Hiera image encoder for parameter efficient finetuning.
 68
 69    This class freezes the pretrained encoder parameters. It then applies the PEFT method to the selected Hiera blocks.
 70
 71    Args:
 72        model: The Segment Anything 2 model.
 73        rank: The rank for low-rank adaptation.
 74        peft_module: The wrapper for the PEFT method.
 75        attention_layers_to_update: The blocks that use the PEFT method. The default is all blocks.
 76        quantize: The flag that enables 4-bit encoder precision. This option needs CUDA and bitsandbytes.
 77        module_kwargs: The extra arguments for the PEFT module.
 78    """
 79
 80    def __init__(
 81        self,
 82        model: nn.Module,
 83        rank: Optional[int] = None,
 84        peft_module: nn.Module = LoRASurgery,
 85        attention_layers_to_update: Optional[List[int]] = None,
 86        quantize: bool = False,
 87        **module_kwargs,
 88    ):
 89        super().__init__()
 90
 91        if issubclass(peft_module, (LoRASurgery, FacTSurgery)) and (not rank or rank <= 0):
 92            raise RuntimeError(f"The rank {rank} is not valid for {peft_module.__name__}. Pass a positive integer.")
 93
 94        valid_modules = (LoRASurgery, FacTSurgery, SelectiveSurgery, SSFSurgery, AdaptFormer)
 95        if not issubclass(peft_module, valid_modules):
 96            raise ValueError(f"The PEFT module {peft_module.__name__} is not valid.")
 97
 98        blocks = model.image_encoder.trunk.blocks
 99
100        if attention_layers_to_update:
101            self.peft_layers = attention_layers_to_update
102        else:
103            self.peft_layers = list(range(len(blocks)))
104
105        self.peft_module = peft_module
106        self.peft_blocks = []
107
108        if quantize:
109            quantize_linear_layers(model.image_encoder)
110
111        for param in model.image_encoder.parameters():
112            param.requires_grad = False
113
114        if issubclass(self.peft_module, SSFSurgery):
115            self.peft_blocks.append(self.peft_module(rank=rank, block=model.image_encoder.trunk.patch_embed))
116
117        if attention_layers_to_update and (set(attention_layers_to_update) - set(list(range(len(blocks))))):
118            raise ValueError(
119                f"The Hiera block ids {attention_layers_to_update} are not valid for a model with {len(blocks)} blocks."
120            )
121
122        for t_layer_i, blk in enumerate(blocks):
123
124            if t_layer_i not in self.peft_layers:
125                continue
126
127            if issubclass(self.peft_module, SelectiveSurgery):
128                self.peft_blocks.append(self.peft_module(block=blk))
129            else:
130                self.peft_blocks.append(self.peft_module(rank=rank, block=blk, **module_kwargs))
131
132        self.peft_blocks = nn.ModuleList(self.peft_blocks)
133        self.sam = model
134
135    def forward(self, *args, **kwargs):
136        return self.sam(*args, **kwargs)

Wrap the SAM2 Hiera image encoder for parameter efficient finetuning.

This class freezes the pretrained encoder parameters. It then applies the PEFT method to the selected Hiera blocks.

Arguments:
  • model: The Segment Anything 2 model.
  • rank: The rank for low-rank adaptation.
  • peft_module: The wrapper for the PEFT method.
  • attention_layers_to_update: The blocks that use the PEFT method. The default is all blocks.
  • quantize: The flag that enables 4-bit encoder precision. This option needs CUDA and bitsandbytes.
  • module_kwargs: The extra arguments for the PEFT module.
PEFT_Sam2( model: torch.nn.modules.module.Module, rank: Optional[int] = None, peft_module: torch.nn.modules.module.Module = <class 'LoRASurgery'>, attention_layers_to_update: Optional[List[int]] = None, quantize: bool = False, **module_kwargs)
 80    def __init__(
 81        self,
 82        model: nn.Module,
 83        rank: Optional[int] = None,
 84        peft_module: nn.Module = LoRASurgery,
 85        attention_layers_to_update: Optional[List[int]] = None,
 86        quantize: bool = False,
 87        **module_kwargs,
 88    ):
 89        super().__init__()
 90
 91        if issubclass(peft_module, (LoRASurgery, FacTSurgery)) and (not rank or rank <= 0):
 92            raise RuntimeError(f"The rank {rank} is not valid for {peft_module.__name__}. Pass a positive integer.")
 93
 94        valid_modules = (LoRASurgery, FacTSurgery, SelectiveSurgery, SSFSurgery, AdaptFormer)
 95        if not issubclass(peft_module, valid_modules):
 96            raise ValueError(f"The PEFT module {peft_module.__name__} is not valid.")
 97
 98        blocks = model.image_encoder.trunk.blocks
 99
100        if attention_layers_to_update:
101            self.peft_layers = attention_layers_to_update
102        else:
103            self.peft_layers = list(range(len(blocks)))
104
105        self.peft_module = peft_module
106        self.peft_blocks = []
107
108        if quantize:
109            quantize_linear_layers(model.image_encoder)
110
111        for param in model.image_encoder.parameters():
112            param.requires_grad = False
113
114        if issubclass(self.peft_module, SSFSurgery):
115            self.peft_blocks.append(self.peft_module(rank=rank, block=model.image_encoder.trunk.patch_embed))
116
117        if attention_layers_to_update and (set(attention_layers_to_update) - set(list(range(len(blocks))))):
118            raise ValueError(
119                f"The Hiera block ids {attention_layers_to_update} are not valid for a model with {len(blocks)} blocks."
120            )
121
122        for t_layer_i, blk in enumerate(blocks):
123
124            if t_layer_i not in self.peft_layers:
125                continue
126
127            if issubclass(self.peft_module, SelectiveSurgery):
128                self.peft_blocks.append(self.peft_module(block=blk))
129            else:
130                self.peft_blocks.append(self.peft_module(rank=rank, block=blk, **module_kwargs))
131
132        self.peft_blocks = nn.ModuleList(self.peft_blocks)
133        self.sam = model

Initialize internal Module state, shared by both nn.Module and ScriptModule.

peft_module
peft_blocks
sam
def forward(self, *args, **kwargs):
135    def forward(self, *args, **kwargs):
136        return self.sam(*args, **kwargs)

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.

PEFT_MODULES = {'LoRASurgery': <class 'LoRASurgery'>, 'FacTSurgery': <class 'micro_sam.models.peft.FacTSurgery'>, 'SSFSurgery': <class 'SSFSurgery'>, 'AdaptFormer': <class 'micro_sam.models.peft.AdaptFormer'>, 'ClassicalSurgery': <class 'micro_sam.models.peft.ClassicalSurgery'>, 'AttentionSurgery': <class 'micro_sam.models.peft.AttentionSurgery'>, 'BiasSurgery': <class 'micro_sam.models.peft.BiasSurgery'>, 'LayerNormSurgery': <class 'micro_sam.models.peft.LayerNormSurgery'>}