configuration_altclip.py 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224
  1. # Copyright 2022 WenXiang ZhongzhiCheng LedellWu LiuGuang BoWenZhang and 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. """AltCLIP 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="BAAI/AltCLIP")
  20. @strict
  21. class AltCLIPTextConfig(PreTrainedConfig):
  22. r"""
  23. project_dim (`int`, *optional*, defaults to 768):
  24. The dimensions of the teacher model before the mapping layer.
  25. Examples:
  26. ```python
  27. >>> from transformers import AltCLIPTextModel, AltCLIPTextConfig
  28. >>> # Initializing a AltCLIPTextConfig with BAAI/AltCLIP style configuration
  29. >>> configuration = AltCLIPTextConfig()
  30. >>> # Initializing a AltCLIPTextModel (with random weights) from the BAAI/AltCLIP style configuration
  31. >>> model = AltCLIPTextModel(configuration)
  32. >>> # Accessing the model configuration
  33. >>> configuration = model.config
  34. ```"""
  35. model_type = "altclip_text_model"
  36. vocab_size: int = 250002
  37. hidden_size: int = 1024
  38. num_hidden_layers: int = 24
  39. num_attention_heads: int = 16
  40. intermediate_size: int = 4096
  41. hidden_act: str = "gelu"
  42. hidden_dropout_prob: float | int = 0.1
  43. attention_probs_dropout_prob: float | int = 0.1
  44. max_position_embeddings: int = 514
  45. type_vocab_size: int = 1
  46. initializer_range: float = 0.02
  47. initializer_factor: float = 0.02
  48. layer_norm_eps: float = 1e-05
  49. pad_token_id: int | None = 1
  50. bos_token_id: int | None = 0
  51. eos_token_id: int | list[int] | None = 2
  52. project_dim: int = 768
  53. @auto_docstring(checkpoint="BAAI/AltCLIP")
  54. @strict
  55. class AltCLIPVisionConfig(PreTrainedConfig):
  56. r"""
  57. Example:
  58. ```python
  59. >>> from transformers import AltCLIPVisionConfig, AltCLIPVisionModel
  60. >>> # Initializing a AltCLIPVisionConfig with BAAI/AltCLIP style configuration
  61. >>> configuration = AltCLIPVisionConfig()
  62. >>> # Initializing a AltCLIPVisionModel (with random weights) from the BAAI/AltCLIP style configuration
  63. >>> model = AltCLIPVisionModel(configuration)
  64. >>> # Accessing the model configuration
  65. >>> configuration = model.config
  66. ```"""
  67. model_type = "altclip_vision_model"
  68. base_config_key = "vision_config"
  69. hidden_size: int = 768
  70. intermediate_size: int = 3072
  71. projection_dim: int = 512
  72. num_hidden_layers: int = 12
  73. num_attention_heads: int = 12
  74. num_channels: int = 3
  75. image_size: int | list[int] | tuple[int, int] = 224
  76. patch_size: int | list[int] | tuple[int, int] = 32
  77. hidden_act: str = "quick_gelu"
  78. layer_norm_eps: float = 1e-5
  79. attention_dropout: float | int = 0.0
  80. initializer_range: float = 0.02
  81. initializer_factor: float = 1.0
  82. @auto_docstring(checkpoint="BAAI/AltCLIP")
  83. @strict
  84. class AltCLIPConfig(PreTrainedConfig):
  85. r"""
  86. Example:
  87. ```python
  88. >>> from transformers import AltCLIPConfig, AltCLIPModel
  89. >>> # Initializing a AltCLIPConfig with BAAI/AltCLIP style configuration
  90. >>> configuration = AltCLIPConfig()
  91. >>> # Initializing a AltCLIPModel (with random weights) from the BAAI/AltCLIP style configuration
  92. >>> model = AltCLIPModel(configuration)
  93. >>> # Accessing the model configuration
  94. >>> configuration = model.config
  95. >>> # We can also initialize a AltCLIPConfig from a AltCLIPTextConfig and a AltCLIPVisionConfig
  96. >>> # Initializing a AltCLIPText and AltCLIPVision configuration
  97. >>> config_text = AltCLIPTextConfig()
  98. >>> config_vision = AltCLIPVisionConfig()
  99. >>> config = AltCLIPConfig(text_config=config_text, vision_config=config_vision)
  100. ```"""
  101. model_type = "altclip"
  102. sub_configs = {"text_config": AltCLIPTextConfig, "vision_config": AltCLIPVisionConfig}
  103. text_config: dict | PreTrainedConfig | None = None
  104. vision_config: dict | PreTrainedConfig | None = None
  105. projection_dim: int = 768
  106. logit_scale_init_value: float = 2.6592
  107. initializer_factor: float = 1.0
  108. def __post_init__(self, **kwargs):
  109. if self.text_config is None:
  110. text_config = {}
  111. logger.info("`text_config` is `None`. Initializing the `AltCLIPTextConfig` with default values.")
  112. elif isinstance(self.text_config, AltCLIPTextConfig):
  113. text_config = self.text_config.to_dict()
  114. else:
  115. text_config = self.text_config
  116. if self.vision_config is None:
  117. vision_config = {}
  118. logger.info("`vision_config` is `None`. initializing the `AltCLIPVisionConfig` with default values.")
  119. elif isinstance(self.vision_config, AltCLIPVisionConfig):
  120. vision_config = self.vision_config.to_dict()
  121. else:
  122. vision_config = self.vision_config
  123. # For backward compatibility check keyword args
  124. # Instead of simply assigning `[text|vision]_config_dict` to `[text|vision]_config`, we use the values in
  125. # `[text|vision]_config_dict` to update the values in `[text|vision]_config`. The values should be same in most
  126. # cases, but we don't want to break anything regarding `_config_dict` that existed before commit `8827e1b2`.
  127. text_config_dict = kwargs.pop("text_config_dict", None)
  128. vision_config_dict = kwargs.pop("vision_config_dict", None)
  129. if text_config_dict is not None:
  130. # This is the complete result when using `text_config_dict`.
  131. _text_config_dict = AltCLIPTextConfig(**text_config_dict).to_dict()
  132. # Give a warning if the values exist in both `_text_config_dict` and `text_config` but being different.
  133. for key, value in _text_config_dict.items():
  134. if key in text_config and value != text_config[key] and key != "transformers_version":
  135. # If specified in `text_config_dict`
  136. if key in text_config_dict:
  137. message = (
  138. f"`{key}` is found in both `text_config_dict` and `text_config` but with different values. "
  139. f'The value `text_config_dict["{key}"]` will be used instead.'
  140. )
  141. # If inferred from default argument values (just to be super careful)
  142. else:
  143. message = (
  144. f"`text_config_dict` is provided which will be used to initialize `AltCLIPTextConfig`. The "
  145. f'value `text_config["{key}"]` will be overridden.'
  146. )
  147. logger.info(message)
  148. # Update all values in `text_config` with the ones in `_text_config_dict`.
  149. text_config.update(_text_config_dict)
  150. if vision_config_dict is not None:
  151. # This is the complete result when using `vision_config_dict`.
  152. _vision_config_dict = AltCLIPVisionConfig(**vision_config_dict).to_dict()
  153. # convert keys to string instead of integer
  154. if "id2label" in _vision_config_dict:
  155. _vision_config_dict["id2label"] = {
  156. str(key): value for key, value in _vision_config_dict["id2label"].items()
  157. }
  158. # Give a warning if the values exist in both `_vision_config_dict` and `vision_config` but being different.
  159. for key, value in _vision_config_dict.items():
  160. if key in vision_config and value != vision_config[key] and key != "transformers_version":
  161. # If specified in `vision_config_dict`
  162. if key in vision_config_dict:
  163. message = (
  164. f"`{key}` is found in both `vision_config_dict` and `vision_config` but with different "
  165. f'values. The value `vision_config_dict["{key}"]` will be used instead.'
  166. )
  167. # If inferred from default argument values (just to be super careful)
  168. else:
  169. message = (
  170. f"`vision_config_dict` is provided which will be used to initialize `AltCLIPVisionConfig`. "
  171. f'The value `vision_config["{key}"]` will be overridden.'
  172. )
  173. logger.info(message)
  174. # Update all values in `vision_config` with the ones in `_vision_config_dict`.
  175. vision_config.update(_vision_config_dict)
  176. # Finally we can convert back our unified text/vision configs to `PretrainedConfig`
  177. self.text_config = AltCLIPTextConfig(**text_config)
  178. self.vision_config = AltCLIPVisionConfig(**vision_config)
  179. super().__post_init__(**kwargs)
  180. __all__ = ["AltCLIPTextConfig", "AltCLIPVisionConfig", "AltCLIPConfig"]