configuration_clipseg.py 18 KB

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