configuration_edgetam.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332
  1. # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
  2. # This file was automatically generated from src/transformers/models/edgetam/modular_edgetam.py.
  3. # Do NOT edit this file manually as any edits will be overwritten by the generation of
  4. # the file from the modular. If any change should be done, please apply the change to the
  5. # modular_edgetam.py file directly. One of our CI enforces this.
  6. # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
  7. # coding=utf-8
  8. # Copyright 2025 The Meta AI Authors and The HuggingFace Team. All rights reserved.
  9. #
  10. # Licensed under the Apache License, Version 2.0 (the "License");
  11. # you may not use this file except in compliance with the License.
  12. # You may obtain a copy of the License at
  13. #
  14. # http://www.apache.org/licenses/LICENSE-2.0
  15. #
  16. # Unless required by applicable law or agreed to in writing, software
  17. # distributed under the License is distributed on an "AS IS" BASIS,
  18. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  19. # See the License for the specific language governing permissions and
  20. # limitations under the License.
  21. from ...configuration_utils import PretrainedConfig
  22. from ..auto import CONFIG_MAPPING, AutoConfig
  23. class EdgeTamVisionConfig(PretrainedConfig):
  24. r"""
  25. This is the configuration class to store the configuration of a [`EdgeTamVisionModel`]. It is used to instantiate a SAM
  26. vision encoder according to the specified arguments, defining the model architecture. Instantiating a configuration
  27. defaults will yield a similar configuration to that of SAM 2.1 Hiera-tiny
  28. [facebook/EdgeTAM](https://huggingface.co/facebook/EdgeTAM) architecture.
  29. Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
  30. documentation from [`PretrainedConfig`] for more information.
  31. Args:
  32. backbone_config (`Union[dict, "PretrainedConfig"]`, *optional*):
  33. Configuration for the vision backbone. This is used to instantiate the backbone using
  34. `AutoModel.from_config`.
  35. backbone_channel_list (`List[int]`, *optional*, defaults to `[384, 192, 96, 48]`):
  36. The list of channel dimensions for the backbone.
  37. backbone_feature_sizes (`List[List[int]]`, *optional*, defaults to `[[256, 256], [128, 128], [64, 64]]`):
  38. The spatial sizes of the feature maps from the backbone.
  39. fpn_hidden_size (`int`, *optional*, defaults to 256):
  40. The hidden dimension of the FPN.
  41. fpn_kernel_size (`int`, *optional*, defaults to 1):
  42. The kernel size for the convolutions in the neck.
  43. fpn_stride (`int`, *optional*, defaults to 1):
  44. The stride for the convolutions in the neck.
  45. fpn_padding (`int`, *optional*, defaults to 0):
  46. The padding for the convolutions in the neck.
  47. fpn_top_down_levels (`List[int]`, *optional*, defaults to `[2, 3]`):
  48. The levels for the top-down FPN connections.
  49. num_feature_levels (`int`, *optional*, defaults to 3):
  50. The number of feature levels from the FPN to use.
  51. hidden_act (`str`, *optional*, defaults to `"gelu"`):
  52. The non-linear activation function in the neck.
  53. layer_norm_eps (`float`, *optional*, defaults to 1e-06):
  54. The epsilon for the layer normalization.
  55. initializer_range (`float`, *optional*, defaults to 0.02):
  56. The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
  57. """
  58. base_config_key = "vision_config"
  59. model_type = "edgetam_vision_model"
  60. sub_configs = {
  61. "backbone_config": AutoConfig,
  62. }
  63. def __init__(
  64. self,
  65. backbone_config=None,
  66. backbone_channel_list=None,
  67. backbone_feature_sizes=None,
  68. fpn_hidden_size=256,
  69. fpn_kernel_size=1,
  70. fpn_stride=1,
  71. fpn_padding=0,
  72. fpn_top_down_levels=None,
  73. num_feature_levels=3,
  74. hidden_act="gelu",
  75. layer_norm_eps=1e-6,
  76. initializer_range=0.02,
  77. **kwargs,
  78. ):
  79. super().__init__(**kwargs)
  80. backbone_channel_list = [384, 192, 96, 48] if backbone_channel_list is None else backbone_channel_list
  81. backbone_feature_sizes = (
  82. [[256, 256], [128, 128], [64, 64]] if backbone_feature_sizes is None else backbone_feature_sizes
  83. )
  84. fpn_top_down_levels = [2, 3] if fpn_top_down_levels is None else fpn_top_down_levels
  85. if isinstance(backbone_config, dict):
  86. backbone_config["model_type"] = backbone_config.get("model_type", "timm_wrapper")
  87. backbone_config = CONFIG_MAPPING[backbone_config["model_type"]](**backbone_config)
  88. elif isinstance(backbone_config, AutoConfig):
  89. backbone_config = backbone_config
  90. elif backbone_config is None:
  91. backbone_config = AutoConfig.from_pretrained(
  92. "timm/repvit_m1.dist_in1k",
  93. model_args={"in_chans": 3, "features_only": True, "out_indices": [0, 1, 2, 3]},
  94. )
  95. self.backbone_config = backbone_config
  96. # Neck
  97. self.backbone_channel_list = backbone_channel_list
  98. self.backbone_feature_sizes = backbone_feature_sizes
  99. self.fpn_hidden_size = fpn_hidden_size
  100. self.fpn_kernel_size = fpn_kernel_size
  101. self.fpn_stride = fpn_stride
  102. self.fpn_padding = fpn_padding
  103. self.fpn_top_down_levels = fpn_top_down_levels
  104. self.num_feature_levels = num_feature_levels
  105. self.hidden_act = hidden_act
  106. self.layer_norm_eps = layer_norm_eps
  107. self.initializer_range = initializer_range
  108. class EdgeTamPromptEncoderConfig(PretrainedConfig):
  109. r"""
  110. This is the configuration class to store the configuration of a [`EdgeTamPromptEncoder`]. The [`EdgeTamPromptEncoder`]
  111. module is used to encode the input 2D points and bounding boxes.
  112. Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
  113. documentation from [`PretrainedConfig`] for more information.
  114. Args:
  115. hidden_size (`int`, *optional*, defaults to 256):
  116. Dimensionality of the hidden states.
  117. image_size (`int`, *optional*, defaults to 1024):
  118. The expected output resolution of the image.
  119. patch_size (`int`, *optional*, defaults to 16):
  120. The size (resolution) of each patch.
  121. mask_input_channels (`int`, *optional*, defaults to 16):
  122. The number of channels to be fed to the `MaskDecoder` module.
  123. num_point_embeddings (`int`, *optional*, defaults to 4):
  124. The number of point embeddings to be used.
  125. hidden_act (`str`, *optional*, defaults to `"gelu"`):
  126. The non-linear activation function in the encoder and pooler.
  127. layer_norm_eps (`float`, *optional*, defaults to 1e-06):
  128. The epsilon used by the layer normalization layers.
  129. scale (`float`, *optional*, defaults to 1):
  130. The scale factor for the prompt encoder.
  131. """
  132. base_config_key = "prompt_encoder_config"
  133. def __init__(
  134. self,
  135. hidden_size=256,
  136. image_size=1024,
  137. patch_size=16,
  138. mask_input_channels=16,
  139. num_point_embeddings=4,
  140. hidden_act="gelu",
  141. layer_norm_eps=1e-6,
  142. scale=1,
  143. **kwargs,
  144. ):
  145. super().__init__(**kwargs)
  146. self.hidden_size = hidden_size
  147. self.image_size = image_size
  148. self.patch_size = patch_size
  149. self.mask_input_channels = mask_input_channels
  150. self.num_point_embeddings = num_point_embeddings
  151. self.hidden_act = hidden_act
  152. self.layer_norm_eps = layer_norm_eps
  153. self.scale = scale
  154. class EdgeTamMaskDecoderConfig(PretrainedConfig):
  155. r"""
  156. This is the configuration class to store the configuration of a [`EdgeTamMaskDecoder`]. It is used to instantiate a EDGETAM
  157. memory encoder according to the specified arguments, defining the model architecture.
  158. Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
  159. documentation from [`PretrainedConfig`] for more information.
  160. Args:
  161. hidden_size (`int`, *optional*, defaults to 256):
  162. Dimensionality of the hidden states.
  163. hidden_act (`str`, *optional*, defaults to `"gelu"`):
  164. The non-linear activation function in the EDGETAM mask decoder.
  165. mlp_dim (`int`, *optional*, defaults to 2048):
  166. The dimension of the MLP in the two-way transformer.
  167. num_hidden_layers (`int`, *optional*, defaults to 2):
  168. The number of hidden layers in the two-way transformer.
  169. num_attention_heads (`int`, *optional*, defaults to 8):
  170. The number of attention heads in the two-way transformer.
  171. attention_downsample_rate (`int`, *optional*, defaults to 2):
  172. The downsample rate for the attention layers.
  173. num_multimask_outputs (`int`, *optional*, defaults to 3):
  174. The number of multimask outputs.
  175. iou_head_depth (`int`, *optional*, defaults to 3):
  176. The depth of the IoU head.
  177. iou_head_hidden_dim (`int`, *optional*, defaults to 256):
  178. The hidden dimension of the IoU head.
  179. dynamic_multimask_via_stability (`bool`, *optional*, defaults to `True`):
  180. Whether to use dynamic multimask via stability.
  181. dynamic_multimask_stability_delta (`float`, *optional*, defaults to 0.05):
  182. The stability delta for the dynamic multimask.
  183. dynamic_multimask_stability_thresh (`float`, *optional*, defaults to 0.98):
  184. The stability threshold for the dynamic multimask.
  185. """
  186. base_config_key = "mask_decoder_config"
  187. def __init__(
  188. self,
  189. hidden_size=256,
  190. hidden_act="gelu",
  191. mlp_dim=2048,
  192. num_hidden_layers=2,
  193. num_attention_heads=8,
  194. attention_downsample_rate=2,
  195. num_multimask_outputs=3,
  196. iou_head_depth=3,
  197. iou_head_hidden_dim=256,
  198. dynamic_multimask_via_stability=True,
  199. dynamic_multimask_stability_delta=0.05,
  200. dynamic_multimask_stability_thresh=0.98,
  201. **kwargs,
  202. ):
  203. super().__init__(**kwargs)
  204. self.hidden_size = hidden_size
  205. self.num_multimask_outputs = num_multimask_outputs
  206. self.hidden_act = hidden_act
  207. self.iou_head_depth = iou_head_depth
  208. self.iou_head_hidden_dim = iou_head_hidden_dim
  209. self.dynamic_multimask_via_stability = dynamic_multimask_via_stability
  210. self.dynamic_multimask_stability_delta = dynamic_multimask_stability_delta
  211. self.dynamic_multimask_stability_thresh = dynamic_multimask_stability_thresh
  212. # TwoWayTransformer configuration
  213. self.num_hidden_layers = num_hidden_layers
  214. self.hidden_size = hidden_size
  215. self.num_attention_heads = num_attention_heads
  216. self.mlp_dim = mlp_dim
  217. self.attention_downsample_rate = attention_downsample_rate
  218. class EdgeTamConfig(PretrainedConfig):
  219. r"""
  220. [`EdgeTamConfig`] is the configuration class to store the configuration of a [`EdgeTamModel`]. It is used to instantiate a
  221. EDGETAM model according to the specified arguments, defining the memory attention, memory encoder, and image encoder
  222. configs. Instantiating a configuration defaults will yield a similar configuration to that of the SAM 2.1 Hiera-tiny
  223. [facebook/edgetam.1-hiera-tiny](https://huggingface.co/facebook/edgetam.1-hiera-tiny) architecture.
  224. Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
  225. documentation from [`PretrainedConfig`] for more information.
  226. Args:
  227. vision_config (Union[`dict`, `EdgeTamVisionConfig`], *optional*):
  228. Dictionary of configuration options used to initialize [`EdgeTamVisionConfig`].
  229. prompt_encoder_config (Union[`dict`, `EdgeTamPromptEncoderConfig`], *optional*):
  230. Dictionary of configuration options used to initialize [`EdgeTamPromptEncoderConfig`].
  231. mask_decoder_config (Union[`dict`, `EdgeTamMaskDecoderConfig`], *optional*):
  232. Dictionary of configuration options used to initialize [`EdgeTamMaskDecoderConfig`].
  233. initializer_range (`float`, *optional*, defaults to 0.02):
  234. Standard deviation for parameter initialization.
  235. Example:
  236. ```python
  237. >>> from transformers import (
  238. ... EdgeTamVisionConfig,
  239. ... EdgeTamPromptEncoderConfig,
  240. ... EdgeTamMaskDecoderConfig,
  241. ... EdgeTamModel,
  242. ... )
  243. >>> # Initializing a EdgeTamConfig with `"facebook/edgetam.1_hiera_tiny"` style configuration
  244. >>> configuration = EdgeTamconfig()
  245. >>> # Initializing a EdgeTamModel (with random weights) from the `"facebook/edgetam.1_hiera_tiny"` style configuration
  246. >>> model = EdgeTamModel(configuration)
  247. >>> # Accessing the model configuration
  248. >>> configuration = model.config
  249. >>> # We can also initialize a EdgeTamConfig from a EdgeTamVisionConfig, EdgeTamPromptEncoderConfig, and EdgeTamMaskDecoderConfig
  250. >>> # Initializing EDGETAM vision encoder, memory attention, and memory encoder configurations
  251. >>> vision_config = EdgeTamVisionConfig()
  252. >>> prompt_encoder_config = EdgeTamPromptEncoderConfig()
  253. >>> mask_decoder_config = EdgeTamMaskDecoderConfig()
  254. >>> config = EdgeTamConfig(vision_config, prompt_encoder_config, mask_decoder_config)
  255. ```"""
  256. model_type = "edgetam"
  257. sub_configs = {
  258. "vision_config": AutoConfig,
  259. "prompt_encoder_config": EdgeTamPromptEncoderConfig,
  260. "mask_decoder_config": EdgeTamMaskDecoderConfig,
  261. }
  262. def __init__(
  263. self,
  264. vision_config=None,
  265. prompt_encoder_config=None,
  266. mask_decoder_config=None,
  267. initializer_range=0.02,
  268. **kwargs,
  269. ):
  270. super().__init__(**kwargs)
  271. vision_config = vision_config if vision_config is not None else {}
  272. prompt_encoder_config = prompt_encoder_config if prompt_encoder_config is not None else {}
  273. mask_decoder_config = mask_decoder_config if mask_decoder_config is not None else {}
  274. if isinstance(vision_config, dict):
  275. vision_config["model_type"] = vision_config.get("model_type", "edgetam_vision_model")
  276. vision_config = CONFIG_MAPPING[vision_config["model_type"]](**vision_config)
  277. if isinstance(prompt_encoder_config, EdgeTamPromptEncoderConfig):
  278. prompt_encoder_config = prompt_encoder_config.to_dict()
  279. if isinstance(mask_decoder_config, EdgeTamMaskDecoderConfig):
  280. mask_decoder_config = mask_decoder_config.to_dict()
  281. self.vision_config = vision_config
  282. self.prompt_encoder_config = EdgeTamPromptEncoderConfig(**prompt_encoder_config)
  283. self.mask_decoder_config = EdgeTamMaskDecoderConfig(**mask_decoder_config)
  284. self.initializer_range = initializer_range
  285. __all__ = ["EdgeTamConfig", "EdgeTamVisionConfig", "EdgeTamPromptEncoderConfig", "EdgeTamMaskDecoderConfig"]