configuration_clipseg.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429
  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. """CLIPSeg model configuration"""
  16. import os
  17. from typing import Union
  18. from ...configuration_utils import PretrainedConfig
  19. from ...utils import logging
  20. logger = logging.get_logger(__name__)
  21. class CLIPSegTextConfig(PretrainedConfig):
  22. r"""
  23. This is the configuration class to store the configuration of a [`CLIPSegModel`]. It is used to instantiate an
  24. CLIPSeg model according to the specified arguments, defining the model architecture. Instantiating a configuration
  25. with the defaults will yield a similar configuration to that of the CLIPSeg
  26. [CIDAS/clipseg-rd64](https://huggingface.co/CIDAS/clipseg-rd64) architecture.
  27. Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
  28. documentation from [`PretrainedConfig`] for more information.
  29. Args:
  30. vocab_size (`int`, *optional*, defaults to 49408):
  31. Vocabulary size of the CLIPSeg text model. Defines the number of different tokens that can be represented
  32. by the `inputs_ids` passed when calling [`CLIPSegModel`].
  33. hidden_size (`int`, *optional*, defaults to 512):
  34. Dimensionality of the encoder layers and the pooler layer.
  35. intermediate_size (`int`, *optional*, defaults to 2048):
  36. Dimensionality of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder.
  37. num_hidden_layers (`int`, *optional*, defaults to 12):
  38. Number of hidden layers in the Transformer encoder.
  39. num_attention_heads (`int`, *optional*, defaults to 8):
  40. Number of attention heads for each attention layer in the Transformer encoder.
  41. max_position_embeddings (`int`, *optional*, defaults to 77):
  42. The maximum sequence length that this model might ever be used with. Typically set this to something large
  43. just in case (e.g., 512 or 1024 or 2048).
  44. hidden_act (`str` or `function`, *optional*, defaults to `"quick_gelu"`):
  45. The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
  46. `"relu"`, `"selu"` and `"gelu_new"` `"quick_gelu"` are supported.
  47. layer_norm_eps (`float`, *optional*, defaults to 1e-05):
  48. The epsilon used by the layer normalization layers.
  49. attention_dropout (`float`, *optional*, defaults to 0.0):
  50. The dropout ratio for the attention probabilities.
  51. initializer_range (`float`, *optional*, defaults to 0.02):
  52. The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
  53. initializer_factor (`float`, *optional*, defaults to 1.0):
  54. A factor for initializing all weight matrices (should be kept to 1, used internally for initialization
  55. testing).
  56. pad_token_id (`int`, *optional*, defaults to 1):
  57. Padding token id.
  58. bos_token_id (`int`, *optional*, defaults to 49406):
  59. Beginning of stream token id.
  60. eos_token_id (`int`, *optional*, defaults to 49407):
  61. End of stream token id.
  62. Example:
  63. ```python
  64. >>> from transformers import CLIPSegTextConfig, CLIPSegTextModel
  65. >>> # Initializing a CLIPSegTextConfig with CIDAS/clipseg-rd64 style configuration
  66. >>> configuration = CLIPSegTextConfig()
  67. >>> # Initializing a CLIPSegTextModel (with random weights) from the CIDAS/clipseg-rd64 style configuration
  68. >>> model = CLIPSegTextModel(configuration)
  69. >>> # Accessing the model configuration
  70. >>> configuration = model.config
  71. ```"""
  72. model_type = "clipseg_text_model"
  73. def __init__(
  74. self,
  75. vocab_size=49408,
  76. hidden_size=512,
  77. intermediate_size=2048,
  78. num_hidden_layers=12,
  79. num_attention_heads=8,
  80. max_position_embeddings=77,
  81. hidden_act="quick_gelu",
  82. layer_norm_eps=1e-5,
  83. attention_dropout=0.0,
  84. initializer_range=0.02,
  85. initializer_factor=1.0,
  86. pad_token_id=1,
  87. bos_token_id=49406,
  88. eos_token_id=49407,
  89. **kwargs,
  90. ):
  91. super().__init__(pad_token_id=pad_token_id, bos_token_id=bos_token_id, eos_token_id=eos_token_id, **kwargs)
  92. self.vocab_size = vocab_size
  93. self.hidden_size = hidden_size
  94. self.intermediate_size = intermediate_size
  95. self.num_hidden_layers = num_hidden_layers
  96. self.num_attention_heads = num_attention_heads
  97. self.max_position_embeddings = max_position_embeddings
  98. self.layer_norm_eps = layer_norm_eps
  99. self.hidden_act = hidden_act
  100. self.initializer_range = initializer_range
  101. self.initializer_factor = initializer_factor
  102. self.attention_dropout = attention_dropout
  103. @classmethod
  104. def from_pretrained(cls, pretrained_model_name_or_path: Union[str, os.PathLike], **kwargs) -> "PretrainedConfig":
  105. cls._set_token_in_kwargs(kwargs)
  106. config_dict, kwargs = cls.get_config_dict(pretrained_model_name_or_path, **kwargs)
  107. # get the text config dict if we are loading from CLIPSegConfig
  108. if config_dict.get("model_type") == "clipseg":
  109. config_dict = config_dict["text_config"]
  110. if "model_type" in config_dict and hasattr(cls, "model_type") and config_dict["model_type"] != cls.model_type:
  111. logger.warning(
  112. f"You are using a model of type {config_dict['model_type']} to instantiate a model of type "
  113. f"{cls.model_type}. This is not supported for all configurations of models and can yield errors."
  114. )
  115. return cls.from_dict(config_dict, **kwargs)
  116. class CLIPSegVisionConfig(PretrainedConfig):
  117. r"""
  118. This is the configuration class to store the configuration of a [`CLIPSegModel`]. It is used to instantiate an
  119. CLIPSeg model according to the specified arguments, defining the model architecture. Instantiating a configuration
  120. with the defaults will yield a similar configuration to that of the CLIPSeg
  121. [CIDAS/clipseg-rd64](https://huggingface.co/CIDAS/clipseg-rd64) architecture.
  122. Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
  123. documentation from [`PretrainedConfig`] for more information.
  124. Args:
  125. hidden_size (`int`, *optional*, defaults to 768):
  126. Dimensionality of the encoder layers and the pooler layer.
  127. intermediate_size (`int`, *optional*, defaults to 3072):
  128. Dimensionality of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder.
  129. num_hidden_layers (`int`, *optional*, defaults to 12):
  130. Number of hidden layers in the Transformer encoder.
  131. num_attention_heads (`int`, *optional*, defaults to 12):
  132. Number of attention heads for each attention layer in the Transformer encoder.
  133. num_channels (`int`, *optional*, defaults to 3):
  134. The number of input channels.
  135. image_size (`int`, *optional*, defaults to 224):
  136. The size (resolution) of each image.
  137. patch_size (`int`, *optional*, defaults to 32):
  138. The size (resolution) of each patch.
  139. hidden_act (`str` or `function`, *optional*, defaults to `"quick_gelu"`):
  140. The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
  141. `"relu"`, `"selu"` and `"gelu_new"` `"quick_gelu"` are supported.
  142. layer_norm_eps (`float`, *optional*, defaults to 1e-05):
  143. The epsilon used by the layer normalization layers.
  144. attention_dropout (`float`, *optional*, defaults to 0.0):
  145. The dropout ratio for the attention probabilities.
  146. initializer_range (`float`, *optional*, defaults to 0.02):
  147. The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
  148. initializer_factor (`float`, *optional*, defaults to 1.0):
  149. A factor for initializing all weight matrices (should be kept to 1, used internally for initialization
  150. testing).
  151. Example:
  152. ```python
  153. >>> from transformers import CLIPSegVisionConfig, CLIPSegVisionModel
  154. >>> # Initializing a CLIPSegVisionConfig with CIDAS/clipseg-rd64 style configuration
  155. >>> configuration = CLIPSegVisionConfig()
  156. >>> # Initializing a CLIPSegVisionModel (with random weights) from the CIDAS/clipseg-rd64 style configuration
  157. >>> model = CLIPSegVisionModel(configuration)
  158. >>> # Accessing the model configuration
  159. >>> configuration = model.config
  160. ```"""
  161. model_type = "clipseg_vision_model"
  162. def __init__(
  163. self,
  164. hidden_size=768,
  165. intermediate_size=3072,
  166. num_hidden_layers=12,
  167. num_attention_heads=12,
  168. num_channels=3,
  169. image_size=224,
  170. patch_size=32,
  171. hidden_act="quick_gelu",
  172. layer_norm_eps=1e-5,
  173. attention_dropout=0.0,
  174. initializer_range=0.02,
  175. initializer_factor=1.0,
  176. **kwargs,
  177. ):
  178. super().__init__(**kwargs)
  179. self.hidden_size = hidden_size
  180. self.intermediate_size = intermediate_size
  181. self.num_hidden_layers = num_hidden_layers
  182. self.num_attention_heads = num_attention_heads
  183. self.num_channels = num_channels
  184. self.patch_size = patch_size
  185. self.image_size = image_size
  186. self.initializer_range = initializer_range
  187. self.initializer_factor = initializer_factor
  188. self.attention_dropout = attention_dropout
  189. self.layer_norm_eps = layer_norm_eps
  190. self.hidden_act = hidden_act
  191. @classmethod
  192. def from_pretrained(cls, pretrained_model_name_or_path: Union[str, os.PathLike], **kwargs) -> "PretrainedConfig":
  193. cls._set_token_in_kwargs(kwargs)
  194. config_dict, kwargs = cls.get_config_dict(pretrained_model_name_or_path, **kwargs)
  195. # get the vision config dict if we are loading from CLIPSegConfig
  196. if config_dict.get("model_type") == "clipseg":
  197. config_dict = config_dict["vision_config"]
  198. if "model_type" in config_dict and hasattr(cls, "model_type") and config_dict["model_type"] != cls.model_type:
  199. logger.warning(
  200. f"You are using a model of type {config_dict['model_type']} to instantiate a model of type "
  201. f"{cls.model_type}. This is not supported for all configurations of models and can yield errors."
  202. )
  203. return cls.from_dict(config_dict, **kwargs)
  204. class CLIPSegConfig(PretrainedConfig):
  205. r"""
  206. [`CLIPSegConfig`] is the configuration class to store the configuration of a [`CLIPSegModel`]. It is used to
  207. instantiate a CLIPSeg model according to the specified arguments, defining the text model and vision model configs.
  208. Instantiating a configuration with the defaults will yield a similar configuration to that of the CLIPSeg
  209. [CIDAS/clipseg-rd64](https://huggingface.co/CIDAS/clipseg-rd64) architecture.
  210. Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
  211. documentation from [`PretrainedConfig`] for more information.
  212. Args:
  213. text_config (`dict`, *optional*):
  214. Dictionary of configuration options used to initialize [`CLIPSegTextConfig`].
  215. vision_config (`dict`, *optional*):
  216. Dictionary of configuration options used to initialize [`CLIPSegVisionConfig`].
  217. projection_dim (`int`, *optional*, defaults to 512):
  218. Dimensionality of text and vision projection layers.
  219. logit_scale_init_value (`float`, *optional*, defaults to 2.6592):
  220. The initial value of the *logit_scale* parameter. Default is used as per the original CLIPSeg implementation.
  221. extract_layers (`List[int]`, *optional*, defaults to `[3, 6, 9]`):
  222. Layers to extract when forwarding the query image through the frozen visual backbone of CLIP.
  223. reduce_dim (`int`, *optional*, defaults to 64):
  224. Dimensionality to reduce the CLIP vision embedding.
  225. decoder_num_attention_heads (`int`, *optional*, defaults to 4):
  226. Number of attention heads in the decoder of CLIPSeg.
  227. decoder_attention_dropout (`float`, *optional*, defaults to 0.0):
  228. The dropout ratio for the attention probabilities.
  229. decoder_hidden_act (`str` or `function`, *optional*, defaults to `"quick_gelu"`):
  230. The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
  231. `"relu"`, `"selu"` and `"gelu_new"` `"quick_gelu"` are supported.
  232. decoder_intermediate_size (`int`, *optional*, defaults to 2048):
  233. Dimensionality of the "intermediate" (i.e., feed-forward) layers in the Transformer decoder.
  234. conditional_layer (`int`, *optional*, defaults to 0):
  235. The layer to use of the Transformer encoder whose activations will be combined with the condition
  236. embeddings using FiLM (Feature-wise Linear Modulation). If 0, the last layer is used.
  237. use_complex_transposed_convolution (`bool`, *optional*, defaults to `False`):
  238. Whether to use a more complex transposed convolution in the decoder, enabling more fine-grained
  239. segmentation.
  240. kwargs (*optional*):
  241. Dictionary of keyword arguments.
  242. Example:
  243. ```python
  244. >>> from transformers import CLIPSegConfig, CLIPSegModel
  245. >>> # Initializing a CLIPSegConfig with CIDAS/clipseg-rd64 style configuration
  246. >>> configuration = CLIPSegConfig()
  247. >>> # Initializing a CLIPSegModel (with random weights) from the CIDAS/clipseg-rd64 style configuration
  248. >>> model = CLIPSegModel(configuration)
  249. >>> # Accessing the model configuration
  250. >>> configuration = model.config
  251. >>> # We can also initialize a CLIPSegConfig from a CLIPSegTextConfig and a CLIPSegVisionConfig
  252. >>> # Initializing a CLIPSegText and CLIPSegVision configuration
  253. >>> config_text = CLIPSegTextConfig()
  254. >>> config_vision = CLIPSegVisionConfig()
  255. >>> config = CLIPSegConfig.from_text_vision_configs(config_text, config_vision)
  256. ```"""
  257. model_type = "clipseg"
  258. def __init__(
  259. self,
  260. text_config=None,
  261. vision_config=None,
  262. projection_dim=512,
  263. logit_scale_init_value=2.6592,
  264. extract_layers=[3, 6, 9],
  265. reduce_dim=64,
  266. decoder_num_attention_heads=4,
  267. decoder_attention_dropout=0.0,
  268. decoder_hidden_act="quick_gelu",
  269. decoder_intermediate_size=2048,
  270. conditional_layer=0,
  271. use_complex_transposed_convolution=False,
  272. **kwargs,
  273. ):
  274. # If `_config_dict` exist, we use them for the backward compatibility.
  275. # We pop out these 2 attributes before calling `super().__init__` to avoid them being saved (which causes a lot
  276. # of confusion!).
  277. text_config_dict = kwargs.pop("text_config_dict", None)
  278. vision_config_dict = kwargs.pop("vision_config_dict", None)
  279. super().__init__(**kwargs)
  280. # Instead of simply assigning `[text|vision]_config_dict` to `[text|vision]_config`, we use the values in
  281. # `[text|vision]_config_dict` to update the values in `[text|vision]_config`. The values should be same in most
  282. # cases, but we don't want to break anything regarding `_config_dict` that existed before commit `8827e1b2`.
  283. if text_config_dict is not None:
  284. if text_config is None:
  285. text_config = {}
  286. # This is the complete result when using `text_config_dict`.
  287. _text_config_dict = CLIPSegTextConfig(**text_config_dict).to_dict()
  288. # Give a warning if the values exist in both `_text_config_dict` and `text_config` but being different.
  289. for key, value in _text_config_dict.items():
  290. if key in text_config and value != text_config[key] and key not in ["transformers_version"]:
  291. # If specified in `text_config_dict`
  292. if key in text_config_dict:
  293. message = (
  294. f"`{key}` is found in both `text_config_dict` and `text_config` but with different values. "
  295. f'The value `text_config_dict["{key}"]` will be used instead.'
  296. )
  297. # If inferred from default argument values (just to be super careful)
  298. else:
  299. message = (
  300. f"`text_config_dict` is provided which will be used to initialize `CLIPSegTextConfig`. The "
  301. f'value `text_config["{key}"]` will be overridden.'
  302. )
  303. logger.info(message)
  304. # Update all values in `text_config` with the ones in `_text_config_dict`.
  305. text_config.update(_text_config_dict)
  306. if vision_config_dict is not None:
  307. if vision_config is None:
  308. vision_config = {}
  309. # This is the complete result when using `vision_config_dict`.
  310. _vision_config_dict = CLIPSegVisionConfig(**vision_config_dict).to_dict()
  311. # convert keys to string instead of integer
  312. if "id2label" in _vision_config_dict:
  313. _vision_config_dict["id2label"] = {
  314. str(key): value for key, value in _vision_config_dict["id2label"].items()
  315. }
  316. # Give a warning if the values exist in both `_vision_config_dict` and `vision_config` but being different.
  317. for key, value in _vision_config_dict.items():
  318. if key in vision_config and value != vision_config[key] and key not in ["transformers_version"]:
  319. # If specified in `vision_config_dict`
  320. if key in vision_config_dict:
  321. message = (
  322. f"`{key}` is found in both `vision_config_dict` and `vision_config` but with different "
  323. f'values. The value `vision_config_dict["{key}"]` will be used instead.'
  324. )
  325. # If inferred from default argument values (just to be super careful)
  326. else:
  327. message = (
  328. f"`vision_config_dict` is provided which will be used to initialize `CLIPSegVisionConfig`. "
  329. f'The value `vision_config["{key}"]` will be overridden.'
  330. )
  331. logger.info(message)
  332. # Update all values in `vision_config` with the ones in `_vision_config_dict`.
  333. vision_config.update(_vision_config_dict)
  334. if text_config is None:
  335. text_config = {}
  336. logger.info("`text_config` is `None`. Initializing the `CLIPSegTextConfig` with default values.")
  337. if vision_config is None:
  338. vision_config = {}
  339. logger.info("`vision_config` is `None`. initializing the `CLIPSegVisionConfig` with default values.")
  340. self.text_config = CLIPSegTextConfig(**text_config)
  341. self.vision_config = CLIPSegVisionConfig(**vision_config)
  342. self.projection_dim = projection_dim
  343. self.logit_scale_init_value = logit_scale_init_value
  344. self.extract_layers = extract_layers
  345. self.reduce_dim = reduce_dim
  346. self.decoder_num_attention_heads = decoder_num_attention_heads
  347. self.decoder_attention_dropout = decoder_attention_dropout
  348. self.decoder_hidden_act = decoder_hidden_act
  349. self.decoder_intermediate_size = decoder_intermediate_size
  350. self.conditional_layer = conditional_layer
  351. self.initializer_factor = 1.0
  352. self.use_complex_transposed_convolution = use_complex_transposed_convolution
  353. @classmethod
  354. def from_text_vision_configs(cls, text_config: CLIPSegTextConfig, vision_config: CLIPSegVisionConfig, **kwargs):
  355. r"""
  356. Instantiate a [`CLIPSegConfig`] (or a derived class) from clipseg text model configuration and clipseg vision
  357. model configuration.
  358. Returns:
  359. [`CLIPSegConfig`]: An instance of a configuration object
  360. """
  361. return cls(text_config=text_config.to_dict(), vision_config=vision_config.to_dict(), **kwargs)