configuration_sam2.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298
  1. # Copyright 2025 The HuggingFace Inc. team. All rights reserved.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. """SAM2 model configuration"""
  15. from huggingface_hub.dataclasses import strict
  16. from ...configuration_utils import PreTrainedConfig
  17. from ...utils import auto_docstring
  18. from ..auto import CONFIG_MAPPING, AutoConfig
  19. @auto_docstring(checkpoint="facebook/sam2.1-hiera-tiny")
  20. @strict
  21. class Sam2HieraDetConfig(PreTrainedConfig):
  22. r"""
  23. patch_kernel_size (`list[int]`, *optional*, defaults to `[7, 7]`):
  24. The kernel size of the patch.
  25. patch_stride (`list[int]`, *optional*, defaults to `[4, 4]`):
  26. The stride of the patch.
  27. patch_padding (`list[int]`, *optional*, defaults to `[3, 3]`):
  28. The padding of the patch.
  29. query_stride (`list[int]`, *optional*, defaults to `[2, 2]`):
  30. The downsample stride between stages.
  31. window_positional_embedding_background_size (`list[int]`, *optional*, defaults to `[7, 7]`):
  32. The window size per stage when not using global attention.
  33. num_query_pool_stages (`int`, *optional*, defaults to 3):
  34. The number of query pool stages.
  35. blocks_per_stage (`list[int]`, *optional*, defaults to `[1, 2, 7, 2]`):
  36. The number of blocks per stage.
  37. embed_dim_per_stage (`list[int]`, *optional*, defaults to `[96, 192, 384, 768]`):
  38. The embedding dimension per stage.
  39. num_attention_heads_per_stage (`list[int]`, *optional*, defaults to `[1, 2, 4, 8]`):
  40. The number of attention heads per stage.
  41. window_size_per_stage (`list[int]`, *optional*, defaults to `[8, 4, 14, 7]`):
  42. The window size per stage.
  43. global_attention_blocks (`list[int]`, *optional*, defaults to `[5, 7, 9]`):
  44. The blocks where global attention is used.
  45. """
  46. base_config_key = "backbone_config"
  47. model_type = "sam2_hiera_det_model"
  48. hidden_size: int = 96
  49. num_attention_heads: int = 1
  50. num_channels: int = 3
  51. image_size: int | list[int] | None = None
  52. patch_kernel_size: int | list[int] | None = None
  53. patch_stride: int | list[int] | None = None
  54. patch_padding: int | list[int] | None = None
  55. query_stride: int | list[int] | None = None
  56. window_positional_embedding_background_size: list[int] | None = None
  57. num_query_pool_stages: int = 3
  58. blocks_per_stage: list[int] | None = None
  59. embed_dim_per_stage: list[int] | None = None
  60. num_attention_heads_per_stage: list[int] | None = None
  61. window_size_per_stage: list[int] | None = None
  62. global_attention_blocks: list[int] | None = None
  63. mlp_ratio: float = 4.0
  64. hidden_act: str = "gelu"
  65. layer_norm_eps: float = 1e-6
  66. initializer_range: float = 0.02
  67. def __post_init__(self, **kwargs):
  68. self.image_size = self.image_size if self.image_size is not None else [1024, 1024]
  69. self.patch_kernel_size = self.patch_kernel_size if self.patch_kernel_size is not None else [7, 7]
  70. self.patch_stride = self.patch_stride if self.patch_stride is not None else [4, 4]
  71. self.patch_padding = self.patch_padding if self.patch_padding is not None else [3, 3]
  72. self.query_stride = self.query_stride if self.query_stride is not None else [2, 2]
  73. self.window_positional_embedding_background_size = (
  74. self.window_positional_embedding_background_size
  75. if self.window_positional_embedding_background_size is not None
  76. else [7, 7]
  77. )
  78. self.blocks_per_stage = self.blocks_per_stage if self.blocks_per_stage is not None else [1, 2, 7, 2]
  79. self.embed_dim_per_stage = (
  80. self.embed_dim_per_stage if self.embed_dim_per_stage is not None else [96, 192, 384, 768]
  81. )
  82. self.num_attention_heads_per_stage = (
  83. self.num_attention_heads_per_stage if self.num_attention_heads_per_stage is not None else [1, 2, 4, 8]
  84. )
  85. self.window_size_per_stage = (
  86. self.window_size_per_stage if self.window_size_per_stage is not None else [8, 4, 14, 7]
  87. )
  88. self.global_attention_blocks = (
  89. self.global_attention_blocks if self.global_attention_blocks is not None else [5, 7, 9]
  90. )
  91. super().__post_init__(**kwargs)
  92. @auto_docstring(checkpoint="facebook/sam2.1-hiera-tiny")
  93. @strict
  94. class Sam2VisionConfig(PreTrainedConfig):
  95. r"""
  96. backbone_channel_list (`List[int]`, *optional*, defaults to `[768, 384, 192, 96]`):
  97. The list of channel dimensions for the backbone.
  98. backbone_feature_sizes (`List[List[int]]`, *optional*, defaults to `[[256, 256], [128, 128], [64, 64]]`):
  99. The spatial sizes of the feature maps from the backbone.
  100. fpn_hidden_size (`int`, *optional*, defaults to 256):
  101. The hidden dimension of the FPN.
  102. fpn_kernel_size (`int`, *optional*, defaults to 1):
  103. The kernel size for the convolutions in the neck.
  104. fpn_stride (`int`, *optional*, defaults to 1):
  105. The stride for the convolutions in the neck.
  106. fpn_padding (`int`, *optional*, defaults to 0):
  107. The padding for the convolutions in the neck.
  108. fpn_top_down_levels (`List[int]`, *optional*, defaults to `[2, 3]`):
  109. The levels for the top-down FPN connections.
  110. num_feature_levels (`int`, *optional*, defaults to 3):
  111. The number of feature levels from the FPN to use.
  112. """
  113. base_config_key = "vision_config"
  114. model_type = "sam2_vision_model"
  115. sub_configs = {
  116. "backbone_config": AutoConfig,
  117. }
  118. backbone_config: dict | PreTrainedConfig | None = None
  119. backbone_channel_list: list[int] | None = None
  120. backbone_feature_sizes: list | None = None
  121. fpn_hidden_size: int = 256
  122. fpn_kernel_size: int = 1
  123. fpn_stride: int = 1
  124. fpn_padding: int = 0
  125. fpn_top_down_levels: list[int] | None = None
  126. num_feature_levels: int = 3
  127. hidden_act: str = "gelu"
  128. layer_norm_eps: float = 1e-6
  129. initializer_range: float = 0.02
  130. def __post_init__(self, **kwargs):
  131. self.backbone_channel_list = (
  132. [768, 384, 192, 96] if self.backbone_channel_list is None else self.backbone_channel_list
  133. )
  134. self.backbone_feature_sizes = (
  135. [[256, 256], [128, 128], [64, 64]] if self.backbone_feature_sizes is None else self.backbone_feature_sizes
  136. )
  137. self.fpn_top_down_levels = [2, 3] if self.fpn_top_down_levels is None else self.fpn_top_down_levels
  138. if isinstance(self.backbone_config, dict):
  139. self.backbone_config["model_type"] = self.backbone_config.get("model_type", "sam2_hiera_det_model")
  140. self.backbone_config = CONFIG_MAPPING[self.backbone_config["model_type"]](**self.backbone_config)
  141. elif self.backbone_config is None:
  142. self.backbone_config = Sam2HieraDetConfig()
  143. super().__post_init__(**kwargs)
  144. @auto_docstring(checkpoint="facebook/sam2.1-hiera-tiny")
  145. @strict
  146. class Sam2PromptEncoderConfig(PreTrainedConfig):
  147. r"""
  148. mask_input_channels (`int`, *optional*, defaults to 16):
  149. The number of channels to be fed to the `MaskDecoder` module.
  150. num_point_embeddings (`int`, *optional*, defaults to 4):
  151. The number of point embeddings to be used.
  152. scale (`float`, *optional*, defaults to 1):
  153. The scale factor for the prompt encoder.
  154. """
  155. base_config_key = "prompt_encoder_config"
  156. hidden_size: int = 256
  157. image_size: int | list[int] | tuple[int, int] = 1024
  158. patch_size: int | list[int] | tuple[int, int] = 16
  159. mask_input_channels: int = 16
  160. num_point_embeddings: int = 4
  161. hidden_act: str = "gelu"
  162. layer_norm_eps: float = 1e-6
  163. scale: int = 1
  164. @auto_docstring(checkpoint="facebook/sam2.1-hiera-tiny")
  165. @strict
  166. class Sam2MaskDecoderConfig(PreTrainedConfig):
  167. r"""
  168. mlp_dim (`int`, *optional*, defaults to 2048):
  169. The dimension of the MLP in the two-way transformer.
  170. attention_downsample_rate (`int`, *optional*, defaults to 2):
  171. The downsample rate for the attention layers.
  172. num_multimask_outputs (`int`, *optional*, defaults to 3):
  173. The number of multimask outputs.
  174. iou_head_depth (`int`, *optional*, defaults to 3):
  175. The depth of the IoU head.
  176. iou_head_hidden_dim (`int`, *optional*, defaults to 256):
  177. The hidden dimension of the IoU head.
  178. dynamic_multimask_via_stability (`bool`, *optional*, defaults to `True`):
  179. Whether to use dynamic multimask via stability.
  180. dynamic_multimask_stability_delta (`float`, *optional*, defaults to 0.05):
  181. The stability delta for the dynamic multimask.
  182. dynamic_multimask_stability_thresh (`float`, *optional*, defaults to 0.98):
  183. The stability threshold for the dynamic multimask.
  184. """
  185. base_config_key = "mask_decoder_config"
  186. hidden_size: int = 256
  187. hidden_act: str = "gelu"
  188. mlp_dim: int = 2048
  189. num_hidden_layers: int = 2
  190. num_attention_heads: int = 8
  191. attention_downsample_rate: int = 2
  192. num_multimask_outputs: int = 3
  193. iou_head_depth: int = 3
  194. iou_head_hidden_dim: int = 256
  195. dynamic_multimask_via_stability: bool = True
  196. dynamic_multimask_stability_delta: float = 0.05
  197. dynamic_multimask_stability_thresh: float = 0.98
  198. @auto_docstring(checkpoint="facebook/sam2.1-hiera-tiny")
  199. @strict
  200. class Sam2Config(PreTrainedConfig):
  201. r"""
  202. prompt_encoder_config (Union[`dict`, `Sam2PromptEncoderConfig`], *optional*):
  203. Dictionary of configuration options used to initialize [`Sam2PromptEncoderConfig`].
  204. mask_decoder_config (Union[`dict`, `Sam2MaskDecoderConfig`], *optional*):
  205. Dictionary of configuration options used to initialize [`Sam2MaskDecoderConfig`].
  206. Example:
  207. ```python
  208. >>> from transformers import (
  209. ... Sam2VisionConfig,
  210. ... Sam2PromptEncoderConfig,
  211. ... Sam2MaskDecoderConfig,
  212. ... Sam2Model,
  213. ... )
  214. >>> # Initializing a Sam2Config with `"facebook/sam2.1_hiera_tiny"` style configuration
  215. >>> configuration = Sam2Config()
  216. >>> # Initializing a Sam2Model (with random weights) from the `"facebook/sam2.1_hiera_tiny"` style configuration
  217. >>> model = Sam2Model(configuration)
  218. >>> # Accessing the model configuration
  219. >>> configuration = model.config
  220. >>> # We can also initialize a Sam2Config from a Sam2VisionConfig, Sam2PromptEncoderConfig, and Sam2MaskDecoderConfig
  221. >>> # Initializing SAM2 vision encoder, memory attention, and memory encoder configurations
  222. >>> vision_config = Sam2VisionConfig()
  223. >>> prompt_encoder_config = Sam2PromptEncoderConfig()
  224. >>> mask_decoder_config = Sam2MaskDecoderConfig()
  225. >>> config = Sam2Config(vision_config, prompt_encoder_config, mask_decoder_config)
  226. ```"""
  227. model_type = "sam2"
  228. sub_configs = {
  229. "vision_config": AutoConfig,
  230. "prompt_encoder_config": Sam2PromptEncoderConfig,
  231. "mask_decoder_config": Sam2MaskDecoderConfig,
  232. }
  233. vision_config: dict | PreTrainedConfig | None = None
  234. prompt_encoder_config: dict | PreTrainedConfig | None = None
  235. mask_decoder_config: dict | PreTrainedConfig | None = None
  236. initializer_range: float = 0.02
  237. def __post_init__(self, **kwargs):
  238. if isinstance(self.vision_config, dict):
  239. self.vision_config["model_type"] = self.vision_config.get("model_type", "sam2_vision_model")
  240. self.vision_config = CONFIG_MAPPING[self.vision_config["model_type"]](**self.vision_config)
  241. elif self.vision_config is None:
  242. self.vision_config = CONFIG_MAPPING["sam2_vision_model"]()
  243. if isinstance(self.prompt_encoder_config, dict):
  244. self.prompt_encoder_config = Sam2PromptEncoderConfig(**self.prompt_encoder_config)
  245. elif self.prompt_encoder_config is None:
  246. self.prompt_encoder_config = Sam2PromptEncoderConfig()
  247. if isinstance(self.mask_decoder_config, dict):
  248. self.mask_decoder_config = Sam2MaskDecoderConfig(**self.mask_decoder_config)
  249. elif self.mask_decoder_config is None:
  250. self.mask_decoder_config = Sam2MaskDecoderConfig()
  251. super().__post_init__(**kwargs)
  252. __all__ = [
  253. "Sam2Config",
  254. "Sam2HieraDetConfig",
  255. "Sam2VisionConfig",
  256. "Sam2PromptEncoderConfig",
  257. "Sam2MaskDecoderConfig",
  258. ]