configuration_hiera.py 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194
  1. # coding=utf-8
  2. # Copyright 2024 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. """Hiera model configuration"""
  16. from ...configuration_utils import PretrainedConfig
  17. from ...utils import logging
  18. from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices
  19. logger = logging.get_logger(__name__)
  20. class HieraConfig(BackboneConfigMixin, PretrainedConfig):
  21. r"""
  22. This is the configuration class to store the configuration of a [`HieraModel`]. It is used to instantiate a Hiera
  23. model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
  24. defaults will yield a similar configuration to that of the Hiera
  25. [facebook/hiera-base-224](https://huggingface.co/facebook/hiera-base-224) architecture.
  26. Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
  27. documentation from [`PretrainedConfig`] for more information.
  28. Args:
  29. embed_dim (`int`, *optional*, defaults to 96):
  30. Dimensionality of patch embedding.
  31. image_size (`list(int)`, *optional*, defaults to `[224, 224]`):
  32. The size (resolution) of input in the format (height, width) for images
  33. and (frames, height, width) for videos.
  34. patch_size (`list(int)`, *optional*, defaults to `[7, 7]`):
  35. The size (resolution) of each patch.
  36. patch_stride (`list(int)`, *optional*, defaults to `[4, 4]`):
  37. The stride of the patch.
  38. patch_padding (`list(int)`, *optional*, defaults to `[3, 3]`):
  39. The padding of the patch.
  40. mlp_ratio (`float`, *optional*, defaults to 4.0):
  41. The ratio of mlp hidden dim to embedding dim.
  42. depths (`list(int)`, *optional*, defaults to `[2, 3, 16, 3]`):
  43. Depth of each layer in the Transformer encoder.
  44. num_heads (`list(int)`, *optional*, defaults to `[1, 2, 4, 8]`):
  45. Number of attention heads in each layer of the Transformer encoder.
  46. embed_dim_multiplier (`float`, *optional*, defaults to 2.0):
  47. The multiplier to the dimensionality of patch embedding in each layer of the Transformer encoder.
  48. num_query_pool (`int`, *optional*, defaults to 3):
  49. The number of query pool stages.
  50. query_stride (`list(int)`, *optional*, defaults to `[2, 2]`):
  51. The stride of the query pool.
  52. masked_unit_size (`list(int)`, *optional*, defaults to `[8, 8]`):
  53. The size of the masked unit.
  54. masked_unit_attention (`list(bool)`, *optional*, defaults to `[True, True, False, False]`):
  55. Whether to use masked unit attention in each layer of the Transformer encoder.
  56. drop_path_rate (`float`, *optional*, defaults to 0.0):
  57. The drop path rate.
  58. num_channels (`int`, *optional*, defaults to 3):
  59. The number of input channels.
  60. hidden_act (`str`, *optional*, defaults to `"gelu"`):
  61. The non-linear activation function (function or string) in the encoder. If string, `"gelu"`, `"relu"`,
  62. `"selu"` and `"gelu_new"` are supported.
  63. initializer_range (`float`, *optional*, defaults to 0.02):
  64. The standard deviation of the truncated_normal_initializer for initializing all weight matrices and
  65. the zero_initializer for initializing all bias vectors.
  66. layer_norm_init (`float`, *optional*, defaults to 1.0):
  67. The initial weight value for layer normalization layers.
  68. layer_norm_eps (`float`, *optional*, defaults to 1e-06):
  69. The epsilon used by the layer normalization layers.
  70. decoder_hidden_size (`int`, *optional*):
  71. Dimensionality of decoder embeddings for MAE pretraining.
  72. decoder_depth (`int`, *optional*):
  73. Depth of the decoder for MAE pretraining.
  74. decoder_num_heads (`int`, *optional*):
  75. Number of attention heads in each layer of the decoder for MAE pretraining.
  76. normalize_pixel_loss (`bool`, *optional*, defaults to `True`):
  77. Whether to normalize the pixel loss by the number of pixels.
  78. mask_ratio (`float`, *optional*, defaults to 0.6):
  79. The ratio of masked tokens in the input.
  80. out_features (`list[str]`, *optional*):
  81. If used as backbone, list of features to output. Can be any of `"stem"`, `"stage1"`, `"stage2"`, etc.
  82. (depending on how many stages the model has). If unset and `out_indices` is set, will default to the
  83. corresponding stages. If unset and `out_indices` is unset, will default to the last stage. Must be in the
  84. same order as defined in the `stage_names` attribute.
  85. out_indices (`list[int]`, *optional*):
  86. If used as backbone, list of indices of features to output. Can be any of 0, 1, 2, etc. (depending on how
  87. many stages the model has). If unset and `out_features` is set, will default to the corresponding stages.
  88. If unset and `out_features` is unset, will default to the last stage. Must be in the
  89. same order as defined in the `stage_names` attribute.
  90. Example:
  91. ```python
  92. >>> from transformers import HieraConfig, HieraModel
  93. >>> # Initializing a Hiera hiera-base-patch16-224 style configuration
  94. >>> configuration = HieraConfig()
  95. >>> # Initializing a model (with random weights) from the hiera-base-patch16-224 style configuration
  96. >>> model = HieraModel(configuration)
  97. >>> # Accessing the model configuration
  98. >>> configuration = model.config
  99. ```"""
  100. model_type = "hiera"
  101. attribute_map = {"num_hidden_layers": "num_layers"}
  102. def __init__(
  103. self,
  104. embed_dim=96,
  105. image_size=[224, 224],
  106. patch_size=[7, 7],
  107. patch_stride=[4, 4],
  108. patch_padding=[3, 3],
  109. mlp_ratio=4.0,
  110. depths=[2, 3, 16, 3],
  111. num_heads=[1, 2, 4, 8],
  112. embed_dim_multiplier=2.0,
  113. num_query_pool=3,
  114. query_stride=[2, 2],
  115. masked_unit_size=[8, 8],
  116. masked_unit_attention=[True, True, False, False],
  117. drop_path_rate=0.0,
  118. num_channels=3,
  119. hidden_act="gelu",
  120. initializer_range=0.02,
  121. layer_norm_init=1.0,
  122. layer_norm_eps=1e-6,
  123. decoder_hidden_size=None,
  124. decoder_depth=None,
  125. decoder_num_heads=None,
  126. normalize_pixel_loss=True,
  127. mask_ratio=0.6,
  128. out_features=None,
  129. out_indices=None,
  130. **kwargs,
  131. ):
  132. super().__init__(**kwargs)
  133. if masked_unit_size[0] % query_stride[0] ** (len(depths) - 1) != 0:
  134. raise ValueError(
  135. f"masked_unit_size[0] ({masked_unit_size[0]}) must be divisible by query_stride[0] ({query_stride[0]}) "
  136. f"raised to the power of the number of layers ({len(depths) - 1})"
  137. )
  138. if num_query_pool >= len(depths):
  139. raise ValueError(
  140. f"num_query_pool ({num_query_pool}) must be less than the number of layers ({len(depths)})"
  141. )
  142. self.embed_dim = embed_dim
  143. self.image_size = image_size
  144. self.patch_size = patch_size
  145. self.patch_stride = patch_stride
  146. self.patch_padding = patch_padding
  147. self.mlp_ratio = mlp_ratio
  148. self.depths = depths
  149. self.num_heads = num_heads
  150. self.num_layers = len(depths)
  151. self.embed_dim_multiplier = embed_dim_multiplier
  152. self.num_query_pool = num_query_pool
  153. self.query_stride = query_stride
  154. self.masked_unit_size = masked_unit_size
  155. self.masked_unit_attention = masked_unit_attention
  156. self.drop_path_rate = drop_path_rate
  157. self.num_channels = num_channels
  158. self.hidden_act = hidden_act
  159. self.initializer_range = initializer_range
  160. self.layer_norm_init = layer_norm_init
  161. self.layer_norm_eps = layer_norm_eps
  162. self.decoder_hidden_size = decoder_hidden_size
  163. self.decoder_depth = decoder_depth
  164. self.decoder_num_heads = decoder_num_heads
  165. self.normalize_pixel_loss = normalize_pixel_loss
  166. self.mask_ratio = mask_ratio
  167. # we set the hidden_size attribute in order to make Hiera work with VisionEncoderDecoderModel
  168. # this indicates the channel dimension after the last stage of the model
  169. self.hidden_size = int(embed_dim * embed_dim_multiplier ** (len(depths) - 1))
  170. self.stage_names = ["stem"] + [f"stage{idx}" for idx in range(1, len(depths) + 1)]
  171. self._out_features, self._out_indices = get_aligned_output_features_output_indices(
  172. out_features=out_features, out_indices=out_indices, stage_names=self.stage_names
  173. )
  174. __all__ = ["HieraConfig"]