configuration_swin.py 7.8 KB

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