configuration_clip.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248
  1. # Copyright 2021 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. """CLIP 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="openai/clip-vit-base-patch32")
  20. @strict
  21. class CLIPTextConfig(PreTrainedConfig):
  22. r"""
  23. Example:
  24. ```python
  25. >>> from transformers import CLIPTextConfig, CLIPTextModel
  26. >>> # Initializing a CLIPTextConfig with openai/clip-vit-base-patch32 style configuration
  27. >>> configuration = CLIPTextConfig()
  28. >>> # Initializing a CLIPTextModel (with random weights) from the openai/clip-vit-base-patch32 style configuration
  29. >>> model = CLIPTextModel(configuration)
  30. >>> # Accessing the model configuration
  31. >>> configuration = model.config
  32. ```"""
  33. model_type = "clip_text_model"
  34. base_config_key = "text_config"
  35. vocab_size: int = 49408
  36. hidden_size: int = 512
  37. intermediate_size: int = 2048
  38. projection_dim: int | None = 512
  39. num_hidden_layers: int = 12
  40. num_attention_heads: int = 8
  41. max_position_embeddings: int = 77
  42. hidden_act: str = "quick_gelu"
  43. layer_norm_eps: float | None = 1e-5
  44. attention_dropout: int | float | None = 0.0
  45. initializer_range: float = 0.02
  46. initializer_factor: float | None = 1.0
  47. # This differs from `CLIPTokenizer`'s default and from openai/clip
  48. # See https://github.com/huggingface/transformers/pull/24773#issuecomment-1632287538
  49. pad_token_id: int | None = 1
  50. bos_token_id: int | None = 49406
  51. eos_token_id: int | list[int] | None = 49407
  52. def validate_architecture(self):
  53. """Part of `@strict`-powered validation. Validates the architecture of the config."""
  54. if self.hidden_size % self.num_attention_heads != 0:
  55. raise ValueError(
  56. f"The hidden size ({self.hidden_size}) is not a multiple of the number of attention "
  57. f"heads ({self.num_attention_heads})."
  58. )
  59. @auto_docstring(checkpoint="openai/clip-vit-base-patch32")
  60. @strict
  61. class CLIPVisionConfig(PreTrainedConfig):
  62. r"""
  63. Example:
  64. ```python
  65. >>> from transformers import CLIPVisionConfig, CLIPVisionModel
  66. >>> # Initializing a CLIPVisionConfig with openai/clip-vit-base-patch32 style configuration
  67. >>> configuration = CLIPVisionConfig()
  68. >>> # Initializing a CLIPVisionModel (with random weights) from the openai/clip-vit-base-patch32 style configuration
  69. >>> model = CLIPVisionModel(configuration)
  70. >>> # Accessing the model configuration
  71. >>> configuration = model.config
  72. ```"""
  73. model_type = "clip_vision_model"
  74. base_config_key = "vision_config"
  75. hidden_size: int = 768
  76. intermediate_size: int = 3072
  77. projection_dim: int | None = 512
  78. num_hidden_layers: int = 12
  79. num_attention_heads: int = 12
  80. num_channels: int | None = 3
  81. image_size: int | None = 224
  82. patch_size: int | None = 32
  83. hidden_act: str = "quick_gelu"
  84. layer_norm_eps: float | None = 1e-5
  85. attention_dropout: int | float | None = 0.0
  86. initializer_range: float = 0.02
  87. initializer_factor: float | None = 1.0
  88. def validate_architecture(self):
  89. """Part of `@strict`-powered validation. Validates the architecture of the config."""
  90. if self.hidden_size % self.num_attention_heads != 0:
  91. raise ValueError(
  92. f"The hidden size ({self.hidden_size}) is not a multiple of the number of attention "
  93. f"heads ({self.num_attention_heads})."
  94. )
  95. @auto_docstring(checkpoint="openai/clip-vit-base-patch32")
  96. @strict
  97. class CLIPConfig(PreTrainedConfig):
  98. r"""
  99. text_config (`dict`, *optional*):
  100. Dictionary of configuration options used to initialize [`CLIPTextConfig`].
  101. vision_config (`dict`, *optional*):
  102. Dictionary of configuration options used to initialize [`CLIPVisionConfig`].
  103. logit_scale_init_value (`float | int`, *optional*, defaults to 2.6592):
  104. The initial value of the *logit_scale* parameter. Default is used as per the original CLIP implementation.
  105. Example:
  106. ```python
  107. >>> from transformers import CLIPConfig, CLIPModel
  108. >>> # Initializing a CLIPConfig with openai/clip-vit-base-patch32 style configuration
  109. >>> configuration = CLIPConfig()
  110. >>> # Initializing a CLIPModel (with random weights) from the openai/clip-vit-base-patch32 style configuration
  111. >>> model = CLIPModel(configuration)
  112. >>> # Accessing the model configuration
  113. >>> configuration = model.config
  114. >>> # We can also initialize a CLIPConfig from a CLIPTextConfig and a CLIPVisionConfig
  115. >>> from transformers import CLIPTextConfig, CLIPVisionConfig
  116. >>> # Initializing a CLIPText and CLIPVision configuration
  117. >>> config_text = CLIPTextConfig()
  118. >>> config_vision = CLIPVisionConfig()
  119. >>> config = CLIPConfig(text_config=config_text, vision_config=config_vision)
  120. ```"""
  121. model_type = "clip"
  122. sub_configs = {"text_config": CLIPTextConfig, "vision_config": CLIPVisionConfig}
  123. text_config: dict | CLIPTextConfig | None = None
  124. vision_config: dict | CLIPVisionConfig | None = None
  125. projection_dim: int | None = 512
  126. logit_scale_init_value: float | int | None = 2.6592
  127. initializer_factor: float | None = 1.0
  128. def __post_init__(self, **kwargs):
  129. if self.text_config is None:
  130. text_config = {}
  131. logger.info("`text_config` is `None`. Initializing the `CLIPTextConfig` with default values.")
  132. elif isinstance(self.text_config, CLIPTextConfig):
  133. text_config = self.text_config.to_dict()
  134. else:
  135. text_config = self.text_config
  136. if self.vision_config is None:
  137. vision_config = {}
  138. logger.info("`vision_config` is `None`. initializing the `CLIPVisionConfig` with default values.")
  139. elif isinstance(self.vision_config, CLIPVisionConfig):
  140. vision_config = self.vision_config.to_dict()
  141. else:
  142. vision_config = self.vision_config
  143. # For backward compatibility check keyword args
  144. # Instead of simply assigning `[text|vision]_config_dict` to `[text|vision]_config`, we use the values in
  145. # `[text|vision]_config_dict` to update the values in `[text|vision]_config`. The values should be same in most
  146. # cases, but we don't want to break anything regarding `_config_dict` that existed before commit `8827e1b2`.
  147. text_config_dict = kwargs.pop("text_config_dict", None)
  148. vision_config_dict = kwargs.pop("vision_config_dict", None)
  149. if text_config_dict is not None:
  150. # This is the complete result when using `text_config_dict`.
  151. _text_config_dict = CLIPTextConfig(**text_config_dict).to_dict()
  152. # Give a warning if the values exist in both `_text_config_dict` and `text_config` but being different.
  153. for key, value in _text_config_dict.items():
  154. if key in text_config and value != text_config[key] and key != "transformers_version":
  155. # If specified in `text_config_dict`
  156. if key in text_config_dict:
  157. message = (
  158. f"`{key}` is found in both `text_config_dict` and `text_config` but with different values. "
  159. f'The value `text_config_dict["{key}"]` will be used instead.'
  160. )
  161. # If inferred from default argument values (just to be super careful)
  162. else:
  163. message = (
  164. f"`text_config_dict` is provided which will be used to initialize `CLIPTextConfig`. The "
  165. f'value `text_config["{key}"]` will be overridden.'
  166. )
  167. logger.info(message)
  168. # Update all values in `text_config` with the ones in `_text_config_dict`.
  169. text_config.update(_text_config_dict)
  170. if vision_config_dict is not None:
  171. # This is the complete result when using `vision_config_dict`.
  172. _vision_config_dict = CLIPVisionConfig(**vision_config_dict).to_dict()
  173. # convert keys to string instead of integer
  174. if "id2label" in _vision_config_dict:
  175. _vision_config_dict["id2label"] = {
  176. str(key): value for key, value in _vision_config_dict["id2label"].items()
  177. }
  178. # Give a warning if the values exist in both `_vision_config_dict` and `vision_config` but being different.
  179. for key, value in _vision_config_dict.items():
  180. if key in vision_config and value != vision_config[key] and key != "transformers_version":
  181. # If specified in `vision_config_dict`
  182. if key in vision_config_dict:
  183. message = (
  184. f"`{key}` is found in both `vision_config_dict` and `vision_config` but with different "
  185. f'values. The value `vision_config_dict["{key}"]` will be used instead.'
  186. )
  187. # If inferred from default argument values (just to be super careful)
  188. else:
  189. message = (
  190. f"`vision_config_dict` is provided which will be used to initialize `CLIPVisionConfig`. "
  191. f'The value `vision_config["{key}"]` will be overridden.'
  192. )
  193. logger.info(message)
  194. # Update all values in `vision_config` with the ones in `_vision_config_dict`.
  195. vision_config.update(_vision_config_dict)
  196. # Finally we can convert back our unified text/vision configs to `PretrainedConfig`
  197. self.text_config = CLIPTextConfig(**text_config)
  198. self.vision_config = CLIPVisionConfig(**vision_config)
  199. super().__post_init__(**kwargs)
  200. __all__ = ["CLIPConfig", "CLIPTextConfig", "CLIPVisionConfig"]