configuration_hiera.py 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122
  1. # Copyright 2024 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. """Hiera model configuration"""
  15. from huggingface_hub.dataclasses import strict
  16. from ...backbone_utils import BackboneConfigMixin
  17. from ...configuration_utils import PreTrainedConfig
  18. from ...utils import auto_docstring
  19. @auto_docstring(checkpoint="facebook/hiera-base-224")
  20. @strict
  21. class HieraConfig(BackboneConfigMixin, PreTrainedConfig):
  22. r"""
  23. patch_stride (`list(int)`, *optional*, defaults to `[4, 4]`):
  24. The stride of the patch.
  25. patch_padding (`list(int)`, *optional*, defaults to `[3, 3]`):
  26. The padding of the patch.
  27. num_heads (`list(int)`, *optional*, defaults to `[1, 2, 4, 8]`):
  28. Number of attention heads in each layer of the Transformer encoder.
  29. embed_dim_multiplier (`float`, *optional*, defaults to 2.0):
  30. The multiplier to the dimensionality of patch embedding in each layer of the Transformer encoder.
  31. num_query_pool (`int`, *optional*, defaults to 3):
  32. The number of query pool stages.
  33. query_stride (`list(int)`, *optional*, defaults to `[2, 2]`):
  34. The stride of the query pool.
  35. masked_unit_size (`list(int)`, *optional*, defaults to `[8, 8]`):
  36. The size of the masked unit.
  37. masked_unit_attention (`list(bool)`, *optional*, defaults to `[True, True, False, False]`):
  38. Whether to use masked unit attention in each layer of the Transformer encoder.
  39. layer_norm_init (`float`, *optional*, defaults to 1.0):
  40. The initial weight value for layer normalization layers.
  41. decoder_depth (`int`, *optional*):
  42. Depth of the decoder for MAE pretraining.
  43. normalize_pixel_loss (`bool`, *optional*, defaults to `True`):
  44. Whether to normalize the pixel loss by the number of pixels.
  45. mask_ratio (`float`, *optional*, defaults to 0.6):
  46. The ratio of masked tokens in the input.
  47. Example:
  48. ```python
  49. >>> from transformers import HieraConfig, HieraModel
  50. >>> # Initializing a Hiera hiera-base-patch16-224 style configuration
  51. >>> configuration = HieraConfig()
  52. >>> # Initializing a model (with random weights) from the hiera-base-patch16-224 style configuration
  53. >>> model = HieraModel(configuration)
  54. >>> # Accessing the model configuration
  55. >>> configuration = model.config
  56. ```"""
  57. model_type = "hiera"
  58. attribute_map = {"num_hidden_layers": "num_layers"}
  59. embed_dim: int = 96
  60. image_size: list[int] | tuple[int, ...] = (224, 224)
  61. patch_size: list[int] | tuple[int, ...] = (7, 7)
  62. patch_stride: list[int] | tuple[int, ...] = (4, 4)
  63. patch_padding: list[int] | tuple[int, ...] = (3, 3)
  64. mlp_ratio: float = 4.0
  65. depths: list[int] | tuple[int, ...] = (2, 3, 16, 3)
  66. num_heads: list[int] | tuple[int, ...] = (1, 2, 4, 8)
  67. embed_dim_multiplier: float | int = 2.0
  68. num_query_pool: int = 3
  69. query_stride: list[int] | tuple[int, ...] = (2, 2)
  70. masked_unit_size: list[int] | tuple[int, ...] = (8, 8)
  71. masked_unit_attention: list[bool] | tuple[bool, ...] = (True, True, False, False)
  72. drop_path_rate: float | int = 0.0
  73. num_channels: int = 3
  74. hidden_act: str = "gelu"
  75. initializer_range: float = 0.02
  76. layer_norm_init: float = 1.0
  77. layer_norm_eps: float = 1e-6
  78. decoder_hidden_size: int | None = None
  79. decoder_depth: int | None = None
  80. decoder_num_heads: int | None = None
  81. normalize_pixel_loss: bool | None = True
  82. mask_ratio: float = 0.6
  83. _out_features: list[str] | None = None
  84. _out_indices: list[int] | None = None
  85. def __post_init__(self, **kwargs):
  86. # we set the hidden_size attribute in order to make Hiera work with VisionEncoderDecoderModel
  87. # this indicates the channel dimension after the last stage of the model
  88. self.hidden_size = int(self.embed_dim * self.embed_dim_multiplier ** (len(self.depths) - 1))
  89. self.stage_names = ["stem"] + [f"stage{idx}" for idx in range(1, len(self.depths) + 1)]
  90. self.set_output_features_output_indices(
  91. out_indices=kwargs.pop("out_indices", None), out_features=kwargs.pop("out_features", None)
  92. )
  93. super().__post_init__(**kwargs)
  94. def validate_architecture(self):
  95. """Part of `@strict`-powered validation. Validates the architecture of the config."""
  96. if self.masked_unit_size[0] % self.query_stride[0] ** (len(self.depths) - 1) != 0:
  97. raise ValueError(
  98. f"masked_unit_size[0] ({self.masked_unit_size[0]}) must be divisible by query_stride[0] ({self.query_stride[0]}) "
  99. f"raised to the power of the number of layers ({len(self.depths) - 1})"
  100. )
  101. if self.num_query_pool >= len(self.depths):
  102. raise ValueError(
  103. f"num_query_pool ({self.num_query_pool}) must be less than the number of layers ({len(self.depths)})"
  104. )
  105. __all__ = ["HieraConfig"]