configuration_focalnet.py 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161
  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. """FocalNet 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 FocalNetConfig(BackboneConfigMixin, PretrainedConfig):
  21. r"""
  22. This is the configuration class to store the configuration of a [`FocalNetModel`]. It is used to instantiate a
  23. FocalNet model according to the specified arguments, defining the model architecture. Instantiating a configuration
  24. with the defaults will yield a similar configuration to that of the FocalNet
  25. [microsoft/focalnet-tiny](https://huggingface.co/microsoft/focalnet-tiny) 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. image_size (`int`, *optional*, defaults to 224):
  30. The size (resolution) of each image.
  31. patch_size (`int`, *optional*, defaults to 4):
  32. The size (resolution) of each patch in the embeddings layer.
  33. num_channels (`int`, *optional*, defaults to 3):
  34. The number of input channels.
  35. embed_dim (`int`, *optional*, defaults to 96):
  36. Dimensionality of patch embedding.
  37. use_conv_embed (`bool`, *optional*, defaults to `False`):
  38. Whether to use convolutional embedding. The authors noted that using convolutional embedding usually
  39. improve the performance, but it's not used by default.
  40. hidden_sizes (`List[int]`, *optional*, defaults to `[192, 384, 768, 768]`):
  41. Dimensionality (hidden size) at each stage.
  42. depths (`list(int)`, *optional*, defaults to `[2, 2, 6, 2]`):
  43. Depth (number of layers) of each stage in the encoder.
  44. focal_levels (`list(int)`, *optional*, defaults to `[2, 2, 2, 2]`):
  45. Number of focal levels in each layer of the respective stages in the encoder.
  46. focal_windows (`list(int)`, *optional*, defaults to `[3, 3, 3, 3]`):
  47. Focal window size in each layer of the respective stages in the encoder.
  48. hidden_act (`str` or `function`, *optional*, defaults to `"gelu"`):
  49. The non-linear activation function (function or string) in the encoder. If string, `"gelu"`, `"relu"`,
  50. `"selu"` and `"gelu_new"` are supported.
  51. mlp_ratio (`float`, *optional*, defaults to 4.0):
  52. Ratio of MLP hidden dimensionality to embedding dimensionality.
  53. hidden_dropout_prob (`float`, *optional*, defaults to 0.0):
  54. The dropout probability for all fully connected layers in the embeddings and encoder.
  55. drop_path_rate (`float`, *optional*, defaults to 0.1):
  56. Stochastic depth rate.
  57. use_layerscale (`bool`, *optional*, defaults to `False`):
  58. Whether to use layer scale in the encoder.
  59. layerscale_value (`float`, *optional*, defaults to 0.0001):
  60. The initial value of the layer scale.
  61. use_post_layernorm (`bool`, *optional*, defaults to `False`):
  62. Whether to use post layer normalization in the encoder.
  63. use_post_layernorm_in_modulation (`bool`, *optional*, defaults to `False`):
  64. Whether to use post layer normalization in the modulation layer.
  65. normalize_modulator (`bool`, *optional*, defaults to `False`):
  66. Whether to normalize the modulator.
  67. initializer_range (`float`, *optional*, defaults to 0.02):
  68. The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
  69. layer_norm_eps (`float`, *optional*, defaults to 1e-05):
  70. The epsilon used by the layer normalization layers.
  71. encoder_stride (`int`, *optional*, defaults to 32):
  72. Factor to increase the spatial resolution by in the decoder head for masked image modeling.
  73. out_features (`List[str]`, *optional*):
  74. If used as backbone, list of features to output. Can be any of `"stem"`, `"stage1"`, `"stage2"`, etc.
  75. (depending on how many stages the model has). If unset and `out_indices` is set, will default to the
  76. corresponding stages. If unset and `out_indices` is unset, will default to the last stage. Must be in the
  77. same order as defined in the `stage_names` attribute.
  78. out_indices (`List[int]`, *optional*):
  79. If used as backbone, list of indices of features to output. Can be any of 0, 1, 2, etc. (depending on how
  80. many stages the model has). If unset and `out_features` is set, will default to the corresponding stages.
  81. If unset and `out_features` is unset, will default to the last stage. Must be in the
  82. same order as defined in the `stage_names` attribute.
  83. Example:
  84. ```python
  85. >>> from transformers import FocalNetConfig, FocalNetModel
  86. >>> # Initializing a FocalNet microsoft/focalnet-tiny style configuration
  87. >>> configuration = FocalNetConfig()
  88. >>> # Initializing a model (with random weights) from the microsoft/focalnet-tiny style configuration
  89. >>> model = FocalNetModel(configuration)
  90. >>> # Accessing the model configuration
  91. >>> configuration = model.config
  92. ```"""
  93. model_type = "focalnet"
  94. def __init__(
  95. self,
  96. image_size=224,
  97. patch_size=4,
  98. num_channels=3,
  99. embed_dim=96,
  100. use_conv_embed=False,
  101. hidden_sizes=[192, 384, 768, 768],
  102. depths=[2, 2, 6, 2],
  103. focal_levels=[2, 2, 2, 2],
  104. focal_windows=[3, 3, 3, 3],
  105. hidden_act="gelu",
  106. mlp_ratio=4.0,
  107. hidden_dropout_prob=0.0,
  108. drop_path_rate=0.1,
  109. use_layerscale=False,
  110. layerscale_value=1e-4,
  111. use_post_layernorm=False,
  112. use_post_layernorm_in_modulation=False,
  113. normalize_modulator=False,
  114. initializer_range=0.02,
  115. layer_norm_eps=1e-5,
  116. encoder_stride=32,
  117. out_features=None,
  118. out_indices=None,
  119. **kwargs,
  120. ):
  121. super().__init__(**kwargs)
  122. self.image_size = image_size
  123. self.patch_size = patch_size
  124. self.num_channels = num_channels
  125. self.embed_dim = embed_dim
  126. self.use_conv_embed = use_conv_embed
  127. self.hidden_sizes = hidden_sizes
  128. self.depths = depths
  129. self.focal_levels = focal_levels
  130. self.focal_windows = focal_windows
  131. self.hidden_act = hidden_act
  132. self.mlp_ratio = mlp_ratio
  133. self.hidden_dropout_prob = hidden_dropout_prob
  134. self.drop_path_rate = drop_path_rate
  135. self.use_layerscale = use_layerscale
  136. self.layerscale_value = layerscale_value
  137. self.use_post_layernorm = use_post_layernorm
  138. self.use_post_layernorm_in_modulation = use_post_layernorm_in_modulation
  139. self.normalize_modulator = normalize_modulator
  140. self.initializer_range = initializer_range
  141. self.layer_norm_eps = layer_norm_eps
  142. self.encoder_stride = encoder_stride
  143. self.stage_names = ["stem"] + [f"stage{idx}" for idx in range(1, len(self.depths) + 1)]
  144. self._out_features, self._out_indices = get_aligned_output_features_output_indices(
  145. out_features=out_features, out_indices=out_indices, stage_names=self.stage_names
  146. )