micro_sam.v2.models.util
1from typing import Optional, Union 2 3import torch 4import torch.nn as nn 5 6from torch_em.model.unetr import UNETR3D 7 8from micro_sam.util import get_device 9from micro_sam.v2.util import get_sam2_model 10 11 12class CustomActivation(nn.Module): 13 """Apply sigmoid to foreground and optional auxiliary channels, and tanh to distances.""" 14 def forward(self, x: torch.Tensor) -> torch.Tensor: 15 # In bfloat16 the sigmoid saturates to exactly one from a logit of 6.5, which zeroes the loss gradient. 16 x = x.float() 17 return torch.cat([torch.sigmoid(x[:, :1]), torch.tanh(x[:, 1:4]), torch.sigmoid(x[:, 4:])], dim=1) 18 19 20def joint_unetr_state(state): 21 """The UniSAM2 state of a joint checkpoint. 22 23 The joint trainer saves the SAM2 weights as 'model_state' and the decoder as 'decoder_state'; the encoder of the 24 UniSAM2 is the SAM2 image encoder, stored under the adapter's 'encoder.inner.' prefix. Joint checkpoints from 25 before v6 hold the whole UniSAM2 state as 'unetr_state'. 26 """ 27 if "unetr_state" in state: 28 return state["unetr_state"] 29 prefix = "image_encoder." 30 encoder = { 31 "encoder.inner." + key[len(prefix):]: value 32 for key, value in state["model_state"].items() if key.startswith(prefix) 33 } 34 return {**encoder, **state["decoder_state"]} 35 36 37def read_unisam2_state(state): 38 """The UniSAM2 weights in a loaded checkpoint. 39 40 Args: 41 state: The content of a checkpoint: a joint checkpoint, a training checkpoint with the weights under 42 'model_state', or the weights directly. 43 44 Returns: 45 The UniSAM2 weights, or None if the checkpoint holds no decoder. 46 """ 47 from micro_sam.v2.util import strip_wrapper_prefixes 48 49 if not isinstance(state, dict): 50 return None 51 if "decoder_state" in state or "unetr_state" in state: 52 model_state = joint_unetr_state(state) 53 else: 54 model_state = state.get("model_state", state) 55 if not isinstance(model_state, dict): 56 return None 57 model_state = strip_wrapper_prefixes(model_state) 58 return model_state if "out_conv.weight" in model_state else None 59 60 61class SAM2EncoderAdapter(nn.Module): 62 """Wraps SAM2's ImageEncoder so UNETR3D can call encoder(x)[0]. 63 64 SAM2's ImageEncoder returns a dict; UNETR3D expects integer-indexed access 65 where index 0 is the primary feature tensor. 66 """ 67 def __init__(self, sam2_image_encoder: nn.Module, img_size: int = 1024): 68 super().__init__() 69 self.inner = sam2_image_encoder 70 self.img_size = img_size 71 72 def forward(self, x: torch.Tensor): 73 out = self.inner(x) 74 return [out["vision_features"]] 75 76 77class UniSAM2(UNETR3D): 78 """UNETR-based model for universal (2d + 3d) segmentation. 79 """ 80 def __init__( 81 self, 82 encoder: Union[str, nn.Module] = "hvit_t", 83 output_channels: int = 4, 84 img_size: int = 1024, 85 device: Optional[Union[str, torch.device]] = None, 86 **kwargs, 87 ): 88 device = torch.device("cpu") if device is None else torch.device(get_device(device)) 89 90 # One encoder type for both callers, so the weights land under the same keys either way. 91 if isinstance(encoder, str): 92 encoder = get_sam2_model(model_type=encoder, input_type="images", device=device).image_encoder 93 94 super().__init__( 95 img_size=img_size, 96 backbone="sam2", 97 encoder=SAM2EncoderAdapter(encoder, img_size=img_size), 98 final_activation=CustomActivation(), 99 out_channels=output_channels, 100 use_sam_stats=True, 101 embed_dim=256, 102 use_strip_pooling=True, 103 **kwargs 104 ) 105 self.init_kwargs = { 106 "encoder": encoder, "output_channels": output_channels, "img_size": img_size, 107 **{key: value for key, value in kwargs.items() if key != "encoder_checkpoint"}, 108 } 109 self.to(device) 110 111 112class SemanticSAM2(UNETR3D): 113 """UNETR-based model for semantic (2d + 3d) segmentation. 114 115 The model has no final activation, so it returns the raw class logits that the semantic losses expect. 116 """ 117 def __init__( 118 self, 119 encoder: Union[str, nn.Module] = "hvit_t", 120 num_classes: int = 3, 121 img_size: int = 1024, 122 device: Optional[Union[str, torch.device]] = None, 123 **kwargs, 124 ): 125 device = torch.device("cpu") if device is None else torch.device(get_device(device)) 126 127 # One encoder type for both callers, so the weights land under the same keys either way. 128 if isinstance(encoder, str): 129 encoder = get_sam2_model(model_type=encoder, input_type="images", device=device).image_encoder 130 131 super().__init__( 132 img_size=img_size, 133 backbone="sam2", 134 encoder=SAM2EncoderAdapter(encoder, img_size=img_size), 135 final_activation=None, 136 out_channels=num_classes, 137 use_sam_stats=True, 138 embed_dim=256, 139 use_strip_pooling=True, 140 **kwargs 141 ) 142 self.init_kwargs = { 143 "encoder": encoder, "num_classes": num_classes, "img_size": img_size, 144 **{key: value for key, value in kwargs.items() if key != "encoder_checkpoint"}, 145 } 146 self.to(device)
13class CustomActivation(nn.Module): 14 """Apply sigmoid to foreground and optional auxiliary channels, and tanh to distances.""" 15 def forward(self, x: torch.Tensor) -> torch.Tensor: 16 # In bfloat16 the sigmoid saturates to exactly one from a logit of 6.5, which zeroes the loss gradient. 17 x = x.float() 18 return torch.cat([torch.sigmoid(x[:, :1]), torch.tanh(x[:, 1:4]), torch.sigmoid(x[:, 4:])], dim=1)
Apply sigmoid to foreground and optional auxiliary channels, and tanh to distances.
15 def forward(self, x: torch.Tensor) -> torch.Tensor: 16 # In bfloat16 the sigmoid saturates to exactly one from a logit of 6.5, which zeroes the loss gradient. 17 x = x.float() 18 return torch.cat([torch.sigmoid(x[:, :1]), torch.tanh(x[:, 1:4]), torch.sigmoid(x[:, 4:])], dim=1)
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.
21def joint_unetr_state(state): 22 """The UniSAM2 state of a joint checkpoint. 23 24 The joint trainer saves the SAM2 weights as 'model_state' and the decoder as 'decoder_state'; the encoder of the 25 UniSAM2 is the SAM2 image encoder, stored under the adapter's 'encoder.inner.' prefix. Joint checkpoints from 26 before v6 hold the whole UniSAM2 state as 'unetr_state'. 27 """ 28 if "unetr_state" in state: 29 return state["unetr_state"] 30 prefix = "image_encoder." 31 encoder = { 32 "encoder.inner." + key[len(prefix):]: value 33 for key, value in state["model_state"].items() if key.startswith(prefix) 34 } 35 return {**encoder, **state["decoder_state"]}
The UniSAM2 state of a joint checkpoint.
The joint trainer saves the SAM2 weights as 'model_state' and the decoder as 'decoder_state'; the encoder of the UniSAM2 is the SAM2 image encoder, stored under the adapter's 'encoder.inner.' prefix. Joint checkpoints from before v6 hold the whole UniSAM2 state as 'unetr_state'.
38def read_unisam2_state(state): 39 """The UniSAM2 weights in a loaded checkpoint. 40 41 Args: 42 state: The content of a checkpoint: a joint checkpoint, a training checkpoint with the weights under 43 'model_state', or the weights directly. 44 45 Returns: 46 The UniSAM2 weights, or None if the checkpoint holds no decoder. 47 """ 48 from micro_sam.v2.util import strip_wrapper_prefixes 49 50 if not isinstance(state, dict): 51 return None 52 if "decoder_state" in state or "unetr_state" in state: 53 model_state = joint_unetr_state(state) 54 else: 55 model_state = state.get("model_state", state) 56 if not isinstance(model_state, dict): 57 return None 58 model_state = strip_wrapper_prefixes(model_state) 59 return model_state if "out_conv.weight" in model_state else None
The UniSAM2 weights in a loaded checkpoint.
Arguments:
- state: The content of a checkpoint: a joint checkpoint, a training checkpoint with the weights under 'model_state', or the weights directly.
Returns:
The UniSAM2 weights, or None if the checkpoint holds no decoder.
62class SAM2EncoderAdapter(nn.Module): 63 """Wraps SAM2's ImageEncoder so UNETR3D can call encoder(x)[0]. 64 65 SAM2's ImageEncoder returns a dict; UNETR3D expects integer-indexed access 66 where index 0 is the primary feature tensor. 67 """ 68 def __init__(self, sam2_image_encoder: nn.Module, img_size: int = 1024): 69 super().__init__() 70 self.inner = sam2_image_encoder 71 self.img_size = img_size 72 73 def forward(self, x: torch.Tensor): 74 out = self.inner(x) 75 return [out["vision_features"]]
Wraps SAM2's ImageEncoder so UNETR3D can call encoder(x)[0].
SAM2's ImageEncoder returns a dict; UNETR3D expects integer-indexed access where index 0 is the primary feature tensor.
68 def __init__(self, sam2_image_encoder: nn.Module, img_size: int = 1024): 69 super().__init__() 70 self.inner = sam2_image_encoder 71 self.img_size = img_size
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.
78class UniSAM2(UNETR3D): 79 """UNETR-based model for universal (2d + 3d) segmentation. 80 """ 81 def __init__( 82 self, 83 encoder: Union[str, nn.Module] = "hvit_t", 84 output_channels: int = 4, 85 img_size: int = 1024, 86 device: Optional[Union[str, torch.device]] = None, 87 **kwargs, 88 ): 89 device = torch.device("cpu") if device is None else torch.device(get_device(device)) 90 91 # One encoder type for both callers, so the weights land under the same keys either way. 92 if isinstance(encoder, str): 93 encoder = get_sam2_model(model_type=encoder, input_type="images", device=device).image_encoder 94 95 super().__init__( 96 img_size=img_size, 97 backbone="sam2", 98 encoder=SAM2EncoderAdapter(encoder, img_size=img_size), 99 final_activation=CustomActivation(), 100 out_channels=output_channels, 101 use_sam_stats=True, 102 embed_dim=256, 103 use_strip_pooling=True, 104 **kwargs 105 ) 106 self.init_kwargs = { 107 "encoder": encoder, "output_channels": output_channels, "img_size": img_size, 108 **{key: value for key, value in kwargs.items() if key != "encoder_checkpoint"}, 109 } 110 self.to(device)
UNETR-based model for universal (2d + 3d) segmentation.
81 def __init__( 82 self, 83 encoder: Union[str, nn.Module] = "hvit_t", 84 output_channels: int = 4, 85 img_size: int = 1024, 86 device: Optional[Union[str, torch.device]] = None, 87 **kwargs, 88 ): 89 device = torch.device("cpu") if device is None else torch.device(get_device(device)) 90 91 # One encoder type for both callers, so the weights land under the same keys either way. 92 if isinstance(encoder, str): 93 encoder = get_sam2_model(model_type=encoder, input_type="images", device=device).image_encoder 94 95 super().__init__( 96 img_size=img_size, 97 backbone="sam2", 98 encoder=SAM2EncoderAdapter(encoder, img_size=img_size), 99 final_activation=CustomActivation(), 100 out_channels=output_channels, 101 use_sam_stats=True, 102 embed_dim=256, 103 use_strip_pooling=True, 104 **kwargs 105 ) 106 self.init_kwargs = { 107 "encoder": encoder, "output_channels": output_channels, "img_size": img_size, 108 **{key: value for key, value in kwargs.items() if key != "encoder_checkpoint"}, 109 } 110 self.to(device)
Initialize internal Module state, shared by both nn.Module and ScriptModule.
113class SemanticSAM2(UNETR3D): 114 """UNETR-based model for semantic (2d + 3d) segmentation. 115 116 The model has no final activation, so it returns the raw class logits that the semantic losses expect. 117 """ 118 def __init__( 119 self, 120 encoder: Union[str, nn.Module] = "hvit_t", 121 num_classes: int = 3, 122 img_size: int = 1024, 123 device: Optional[Union[str, torch.device]] = None, 124 **kwargs, 125 ): 126 device = torch.device("cpu") if device is None else torch.device(get_device(device)) 127 128 # One encoder type for both callers, so the weights land under the same keys either way. 129 if isinstance(encoder, str): 130 encoder = get_sam2_model(model_type=encoder, input_type="images", device=device).image_encoder 131 132 super().__init__( 133 img_size=img_size, 134 backbone="sam2", 135 encoder=SAM2EncoderAdapter(encoder, img_size=img_size), 136 final_activation=None, 137 out_channels=num_classes, 138 use_sam_stats=True, 139 embed_dim=256, 140 use_strip_pooling=True, 141 **kwargs 142 ) 143 self.init_kwargs = { 144 "encoder": encoder, "num_classes": num_classes, "img_size": img_size, 145 **{key: value for key, value in kwargs.items() if key != "encoder_checkpoint"}, 146 } 147 self.to(device)
UNETR-based model for semantic (2d + 3d) segmentation.
The model has no final activation, so it returns the raw class logits that the semantic losses expect.
118 def __init__( 119 self, 120 encoder: Union[str, nn.Module] = "hvit_t", 121 num_classes: int = 3, 122 img_size: int = 1024, 123 device: Optional[Union[str, torch.device]] = None, 124 **kwargs, 125 ): 126 device = torch.device("cpu") if device is None else torch.device(get_device(device)) 127 128 # One encoder type for both callers, so the weights land under the same keys either way. 129 if isinstance(encoder, str): 130 encoder = get_sam2_model(model_type=encoder, input_type="images", device=device).image_encoder 131 132 super().__init__( 133 img_size=img_size, 134 backbone="sam2", 135 encoder=SAM2EncoderAdapter(encoder, img_size=img_size), 136 final_activation=None, 137 out_channels=num_classes, 138 use_sam_stats=True, 139 embed_dim=256, 140 use_strip_pooling=True, 141 **kwargs 142 ) 143 self.init_kwargs = { 144 "encoder": encoder, "num_classes": num_classes, "img_size": img_size, 145 **{key: value for key, value in kwargs.items() if key != "encoder_checkpoint"}, 146 } 147 self.to(device)
Initialize internal Module state, shared by both nn.Module and ScriptModule.