configuration_swinv2.py 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159
  1. # coding=utf-8
  2. # Copyright 2022 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. """Swinv2 Transformer 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 Swinv2Config(BackboneConfigMixin, PretrainedConfig):
  21. r"""
  22. This is the configuration class to store the configuration of a [`Swinv2Model`]. It is used to instantiate a Swin
  23. Transformer v2 model according to the specified arguments, defining the model architecture. Instantiating a
  24. configuration with the defaults will yield a similar configuration to that of the Swin Transformer v2
  25. [microsoft/swinv2-tiny-patch4-window8-256](https://huggingface.co/microsoft/swinv2-tiny-patch4-window8-256)
  26. architecture.
  27. Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
  28. documentation from [`PretrainedConfig`] for more information.
  29. Args:
  30. image_size (`int`, *optional*, defaults to 224):
  31. The size (resolution) of each image.
  32. patch_size (`int`, *optional*, defaults to 4):
  33. The size (resolution) of each patch.
  34. num_channels (`int`, *optional*, defaults to 3):
  35. The number of input channels.
  36. embed_dim (`int`, *optional*, defaults to 96):
  37. Dimensionality of patch embedding.
  38. depths (`list(int)`, *optional*, defaults to `[2, 2, 6, 2]`):
  39. Depth of each layer in the Transformer encoder.
  40. num_heads (`list(int)`, *optional*, defaults to `[3, 6, 12, 24]`):
  41. Number of attention heads in each layer of the Transformer encoder.
  42. window_size (`int`, *optional*, defaults to 7):
  43. Size of windows.
  44. pretrained_window_sizes (`list(int)`, *optional*, defaults to `[0, 0, 0, 0]`):
  45. Size of windows during pretraining.
  46. mlp_ratio (`float`, *optional*, defaults to 4.0):
  47. Ratio of MLP hidden dimensionality to embedding dimensionality.
  48. qkv_bias (`bool`, *optional*, defaults to `True`):
  49. Whether or not a learnable bias should be added to the queries, keys and values.
  50. hidden_dropout_prob (`float`, *optional*, defaults to 0.0):
  51. The dropout probability for all fully connected layers in the embeddings and encoder.
  52. attention_probs_dropout_prob (`float`, *optional*, defaults to 0.0):
  53. The dropout ratio for the attention probabilities.
  54. drop_path_rate (`float`, *optional*, defaults to 0.1):
  55. Stochastic depth rate.
  56. hidden_act (`str` or `function`, *optional*, defaults to `"gelu"`):
  57. The non-linear activation function (function or string) in the encoder. If string, `"gelu"`, `"relu"`,
  58. `"selu"` and `"gelu_new"` are supported.
  59. use_absolute_embeddings (`bool`, *optional*, defaults to `False`):
  60. Whether or not to add absolute position embeddings to the patch embeddings.
  61. initializer_range (`float`, *optional*, defaults to 0.02):
  62. The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
  63. layer_norm_eps (`float`, *optional*, defaults to 1e-05):
  64. The epsilon used by the layer normalization layers.
  65. encoder_stride (`int`, *optional*, defaults to 32):
  66. Factor to increase the spatial resolution by in the decoder head for masked image modeling.
  67. out_features (`list[str]`, *optional*):
  68. If used as backbone, list of features to output. Can be any of `"stem"`, `"stage1"`, `"stage2"`, etc.
  69. (depending on how many stages the model has). If unset and `out_indices` is set, will default to the
  70. corresponding stages. If unset and `out_indices` is unset, will default to the last stage.
  71. out_indices (`list[int]`, *optional*):
  72. If used as backbone, list of indices of features to output. Can be any of 0, 1, 2, etc. (depending on how
  73. many stages the model has). If unset and `out_features` is set, will default to the corresponding stages.
  74. If unset and `out_features` is unset, will default to the last stage.
  75. Example:
  76. ```python
  77. >>> from transformers import Swinv2Config, Swinv2Model
  78. >>> # Initializing a Swinv2 microsoft/swinv2-tiny-patch4-window8-256 style configuration
  79. >>> configuration = Swinv2Config()
  80. >>> # Initializing a model (with random weights) from the microsoft/swinv2-tiny-patch4-window8-256 style configuration
  81. >>> model = Swinv2Model(configuration)
  82. >>> # Accessing the model configuration
  83. >>> configuration = model.config
  84. ```"""
  85. model_type = "swinv2"
  86. attribute_map = {
  87. "num_attention_heads": "num_heads",
  88. "num_hidden_layers": "num_layers",
  89. }
  90. def __init__(
  91. self,
  92. image_size=224,
  93. patch_size=4,
  94. num_channels=3,
  95. embed_dim=96,
  96. depths=[2, 2, 6, 2],
  97. num_heads=[3, 6, 12, 24],
  98. window_size=7,
  99. pretrained_window_sizes=[0, 0, 0, 0],
  100. mlp_ratio=4.0,
  101. qkv_bias=True,
  102. hidden_dropout_prob=0.0,
  103. attention_probs_dropout_prob=0.0,
  104. drop_path_rate=0.1,
  105. hidden_act="gelu",
  106. use_absolute_embeddings=False,
  107. initializer_range=0.02,
  108. layer_norm_eps=1e-5,
  109. encoder_stride=32,
  110. out_features=None,
  111. out_indices=None,
  112. **kwargs,
  113. ):
  114. super().__init__(**kwargs)
  115. self.image_size = image_size
  116. self.patch_size = patch_size
  117. self.num_channels = num_channels
  118. self.embed_dim = embed_dim
  119. self.depths = depths
  120. self.num_layers = len(depths)
  121. self.num_heads = num_heads
  122. self.window_size = window_size
  123. self.pretrained_window_sizes = pretrained_window_sizes
  124. self.mlp_ratio = mlp_ratio
  125. self.qkv_bias = qkv_bias
  126. self.hidden_dropout_prob = hidden_dropout_prob
  127. self.attention_probs_dropout_prob = attention_probs_dropout_prob
  128. self.drop_path_rate = drop_path_rate
  129. self.hidden_act = hidden_act
  130. self.use_absolute_embeddings = use_absolute_embeddings
  131. self.layer_norm_eps = layer_norm_eps
  132. self.initializer_range = initializer_range
  133. self.encoder_stride = encoder_stride
  134. self.stage_names = ["stem"] + [f"stage{idx}" for idx in range(1, len(depths) + 1)]
  135. self._out_features, self._out_indices = get_aligned_output_features_output_indices(
  136. out_features=out_features, out_indices=out_indices, stage_names=self.stage_names
  137. )
  138. # we set the hidden_size attribute in order to make Swinv2 work with VisionEncoderDecoderModel
  139. # this indicates the channel dimension after the last stage of the model
  140. self.hidden_size = int(embed_dim * 2 ** (len(depths) - 1))
  141. __all__ = ["Swinv2Config"]