configuration_sam.py 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212
  1. # Copyright 2023 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. """SAM model configuration"""
  15. from huggingface_hub.dataclasses import strict
  16. from ...configuration_utils import PreTrainedConfig
  17. from ...utils import auto_docstring
  18. @auto_docstring(checkpoint="facebook/sam-vit-huge")
  19. @strict
  20. class SamPromptEncoderConfig(PreTrainedConfig):
  21. r"""
  22. mask_input_channels (`int`, *optional*, defaults to 16):
  23. The number of channels to be fed to the `MaskDecoder` module.
  24. num_point_embeddings (`int`, *optional*, defaults to 4):
  25. The number of point embeddings to be used.
  26. """
  27. base_config_key = "prompt_encoder_config"
  28. hidden_size: int = 256
  29. image_size: int | list[int] | tuple[int, int] = 1024
  30. patch_size: int | list[int] | tuple[int, int] = 16
  31. mask_input_channels: int = 16
  32. num_point_embeddings: int = 4
  33. hidden_act: str = "gelu"
  34. layer_norm_eps: float = 1e-6
  35. def __post_init__(self, **kwargs):
  36. self.image_embedding_size = self.image_size // self.patch_size
  37. super().__post_init__(**kwargs)
  38. @auto_docstring(checkpoint="facebook/sam-vit-huge")
  39. @strict
  40. class SamMaskDecoderConfig(PreTrainedConfig):
  41. r"""
  42. mlp_dim (`int`, *optional*, defaults to 2048):
  43. Dimensionality of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder.
  44. attention_downsample_rate (`int`, *optional*, defaults to 2):
  45. The downsampling rate of the attention layer.
  46. num_multimask_outputs (`int`, *optional*, defaults to 3):
  47. The number of outputs from the `SamMaskDecoder` module. In the Segment Anything paper, this is set to 3.
  48. iou_head_depth (`int`, *optional*, defaults to 3):
  49. The number of layers in the IoU head module.
  50. iou_head_hidden_dim (`int`, *optional*, defaults to 256):
  51. The dimensionality of the hidden states in the IoU head module.
  52. """
  53. base_config_key = "mask_decoder_config"
  54. hidden_size: int = 256
  55. hidden_act: str = "relu"
  56. mlp_dim: int = 2048
  57. num_hidden_layers: int = 2
  58. num_attention_heads: int = 8
  59. attention_downsample_rate: int = 2
  60. num_multimask_outputs: int = 3
  61. iou_head_depth: int = 3
  62. iou_head_hidden_dim: int = 256
  63. layer_norm_eps: float = 1e-6
  64. @auto_docstring(checkpoint="facebook/sam-vit-huge")
  65. @strict
  66. class SamVisionConfig(PreTrainedConfig):
  67. r"""
  68. output_channels (`int`, *optional*, defaults to 256):
  69. Dimensionality of the output channels in the Patch Encoder.
  70. use_rel_pos (`bool`, *optional*, defaults to `True`):
  71. Whether to use relative position embedding.
  72. window_size (`int`, *optional*, defaults to 14):
  73. Window size for relative position.
  74. global_attn_indexes (`list[int]`, *optional*, defaults to `[2, 5, 8, 11]`):
  75. The indexes of the global attention layers.
  76. num_pos_feats (`int`, *optional*, defaults to 128):
  77. The dimensionality of the position embedding.
  78. mlp_dim (`int`, *optional*):
  79. The dimensionality of the MLP layer in the Transformer encoder. If `None`, defaults to `mlp_ratio *
  80. hidden_size`.
  81. Example:
  82. ```python
  83. >>> from transformers import (
  84. ... SamVisionConfig,
  85. ... SamVisionModel,
  86. ... )
  87. >>> # Initializing a SamVisionConfig with `"facebook/sam-vit-huge"` style configuration
  88. >>> configuration = SamVisionConfig()
  89. >>> # Initializing a SamVisionModel (with random weights) from the `"facebook/sam-vit-huge"` style configuration
  90. >>> model = SamVisionModel(configuration)
  91. >>> # Accessing the model configuration
  92. >>> configuration = model.config
  93. ```"""
  94. base_config_key = "vision_config"
  95. model_type = "sam_vision_model"
  96. hidden_size: int = 768
  97. output_channels: int = 256
  98. num_hidden_layers: int = 12
  99. num_attention_heads: int = 12
  100. num_channels: int = 3
  101. image_size: int | list[int] | tuple[int, int] = 1024
  102. patch_size: int | list[int] | tuple[int, int] = 16
  103. hidden_act: str = "gelu"
  104. layer_norm_eps: float = 1e-06
  105. attention_dropout: float | int = 0.0
  106. initializer_range: float = 1e-10
  107. qkv_bias: bool = True
  108. mlp_ratio: float = 4.0
  109. use_abs_pos: bool = True
  110. use_rel_pos: bool = True
  111. window_size: int = 14
  112. global_attn_indexes: list[int] | tuple[int, ...] = (2, 5, 8, 11)
  113. num_pos_feats: int = 128
  114. mlp_dim: int | None = None
  115. def __post_init__(self, **kwargs):
  116. self.mlp_dim = int(self.hidden_size * self.mlp_ratio) if self.mlp_dim is None else self.mlp_dim
  117. self.scale = self.hidden_size // 2
  118. super().__post_init__(**kwargs)
  119. @auto_docstring(checkpoint="facebook/sam-vit-huge")
  120. @strict
  121. class SamConfig(PreTrainedConfig):
  122. r"""
  123. prompt_encoder_config (Union[`dict`, `SamPromptEncoderConfig`], *optional*):
  124. Dictionary of configuration options used to initialize [`SamPromptEncoderConfig`].
  125. mask_decoder_config (Union[`dict`, `SamMaskDecoderConfig`], *optional*):
  126. Dictionary of configuration options used to initialize [`SamMaskDecoderConfig`].
  127. Example:
  128. ```python
  129. >>> from transformers import (
  130. ... SamVisionConfig,
  131. ... SamPromptEncoderConfig,
  132. ... SamMaskDecoderConfig,
  133. ... SamModel,
  134. ... )
  135. >>> # Initializing a SamConfig with `"facebook/sam-vit-huge"` style configuration
  136. >>> configuration = SamConfig()
  137. >>> # Initializing a SamModel (with random weights) from the `"facebook/sam-vit-huge"` style configuration
  138. >>> model = SamModel(configuration)
  139. >>> # Accessing the model configuration
  140. >>> configuration = model.config
  141. >>> # We can also initialize a SamConfig from a SamVisionConfig, SamPromptEncoderConfig, and SamMaskDecoderConfig
  142. >>> # Initializing SAM vision, SAM Q-Former and language model configurations
  143. >>> vision_config = SamVisionConfig()
  144. >>> prompt_encoder_config = SamPromptEncoderConfig()
  145. >>> mask_decoder_config = SamMaskDecoderConfig()
  146. >>> config = SamConfig(vision_config, prompt_encoder_config, mask_decoder_config)
  147. ```"""
  148. model_type = "sam"
  149. sub_configs = {
  150. "prompt_encoder_config": SamPromptEncoderConfig,
  151. "mask_decoder_config": SamMaskDecoderConfig,
  152. "vision_config": SamVisionConfig,
  153. }
  154. vision_config: dict | PreTrainedConfig | None = None
  155. prompt_encoder_config: dict | PreTrainedConfig | None = None
  156. mask_decoder_config: dict | PreTrainedConfig | None = None
  157. initializer_range: float = 0.02
  158. tie_word_embeddings: bool = True
  159. def __post_init__(self, **kwargs):
  160. if isinstance(self.vision_config, dict):
  161. self.vision_config = SamVisionConfig(**self.vision_config)
  162. elif self.vision_config is None:
  163. self.vision_config = SamVisionConfig()
  164. if isinstance(self.prompt_encoder_config, dict):
  165. self.prompt_encoder_config = SamPromptEncoderConfig(**self.prompt_encoder_config)
  166. elif self.prompt_encoder_config is None:
  167. self.prompt_encoder_config = SamPromptEncoderConfig()
  168. if isinstance(self.mask_decoder_config, dict):
  169. self.mask_decoder_config = SamMaskDecoderConfig(**self.mask_decoder_config)
  170. elif self.mask_decoder_config is None:
  171. self.mask_decoder_config = SamMaskDecoderConfig()
  172. super().__post_init__(**kwargs)
  173. __all__ = ["SamConfig", "SamMaskDecoderConfig", "SamPromptEncoderConfig", "SamVisionConfig"]