configuration_bit.py 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133
  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. """BiT 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 BitConfig(BackboneConfigMixin, PretrainedConfig):
  21. r"""
  22. This is the configuration class to store the configuration of a [`BitModel`]. It is used to instantiate an BiT
  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 BiT
  25. [google/bit-50](https://huggingface.co/google/bit-50) 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. num_channels (`int`, *optional*, defaults to 3):
  30. The number of input channels.
  31. embedding_size (`int`, *optional*, defaults to 64):
  32. Dimensionality (hidden size) for the embedding layer.
  33. hidden_sizes (`List[int]`, *optional*, defaults to `[256, 512, 1024, 2048]`):
  34. Dimensionality (hidden size) at each stage.
  35. depths (`List[int]`, *optional*, defaults to `[3, 4, 6, 3]`):
  36. Depth (number of layers) for each stage.
  37. layer_type (`str`, *optional*, defaults to `"preactivation"`):
  38. The layer to use, it can be either `"preactivation"` or `"bottleneck"`.
  39. hidden_act (`str`, *optional*, defaults to `"relu"`):
  40. The non-linear activation function in each block. If string, `"gelu"`, `"relu"`, `"selu"` and `"gelu_new"`
  41. are supported.
  42. global_padding (`str`, *optional*):
  43. Padding strategy to use for the convolutional layers. Can be either `"valid"`, `"same"`, or `None`.
  44. num_groups (`int`, *optional*, defaults to 32):
  45. Number of groups used for the `BitGroupNormActivation` layers.
  46. drop_path_rate (`float`, *optional*, defaults to 0.0):
  47. The drop path rate for the stochastic depth.
  48. embedding_dynamic_padding (`bool`, *optional*, defaults to `False`):
  49. Whether or not to make use of dynamic padding for the embedding layer.
  50. output_stride (`int`, *optional*, defaults to 32):
  51. The output stride of the model.
  52. width_factor (`int`, *optional*, defaults to 1):
  53. The width factor for the model.
  54. out_features (`List[str]`, *optional*):
  55. If used as backbone, list of features to output. Can be any of `"stem"`, `"stage1"`, `"stage2"`, etc.
  56. (depending on how many stages the model has). If unset and `out_indices` is set, will default to the
  57. corresponding stages. If unset and `out_indices` is unset, will default to the last stage. Must be in the
  58. same order as defined in the `stage_names` attribute.
  59. out_indices (`List[int]`, *optional*):
  60. If used as backbone, list of indices of features to output. Can be any of 0, 1, 2, etc. (depending on how
  61. many stages the model has). If unset and `out_features` is set, will default to the corresponding stages.
  62. If unset and `out_features` is unset, will default to the last stage. Must be in the
  63. same order as defined in the `stage_names` attribute.
  64. Example:
  65. ```python
  66. >>> from transformers import BitConfig, BitModel
  67. >>> # Initializing a BiT bit-50 style configuration
  68. >>> configuration = BitConfig()
  69. >>> # Initializing a model (with random weights) from the bit-50 style configuration
  70. >>> model = BitModel(configuration)
  71. >>> # Accessing the model configuration
  72. >>> configuration = model.config
  73. ```
  74. """
  75. model_type = "bit"
  76. layer_types = ["preactivation", "bottleneck"]
  77. supported_padding = ["SAME", "VALID"]
  78. def __init__(
  79. self,
  80. num_channels=3,
  81. embedding_size=64,
  82. hidden_sizes=[256, 512, 1024, 2048],
  83. depths=[3, 4, 6, 3],
  84. layer_type="preactivation",
  85. hidden_act="relu",
  86. global_padding=None,
  87. num_groups=32,
  88. drop_path_rate=0.0,
  89. embedding_dynamic_padding=False,
  90. output_stride=32,
  91. width_factor=1,
  92. out_features=None,
  93. out_indices=None,
  94. **kwargs,
  95. ):
  96. super().__init__(**kwargs)
  97. if layer_type not in self.layer_types:
  98. raise ValueError(f"layer_type={layer_type} is not one of {','.join(self.layer_types)}")
  99. if global_padding is not None:
  100. if global_padding.upper() in self.supported_padding:
  101. global_padding = global_padding.upper()
  102. else:
  103. raise ValueError(f"Padding strategy {global_padding} not supported")
  104. self.num_channels = num_channels
  105. self.embedding_size = embedding_size
  106. self.hidden_sizes = hidden_sizes
  107. self.depths = depths
  108. self.layer_type = layer_type
  109. self.hidden_act = hidden_act
  110. self.global_padding = global_padding
  111. self.num_groups = num_groups
  112. self.drop_path_rate = drop_path_rate
  113. self.embedding_dynamic_padding = embedding_dynamic_padding
  114. self.output_stride = output_stride
  115. self.width_factor = width_factor
  116. self.stage_names = ["stem"] + [f"stage{idx}" for idx in range(1, len(depths) + 1)]
  117. self._out_features, self._out_indices = get_aligned_output_features_output_indices(
  118. out_features=out_features, out_indices=out_indices, stage_names=self.stage_names
  119. )