configuration_sam.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337
  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. base_config_key = "prompt_encoder_config"
  42. def __init__(
  43. self,
  44. hidden_size=256,
  45. image_size=1024,
  46. patch_size=16,
  47. mask_input_channels=16,
  48. num_point_embeddings=4,
  49. hidden_act="gelu",
  50. layer_norm_eps=1e-6,
  51. **kwargs,
  52. ):
  53. super().__init__(**kwargs)
  54. self.hidden_size = hidden_size
  55. self.image_size = image_size
  56. self.patch_size = patch_size
  57. self.image_embedding_size = image_size // patch_size
  58. self.mask_input_channels = mask_input_channels
  59. self.num_point_embeddings = num_point_embeddings
  60. self.hidden_act = hidden_act
  61. self.layer_norm_eps = layer_norm_eps
  62. class SamMaskDecoderConfig(PretrainedConfig):
  63. r"""
  64. This is the configuration class to store the configuration of a [`SamMaskDecoder`]. It is used to instantiate a SAM
  65. mask decoder to the specified arguments, defining the model architecture. Instantiating a configuration defaults
  66. will yield a similar configuration to that of the SAM-vit-h
  67. [facebook/sam-vit-huge](https://huggingface.co/facebook/sam-vit-huge) architecture.
  68. Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
  69. documentation from [`PretrainedConfig`] for more information.
  70. Args:
  71. hidden_size (`int`, *optional*, defaults to 256):
  72. Dimensionality of the hidden states.
  73. hidden_act (`str`, *optional*, defaults to `"relu"`):
  74. The non-linear activation function used inside the `SamMaskDecoder` module.
  75. mlp_dim (`int`, *optional*, defaults to 2048):
  76. Dimensionality of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder.
  77. num_hidden_layers (`int`, *optional*, defaults to 2):
  78. Number of hidden layers in the Transformer encoder.
  79. num_attention_heads (`int`, *optional*, defaults to 8):
  80. Number of attention heads for each attention layer in the Transformer encoder.
  81. attention_downsample_rate (`int`, *optional*, defaults to 2):
  82. The downsampling rate of the attention layer.
  83. num_multimask_outputs (`int`, *optional*, defaults to 3):
  84. The number of outputs from the `SamMaskDecoder` module. In the Segment Anything paper, this is set to 3.
  85. iou_head_depth (`int`, *optional*, defaults to 3):
  86. The number of layers in the IoU head module.
  87. iou_head_hidden_dim (`int`, *optional*, defaults to 256):
  88. The dimensionality of the hidden states in the IoU head module.
  89. layer_norm_eps (`float`, *optional*, defaults to 1e-06):
  90. The epsilon used by the layer normalization layers.
  91. """
  92. base_config_key = "mask_decoder_config"
  93. def __init__(
  94. self,
  95. hidden_size=256,
  96. hidden_act="relu",
  97. mlp_dim=2048,
  98. num_hidden_layers=2,
  99. num_attention_heads=8,
  100. attention_downsample_rate=2,
  101. num_multimask_outputs=3,
  102. iou_head_depth=3,
  103. iou_head_hidden_dim=256,
  104. layer_norm_eps=1e-6,
  105. **kwargs,
  106. ):
  107. super().__init__(**kwargs)
  108. self.hidden_size = hidden_size
  109. self.hidden_act = hidden_act
  110. self.mlp_dim = mlp_dim
  111. self.num_hidden_layers = num_hidden_layers
  112. self.num_attention_heads = num_attention_heads
  113. self.attention_downsample_rate = attention_downsample_rate
  114. self.num_multimask_outputs = num_multimask_outputs
  115. self.iou_head_depth = iou_head_depth
  116. self.iou_head_hidden_dim = iou_head_hidden_dim
  117. self.layer_norm_eps = layer_norm_eps
  118. class SamVisionConfig(PretrainedConfig):
  119. r"""
  120. This is the configuration class to store the configuration of a [`SamVisionModel`]. It is used to instantiate a SAM
  121. vision encoder according to the specified arguments, defining the model architecture. Instantiating a configuration
  122. defaults will yield a similar configuration to that of the SAM ViT-h
  123. [facebook/sam-vit-huge](https://huggingface.co/facebook/sam-vit-huge) architecture.
  124. Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
  125. documentation from [`PretrainedConfig`] for more information.
  126. Args:
  127. hidden_size (`int`, *optional*, defaults to 768):
  128. Dimensionality of the encoder layers and the pooler layer.
  129. output_channels (`int`, *optional*, defaults to 256):
  130. Dimensionality of the output channels in the Patch Encoder.
  131. num_hidden_layers (`int`, *optional*, defaults to 12):
  132. Number of hidden layers in the Transformer encoder.
  133. num_attention_heads (`int`, *optional*, defaults to 12):
  134. Number of attention heads for each attention layer in the Transformer encoder.
  135. num_channels (`int`, *optional*, defaults to 3):
  136. Number of channels in the input image.
  137. image_size (`int`, *optional*, defaults to 1024):
  138. Expected resolution. Target size of the resized input image.
  139. patch_size (`int`, *optional*, defaults to 16):
  140. Size of the patches to be extracted from the input image.
  141. hidden_act (`str`, *optional*, defaults to `"gelu"`):
  142. The non-linear activation function (function or string)
  143. layer_norm_eps (`float`, *optional*, defaults to 1e-06):
  144. The epsilon used by the layer normalization layers.
  145. attention_dropout (`float`, *optional*, defaults to 0.0):
  146. The dropout ratio for the attention probabilities.
  147. initializer_range (`float`, *optional*, defaults to 1e-10):
  148. The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
  149. qkv_bias (`bool`, *optional*, defaults to `True`):
  150. Whether to add a bias to query, key, value projections.
  151. mlp_ratio (`float`, *optional*, defaults to 4.0):
  152. Ratio of mlp hidden dim to embedding dim.
  153. use_abs_pos (`bool`, *optional*, defaults to `True`):
  154. Whether to use absolute position embedding.
  155. use_rel_pos (`bool`, *optional*, defaults to `True`):
  156. Whether to use relative position embedding.
  157. window_size (`int`, *optional*, defaults to 14):
  158. Window size for relative position.
  159. global_attn_indexes (`list[int]`, *optional*, defaults to `[2, 5, 8, 11]`):
  160. The indexes of the global attention layers.
  161. num_pos_feats (`int`, *optional*, defaults to 128):
  162. The dimensionality of the position embedding.
  163. mlp_dim (`int`, *optional*):
  164. The dimensionality of the MLP layer in the Transformer encoder. If `None`, defaults to `mlp_ratio *
  165. hidden_size`.
  166. Example:
  167. ```python
  168. >>> from transformers import (
  169. ... SamVisionConfig,
  170. ... SamVisionModel,
  171. ... )
  172. >>> # Initializing a SamVisionConfig with `"facebook/sam-vit-huge"` style configuration
  173. >>> configuration = SamVisionConfig()
  174. >>> # Initializing a SamVisionModel (with random weights) from the `"facebook/sam-vit-huge"` style configuration
  175. >>> model = SamVisionModel(configuration)
  176. >>> # Accessing the model configuration
  177. >>> configuration = model.config
  178. ```"""
  179. base_config_key = "vision_config"
  180. model_type = "sam_vision_model"
  181. def __init__(
  182. self,
  183. hidden_size=768,
  184. output_channels=256,
  185. num_hidden_layers=12,
  186. num_attention_heads=12,
  187. num_channels=3,
  188. image_size=1024,
  189. patch_size=16,
  190. hidden_act="gelu",
  191. layer_norm_eps=1e-06,
  192. attention_dropout=0.0,
  193. initializer_range=1e-10,
  194. qkv_bias=True,
  195. mlp_ratio=4.0,
  196. use_abs_pos=True,
  197. use_rel_pos=True,
  198. window_size=14,
  199. global_attn_indexes=[2, 5, 8, 11],
  200. num_pos_feats=128,
  201. mlp_dim=None,
  202. **kwargs,
  203. ):
  204. super().__init__(**kwargs)
  205. self.hidden_size = hidden_size
  206. self.output_channels = output_channels
  207. self.num_hidden_layers = num_hidden_layers
  208. self.num_attention_heads = num_attention_heads
  209. self.num_channels = num_channels
  210. self.image_size = image_size
  211. self.patch_size = patch_size
  212. self.hidden_act = hidden_act
  213. self.layer_norm_eps = layer_norm_eps
  214. self.attention_dropout = attention_dropout
  215. self.initializer_range = initializer_range
  216. self.qkv_bias = qkv_bias
  217. self.mlp_ratio = mlp_ratio
  218. self.use_abs_pos = use_abs_pos
  219. self.use_rel_pos = use_rel_pos
  220. self.window_size = window_size
  221. self.global_attn_indexes = global_attn_indexes
  222. self.num_pos_feats = num_pos_feats
  223. self.mlp_dim = int(hidden_size * mlp_ratio) if mlp_dim is None else mlp_dim
  224. class SamConfig(PretrainedConfig):
  225. r"""
  226. [`SamConfig`] is the configuration class to store the configuration of a [`SamModel`]. It is used to instantiate a
  227. SAM model according to the specified arguments, defining the vision model, prompt-encoder model and mask decoder
  228. configs. Instantiating a configuration with the defaults will yield a similar configuration to that of the
  229. SAM-ViT-H [facebook/sam-vit-huge](https://huggingface.co/facebook/sam-vit-huge) architecture.
  230. Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
  231. documentation from [`PretrainedConfig`] for more information.
  232. Args:
  233. vision_config (Union[`dict`, `SamVisionConfig`], *optional*):
  234. Dictionary of configuration options used to initialize [`SamVisionConfig`].
  235. prompt_encoder_config (Union[`dict`, `SamPromptEncoderConfig`], *optional*):
  236. Dictionary of configuration options used to initialize [`SamPromptEncoderConfig`].
  237. mask_decoder_config (Union[`dict`, `SamMaskDecoderConfig`], *optional*):
  238. Dictionary of configuration options used to initialize [`SamMaskDecoderConfig`].
  239. kwargs (*optional*):
  240. Dictionary of keyword arguments.
  241. Example:
  242. ```python
  243. >>> from transformers import (
  244. ... SamVisionConfig,
  245. ... SamPromptEncoderConfig,
  246. ... SamMaskDecoderConfig,
  247. ... SamModel,
  248. ... )
  249. >>> # Initializing a SamConfig with `"facebook/sam-vit-huge"` style configuration
  250. >>> configuration = SamConfig()
  251. >>> # Initializing a SamModel (with random weights) from the `"facebook/sam-vit-huge"` style configuration
  252. >>> model = SamModel(configuration)
  253. >>> # Accessing the model configuration
  254. >>> configuration = model.config
  255. >>> # We can also initialize a SamConfig from a SamVisionConfig, SamPromptEncoderConfig, and SamMaskDecoderConfig
  256. >>> # Initializing SAM vision, SAM Q-Former and language model configurations
  257. >>> vision_config = SamVisionConfig()
  258. >>> prompt_encoder_config = SamPromptEncoderConfig()
  259. >>> mask_decoder_config = SamMaskDecoderConfig()
  260. >>> config = SamConfig(vision_config, prompt_encoder_config, mask_decoder_config)
  261. ```"""
  262. model_type = "sam"
  263. sub_configs = {
  264. "prompt_encoder_config": SamPromptEncoderConfig,
  265. "mask_decoder_config": SamMaskDecoderConfig,
  266. "vision_config": SamVisionConfig,
  267. }
  268. def __init__(
  269. self,
  270. vision_config=None,
  271. prompt_encoder_config=None,
  272. mask_decoder_config=None,
  273. initializer_range=0.02,
  274. **kwargs,
  275. ):
  276. super().__init__(**kwargs)
  277. vision_config = vision_config if vision_config is not None else {}
  278. prompt_encoder_config = prompt_encoder_config if prompt_encoder_config is not None else {}
  279. mask_decoder_config = mask_decoder_config if mask_decoder_config is not None else {}
  280. if isinstance(vision_config, SamVisionConfig):
  281. vision_config = vision_config.to_dict()
  282. if isinstance(prompt_encoder_config, SamPromptEncoderConfig):
  283. prompt_encoder_config = prompt_encoder_config.to_dict()
  284. if isinstance(mask_decoder_config, SamMaskDecoderConfig):
  285. mask_decoder_config = mask_decoder_config.to_dict()
  286. self.vision_config = SamVisionConfig(**vision_config)
  287. self.prompt_encoder_config = SamPromptEncoderConfig(**prompt_encoder_config)
  288. self.mask_decoder_config = SamMaskDecoderConfig(**mask_decoder_config)
  289. self.initializer_range = initializer_range
  290. __all__ = ["SamConfig", "SamMaskDecoderConfig", "SamPromptEncoderConfig", "SamVisionConfig"]