configuration_groupvit.py 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229
  1. # Copyright 2022 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. """GroupViT model configuration"""
  15. from huggingface_hub.dataclasses import strict
  16. from ...configuration_utils import PreTrainedConfig
  17. from ...utils import auto_docstring, logging
  18. logger = logging.get_logger(__name__)
  19. @auto_docstring(checkpoint="nvidia/groupvit-gcc-yfcc")
  20. @strict
  21. class GroupViTTextConfig(PreTrainedConfig):
  22. r"""
  23. Example:
  24. ```python
  25. >>> from transformers import GroupViTTextConfig, GroupViTTextModel
  26. >>> # Initializing a GroupViTTextModel with nvidia/groupvit-gcc-yfcc style configuration
  27. >>> configuration = GroupViTTextConfig()
  28. >>> model = GroupViTTextModel(configuration)
  29. >>> # Accessing the model configuration
  30. >>> configuration = model.config
  31. ```"""
  32. model_type = "groupvit_text_model"
  33. base_config_key = "text_config"
  34. vocab_size: int = 49408
  35. hidden_size: int = 256
  36. intermediate_size: int = 1024
  37. num_hidden_layers: int = 12
  38. num_attention_heads: int = 4
  39. max_position_embeddings: int = 77
  40. hidden_act: str = "quick_gelu"
  41. layer_norm_eps: float = 1e-5
  42. dropout: float | int = 0.0
  43. attention_dropout: float | int = 0.0
  44. initializer_range: float = 0.02
  45. initializer_factor: float = 1.0
  46. pad_token_id: int | None = 1
  47. bos_token_id: int | None = 49406
  48. eos_token_id: int | list[int] | None = 49407
  49. @auto_docstring(checkpoint="nvidia/groupvit-gcc-yfcc")
  50. @strict
  51. class GroupViTVisionConfig(PreTrainedConfig):
  52. r"""
  53. depths (`list[int]`, *optional*, defaults to [6, 3, 3]):
  54. The number of layers in each encoder block.
  55. num_group_tokens (`list[int]`, *optional*, defaults to [64, 8, 0]):
  56. The number of group tokens for each stage.
  57. num_output_groups (`list[int]`, *optional*, defaults to [64, 8, 8]):
  58. The number of output groups for each stage, 0 means no group.
  59. assign_eps (`float`, *optional*, defaults to `1.0`):
  60. Epsilon used in layer norm
  61. assign_mlp_ratio (`list[int]`, *optional*, defaults to `[0.5, 4]`):
  62. Ratio used to infer hidden size of MLP layers.
  63. Example:
  64. ```python
  65. >>> from transformers import GroupViTVisionConfig, GroupViTVisionModel
  66. >>> # Initializing a GroupViTVisionModel with nvidia/groupvit-gcc-yfcc style configuration
  67. >>> configuration = GroupViTVisionConfig()
  68. >>> model = GroupViTVisionModel(configuration)
  69. >>> # Accessing the model configuration
  70. >>> configuration = model.config
  71. ```"""
  72. model_type = "groupvit_vision_model"
  73. base_config_key = "vision_config"
  74. hidden_size: int = 384
  75. intermediate_size: int = 1536
  76. num_hidden_layers: int = 12
  77. depths: list[int] | tuple[int, ...] = (6, 3, 3)
  78. num_group_tokens: list[int] | tuple[int, ...] = (64, 8, 0)
  79. num_output_groups: list[int] | tuple[int, ...] = (64, 8, 8)
  80. num_attention_heads: int = 6
  81. image_size: int | list[int] | tuple[int, int] = 224
  82. patch_size: int | list[int] | tuple[int, int] = 16
  83. num_channels: int = 3
  84. hidden_act: str = "gelu"
  85. layer_norm_eps: float = 1e-5
  86. dropout: float | int = 0.0
  87. attention_dropout: float | int = 0.0
  88. initializer_range: float = 0.02
  89. initializer_factor: float = 1.0
  90. assign_eps: float = 1.0
  91. assign_mlp_ratio: list[float | int] | tuple[float | int, ...] = (0.5, 4)
  92. def validate_architecture(self):
  93. """Part of `@strict`-powered validation. Validates the architecture of the config."""
  94. if self.num_hidden_layers != sum(self.depths):
  95. logger.warning(
  96. f"Manually setting num_hidden_layers to {self.num_hidden_layers}, but we expect num_hidden_layers ="
  97. f" sum(depth) = {sum(self.depths)}"
  98. )
  99. @auto_docstring(checkpoint="nvidia/groupvit-gcc-yfcc")
  100. @strict
  101. class GroupViTConfig(PreTrainedConfig):
  102. r"""
  103. projection_intermediate_dim (`int`, *optional*, defaults to 4096):
  104. Dimensionality of intermediate layer of text and vision projection layers.
  105. output_segmentation (`bool`, *optional*, defaults to False):
  106. Whether or not to return the segmentation logits.
  107. """
  108. model_type = "groupvit"
  109. sub_configs = {"text_config": GroupViTTextConfig, "vision_config": GroupViTVisionConfig}
  110. text_config: dict | PreTrainedConfig | None = None
  111. vision_config: dict | PreTrainedConfig | None = None
  112. projection_dim: int = 256
  113. projection_intermediate_dim: int = 4096
  114. logit_scale_init_value: float = 2.6592
  115. initializer_range: float = 0.02
  116. initializer_factor: float = 1.0
  117. output_segmentation: bool = False
  118. def __post_init__(self, **kwargs):
  119. if self.text_config is None:
  120. text_config = {}
  121. logger.info("`text_config` is `None`. Initializing the `GroupViTTextConfig` with default values.")
  122. elif isinstance(self.text_config, GroupViTTextConfig):
  123. text_config = self.text_config.to_dict()
  124. else:
  125. text_config = self.text_config
  126. if self.vision_config is None:
  127. vision_config = {}
  128. logger.info("`vision_config` is `None`. initializing the `GroupViTVisionConfig` with default values.")
  129. elif isinstance(self.vision_config, GroupViTVisionConfig):
  130. vision_config = self.vision_config.to_dict()
  131. else:
  132. vision_config = self.vision_config
  133. # For backward compatibility check keyword args
  134. # Instead of simply assigning `[text|vision]_config_dict` to `[text|vision]_config`, we use the values in
  135. # `[text|vision]_config_dict` to update the values in `[text|vision]_config`. The values should be same in most
  136. # cases, but we don't want to break anything regarding `_config_dict` that existed before commit `8827e1b2`.
  137. text_config_dict = kwargs.pop("text_config_dict", None)
  138. vision_config_dict = kwargs.pop("vision_config_dict", None)
  139. if text_config_dict is not None:
  140. # This is the complete result when using `text_config_dict`.
  141. _text_config_dict = GroupViTTextConfig(**text_config_dict).to_dict()
  142. # Give a warning if the values exist in both `_text_config_dict` and `text_config` but being different.
  143. for key, value in _text_config_dict.items():
  144. if key in text_config and value != text_config[key] and key != "transformers_version":
  145. # If specified in `text_config_dict`
  146. if key in text_config_dict:
  147. message = (
  148. f"`{key}` is found in both `text_config_dict` and `text_config` but with different values. "
  149. f'The value `text_config_dict["{key}"]` will be used instead.'
  150. )
  151. # If inferred from default argument values (just to be super careful)
  152. else:
  153. message = (
  154. f"`text_config_dict` is provided which will be used to initialize `GroupViTTextConfig`. The "
  155. f'value `text_config["{key}"]` will be overridden.'
  156. )
  157. logger.info(message)
  158. # Update all values in `text_config` with the ones in `_text_config_dict`.
  159. text_config.update(_text_config_dict)
  160. if vision_config_dict is not None:
  161. # This is the complete result when using `vision_config_dict`.
  162. _vision_config_dict = GroupViTVisionConfig(**vision_config_dict).to_dict()
  163. # convert keys to string instead of integer
  164. if "id2label" in _vision_config_dict:
  165. _vision_config_dict["id2label"] = {
  166. str(key): value for key, value in _vision_config_dict["id2label"].items()
  167. }
  168. # Give a warning if the values exist in both `_vision_config_dict` and `vision_config` but being different.
  169. for key, value in _vision_config_dict.items():
  170. if key in vision_config and value != vision_config[key] and key != "transformers_version":
  171. # If specified in `vision_config_dict`
  172. if key in vision_config_dict:
  173. message = (
  174. f"`{key}` is found in both `vision_config_dict` and `vision_config` but with different "
  175. f'values. The value `vision_config_dict["{key}"]` will be used instead.'
  176. )
  177. # If inferred from default argument values (just to be super careful)
  178. else:
  179. message = (
  180. f"`vision_config_dict` is provided which will be used to initialize `GroupViTVisionConfig`. "
  181. f'The value `vision_config["{key}"]` will be overridden.'
  182. )
  183. logger.info(message)
  184. # Update all values in `vision_config` with the ones in `_vision_config_dict`.
  185. vision_config.update(_vision_config_dict)
  186. # Finally we can convert back our unified text/vision configs to `PretrainedConfig`
  187. self.text_config = GroupViTTextConfig(**text_config)
  188. self.vision_config = GroupViTVisionConfig(**vision_config)
  189. super().__post_init__(**kwargs)
  190. __all__ = ["GroupViTConfig", "GroupViTTextConfig", "GroupViTVisionConfig"]