configuration_sam.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305
  1. # coding=utf-8
  2. # Copyright 2023 The HuggingFace Inc. team. All rights reserved.
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. """SAM model configuration"""
  16. from ...configuration_utils import PretrainedConfig
  17. from ...utils import logging
  18. logger = logging.get_logger(__name__)
  19. class SamPromptEncoderConfig(PretrainedConfig):
  20. r"""
  21. This is the configuration class to store the configuration of a [`SamPromptEncoder`]. The [`SamPromptEncoder`]
  22. module is used to encode the input 2D points and bounding boxes. Instantiating a configuration defaults will yield
  23. a similar configuration to that of the SAM-vit-h
  24. [facebook/sam-vit-huge](https://huggingface.co/facebook/sam-vit-huge) architecture.
  25. Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
  26. documentation from [`PretrainedConfig`] for more information.
  27. Args:
  28. hidden_size (`int`, *optional*, defaults to 256):
  29. Dimensionality of the hidden states.
  30. image_size (`int`, *optional*, defaults to 1024):
  31. The expected output resolution of the image.
  32. patch_size (`int`, *optional*, defaults to 16):
  33. The size (resolution) of each patch.
  34. mask_input_channels (`int`, *optional*, defaults to 16):
  35. The number of channels to be fed to the `MaskDecoder` module.
  36. num_point_embeddings (`int`, *optional*, defaults to 4):
  37. The number of point embeddings to be used.
  38. hidden_act (`str`, *optional*, defaults to `"gelu"`):
  39. The non-linear activation function in the encoder and pooler.
  40. """
  41. def __init__(
  42. self,
  43. hidden_size=256,
  44. image_size=1024,
  45. patch_size=16,
  46. mask_input_channels=16,
  47. num_point_embeddings=4,
  48. hidden_act="gelu",
  49. layer_norm_eps=1e-6,
  50. **kwargs,
  51. ):
  52. super().__init__(**kwargs)
  53. self.hidden_size = hidden_size
  54. self.image_size = image_size
  55. self.patch_size = patch_size
  56. self.image_embedding_size = image_size // patch_size
  57. self.mask_input_channels = mask_input_channels
  58. self.num_point_embeddings = num_point_embeddings
  59. self.hidden_act = hidden_act
  60. self.layer_norm_eps = layer_norm_eps
  61. class SamMaskDecoderConfig(PretrainedConfig):
  62. r"""
  63. This is the configuration class to store the configuration of a [`SamMaskDecoder`]. It is used to instantiate a SAM
  64. mask decoder to the specified arguments, defining the model architecture. Instantiating a configuration defaults
  65. will yield a similar configuration to that of the SAM-vit-h
  66. [facebook/sam-vit-huge](https://huggingface.co/facebook/sam-vit-huge) architecture.
  67. Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
  68. documentation from [`PretrainedConfig`] for more information.
  69. Args:
  70. hidden_size (`int`, *optional*, defaults to 256):
  71. Dimensionality of the hidden states.
  72. hidden_act (`str`, *optional*, defaults to `"relu"`):
  73. The non-linear activation function used inside the `SamMaskDecoder` module.
  74. mlp_dim (`int`, *optional*, defaults to 2048):
  75. Dimensionality of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder.
  76. num_hidden_layers (`int`, *optional*, defaults to 2):
  77. Number of hidden layers in the Transformer encoder.
  78. num_attention_heads (`int`, *optional*, defaults to 8):
  79. Number of attention heads for each attention layer in the Transformer encoder.
  80. attention_downsample_rate (`int`, *optional*, defaults to 2):
  81. The downsampling rate of the attention layer.
  82. num_multimask_outputs (`int`, *optional*, defaults to 3):
  83. The number of outputs from the `SamMaskDecoder` module. In the Segment Anything paper, this is set to 3.
  84. iou_head_depth (`int`, *optional*, defaults to 3):
  85. The number of layers in the IoU head module.
  86. iou_head_hidden_dim (`int`, *optional*, defaults to 256):
  87. The dimensionality of the hidden states in the IoU head module.
  88. layer_norm_eps (`float`, *optional*, defaults to 1e-06):
  89. The epsilon used by the layer normalization layers.
  90. """
  91. def __init__(
  92. self,
  93. hidden_size=256,
  94. hidden_act="relu",
  95. mlp_dim=2048,
  96. num_hidden_layers=2,
  97. num_attention_heads=8,
  98. attention_downsample_rate=2,
  99. num_multimask_outputs=3,
  100. iou_head_depth=3,
  101. iou_head_hidden_dim=256,
  102. layer_norm_eps=1e-6,
  103. **kwargs,
  104. ):
  105. super().__init__(**kwargs)
  106. self.hidden_size = hidden_size
  107. self.hidden_act = hidden_act
  108. self.mlp_dim = mlp_dim
  109. self.num_hidden_layers = num_hidden_layers
  110. self.num_attention_heads = num_attention_heads
  111. self.attention_downsample_rate = attention_downsample_rate
  112. self.num_multimask_outputs = num_multimask_outputs
  113. self.iou_head_depth = iou_head_depth
  114. self.iou_head_hidden_dim = iou_head_hidden_dim
  115. self.layer_norm_eps = layer_norm_eps
  116. class SamVisionConfig(PretrainedConfig):
  117. r"""
  118. This is the configuration class to store the configuration of a [`SamVisionModel`]. It is used to instantiate a SAM
  119. vision encoder according to the specified arguments, defining the model architecture. Instantiating a configuration
  120. defaults will yield a similar configuration to that of the SAM ViT-h
  121. [facebook/sam-vit-huge](https://huggingface.co/facebook/sam-vit-huge) architecture.
  122. Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
  123. documentation from [`PretrainedConfig`] for more information.
  124. Args:
  125. hidden_size (`int`, *optional*, defaults to 768):
  126. Dimensionality of the encoder layers and the pooler layer.
  127. output_channels (`int`, *optional*, defaults to 256):
  128. Dimensionality of the output channels in the Patch Encoder.
  129. num_hidden_layers (`int`, *optional*, defaults to 12):
  130. Number of hidden layers in the Transformer encoder.
  131. num_attention_heads (`int`, *optional*, defaults to 12):
  132. Number of attention heads for each attention layer in the Transformer encoder.
  133. num_channels (`int`, *optional*, defaults to 3):
  134. Number of channels in the input image.
  135. image_size (`int`, *optional*, defaults to 1024):
  136. Expected resolution. Target size of the resized input image.
  137. patch_size (`int`, *optional*, defaults to 16):
  138. Size of the patches to be extracted from the input image.
  139. hidden_act (`str`, *optional*, defaults to `"gelu"`):
  140. The non-linear activation function (function or string)
  141. layer_norm_eps (`float`, *optional*, defaults to 1e-06):
  142. The epsilon used by the layer normalization layers.
  143. attention_dropout (`float`, *optional*, defaults to 0.0):
  144. The dropout ratio for the attention probabilities.
  145. initializer_range (`float`, *optional*, defaults to 1e-10):
  146. The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
  147. qkv_bias (`bool`, *optional*, defaults to `True`):
  148. Whether to add a bias to query, key, value projections.
  149. mlp_ratio (`float`, *optional*, defaults to 4.0):
  150. Ratio of mlp hidden dim to embedding dim.
  151. use_abs_pos (`bool`, *optional*, defaults to `True`):
  152. Whether to use absolute position embedding.
  153. use_rel_pos (`bool`, *optional*, defaults to `True`):
  154. Whether to use relative position embedding.
  155. window_size (`int`, *optional*, defaults to 14):
  156. Window size for relative position.
  157. global_attn_indexes (`List[int]`, *optional*, defaults to `[2, 5, 8, 11]`):
  158. The indexes of the global attention layers.
  159. num_pos_feats (`int`, *optional*, defaults to 128):
  160. The dimensionality of the position embedding.
  161. mlp_dim (`int`, *optional*):
  162. The dimensionality of the MLP layer in the Transformer encoder. If `None`, defaults to `mlp_ratio *
  163. hidden_size`.
  164. """
  165. def __init__(
  166. self,
  167. hidden_size=768,
  168. output_channels=256,
  169. num_hidden_layers=12,
  170. num_attention_heads=12,
  171. num_channels=3,
  172. image_size=1024,
  173. patch_size=16,
  174. hidden_act="gelu",
  175. layer_norm_eps=1e-06,
  176. attention_dropout=0.0,
  177. initializer_range=1e-10,
  178. qkv_bias=True,
  179. mlp_ratio=4.0,
  180. use_abs_pos=True,
  181. use_rel_pos=True,
  182. window_size=14,
  183. global_attn_indexes=[2, 5, 8, 11],
  184. num_pos_feats=128,
  185. mlp_dim=None,
  186. **kwargs,
  187. ):
  188. super().__init__(**kwargs)
  189. self.hidden_size = hidden_size
  190. self.output_channels = output_channels
  191. self.num_hidden_layers = num_hidden_layers
  192. self.num_attention_heads = num_attention_heads
  193. self.num_channels = num_channels
  194. self.image_size = image_size
  195. self.patch_size = patch_size
  196. self.hidden_act = hidden_act
  197. self.layer_norm_eps = layer_norm_eps
  198. self.attention_dropout = attention_dropout
  199. self.initializer_range = initializer_range
  200. self.qkv_bias = qkv_bias
  201. self.mlp_ratio = mlp_ratio
  202. self.use_abs_pos = use_abs_pos
  203. self.use_rel_pos = use_rel_pos
  204. self.window_size = window_size
  205. self.global_attn_indexes = global_attn_indexes
  206. self.num_pos_feats = num_pos_feats
  207. self.mlp_dim = int(hidden_size * mlp_ratio) if mlp_dim is None else mlp_dim
  208. class SamConfig(PretrainedConfig):
  209. r"""
  210. [`SamConfig`] is the configuration class to store the configuration of a [`SamModel`]. It is used to instantiate a
  211. SAM model according to the specified arguments, defining the vision model, prompt-encoder model and mask decoder
  212. configs. Instantiating a configuration with the defaults will yield a similar configuration to that of the
  213. SAM-ViT-H [facebook/sam-vit-huge](https://huggingface.co/facebook/sam-vit-huge) architecture.
  214. Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
  215. documentation from [`PretrainedConfig`] for more information.
  216. Args:
  217. vision_config (Union[`dict`, `SamVisionConfig`], *optional*):
  218. Dictionary of configuration options used to initialize [`SamVisionConfig`].
  219. prompt_encoder_config (Union[`dict`, `SamPromptEncoderConfig`], *optional*):
  220. Dictionary of configuration options used to initialize [`SamPromptEncoderConfig`].
  221. mask_decoder_config (Union[`dict`, `SamMaskDecoderConfig`], *optional*):
  222. Dictionary of configuration options used to initialize [`SamMaskDecoderConfig`].
  223. kwargs (*optional*):
  224. Dictionary of keyword arguments.
  225. Example:
  226. ```python
  227. >>> from transformers import (
  228. ... SamVisionConfig,
  229. ... SamPromptEncoderConfig,
  230. ... SamMaskDecoderConfig,
  231. ... SamModel,
  232. ... )
  233. >>> # Initializing a SamConfig with `"facebook/sam-vit-huge"` style configuration
  234. >>> configuration = SamConfig()
  235. >>> # Initializing a SamModel (with random weights) from the `"facebook/sam-vit-huge"` style configuration
  236. >>> model = SamModel(configuration)
  237. >>> # Accessing the model configuration
  238. >>> configuration = model.config
  239. >>> # We can also initialize a SamConfig from a SamVisionConfig, SamPromptEncoderConfig, and SamMaskDecoderConfig
  240. >>> # Initializing SAM vision, SAM Q-Former and language model configurations
  241. >>> vision_config = SamVisionConfig()
  242. >>> prompt_encoder_config = SamPromptEncoderConfig()
  243. >>> mask_decoder_config = SamMaskDecoderConfig()
  244. >>> config = SamConfig(vision_config, prompt_encoder_config, mask_decoder_config)
  245. ```"""
  246. model_type = "sam"
  247. def __init__(
  248. self,
  249. vision_config=None,
  250. prompt_encoder_config=None,
  251. mask_decoder_config=None,
  252. initializer_range=0.02,
  253. **kwargs,
  254. ):
  255. super().__init__(**kwargs)
  256. vision_config = vision_config if vision_config is not None else {}
  257. prompt_encoder_config = prompt_encoder_config if prompt_encoder_config is not None else {}
  258. mask_decoder_config = mask_decoder_config if mask_decoder_config is not None else {}
  259. if isinstance(vision_config, SamVisionConfig):
  260. vision_config = vision_config.to_dict()
  261. if isinstance(prompt_encoder_config, SamPromptEncoderConfig):
  262. prompt_encoder_config = prompt_encoder_config.to_dict()
  263. if isinstance(mask_decoder_config, SamMaskDecoderConfig):
  264. mask_decoder_config = mask_decoder_config.to_dict()
  265. self.vision_config = SamVisionConfig(**vision_config)
  266. self.prompt_encoder_config = SamPromptEncoderConfig(**prompt_encoder_config)
  267. self.mask_decoder_config = SamMaskDecoderConfig(**mask_decoder_config)
  268. self.initializer_range = initializer_range