configuration_clipseg.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238
  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. """CLIPSeg 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="CIDAS/clipseg-rd64")
  20. @strict
  21. class CLIPSegTextConfig(PreTrainedConfig):
  22. r"""
  23. Example:
  24. ```python
  25. >>> from transformers import CLIPSegTextConfig, CLIPSegTextModel
  26. >>> # Initializing a CLIPSegTextConfig with CIDAS/clipseg-rd64 style configuration
  27. >>> configuration = CLIPSegTextConfig()
  28. >>> # Initializing a CLIPSegTextModel (with random weights) from the CIDAS/clipseg-rd64 style configuration
  29. >>> model = CLIPSegTextModel(configuration)
  30. >>> # Accessing the model configuration
  31. >>> configuration = model.config
  32. ```"""
  33. model_type = "clipseg_text_model"
  34. base_config_key = "text_config"
  35. vocab_size: int = 49408
  36. hidden_size: int = 512
  37. intermediate_size: int = 2048
  38. num_hidden_layers: int = 12
  39. num_attention_heads: int = 8
  40. max_position_embeddings: int = 77
  41. hidden_act: str = "quick_gelu"
  42. layer_norm_eps: float = 1e-5
  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="CIDAS/clipseg-rd64")
  50. @strict
  51. class CLIPSegVisionConfig(PreTrainedConfig):
  52. r"""
  53. Example:
  54. ```python
  55. >>> from transformers import CLIPSegVisionConfig, CLIPSegVisionModel
  56. >>> # Initializing a CLIPSegVisionConfig with CIDAS/clipseg-rd64 style configuration
  57. >>> configuration = CLIPSegVisionConfig()
  58. >>> # Initializing a CLIPSegVisionModel (with random weights) from the CIDAS/clipseg-rd64 style configuration
  59. >>> model = CLIPSegVisionModel(configuration)
  60. >>> # Accessing the model configuration
  61. >>> configuration = model.config
  62. ```"""
  63. model_type = "clipseg_vision_model"
  64. base_config_key = "vision_config"
  65. hidden_size: int = 768
  66. intermediate_size: int = 3072
  67. num_hidden_layers: int = 12
  68. num_attention_heads: int = 12
  69. num_channels: int = 3
  70. image_size: int | list[int] | tuple[int, int] = 224
  71. patch_size: int | list[int] | tuple[int, int] = 32
  72. hidden_act: str = "quick_gelu"
  73. layer_norm_eps: float = 1e-5
  74. attention_dropout: float | int = 0.0
  75. initializer_range: float = 0.02
  76. initializer_factor: float = 1.0
  77. @auto_docstring(checkpoint="CIDAS/clipseg-rd64")
  78. @strict
  79. class CLIPSegConfig(PreTrainedConfig):
  80. r"""
  81. extract_layers (`list[int]`, *optional*, defaults to `[3, 6, 9]`):
  82. Layers to extract when forwarding the query image through the frozen visual backbone of CLIP.
  83. reduce_dim (`int`, *optional*, defaults to 64):
  84. Dimensionality to reduce the CLIP vision embedding.
  85. conditional_layer (`int`, *optional*, defaults to 0):
  86. The layer to use of the Transformer encoder whose activations will be combined with the condition
  87. embeddings using FiLM (Feature-wise Linear Modulation). If 0, the last layer is used.
  88. use_complex_transposed_convolution (`bool`, *optional*, defaults to `False`):
  89. Whether to use a more complex transposed convolution in the decoder, enabling more fine-grained
  90. segmentation..
  91. Example:
  92. ```python
  93. >>> from transformers import CLIPSegConfig, CLIPSegModel
  94. >>> # Initializing a CLIPSegConfig with CIDAS/clipseg-rd64 style configuration
  95. >>> configuration = CLIPSegConfig()
  96. >>> # Initializing a CLIPSegModel (with random weights) from the CIDAS/clipseg-rd64 style configuration
  97. >>> model = CLIPSegModel(configuration)
  98. >>> # Accessing the model configuration
  99. >>> configuration = model.config
  100. >>> # We can also initialize a CLIPSegConfig from a CLIPSegTextConfig and a CLIPSegVisionConfig
  101. >>> # Initializing a CLIPSegText and CLIPSegVision configuration
  102. >>> config_text = CLIPSegTextConfig()
  103. >>> config_vision = CLIPSegVisionConfig()
  104. >>> config = CLIPSegConfig(text_config=config_text, vision_config=config_vision)
  105. ```"""
  106. model_type = "clipseg"
  107. sub_configs = {"text_config": CLIPSegTextConfig, "vision_config": CLIPSegVisionConfig}
  108. text_config: dict | CLIPSegTextConfig | None = None
  109. vision_config: dict | CLIPSegVisionConfig | None = None
  110. projection_dim: int | None = 512
  111. logit_scale_init_value: float | int | None = 2.6592
  112. initializer_factor: float | None = 1.0
  113. extract_layers: list[int] | tuple[int, ...] = (3, 6, 9)
  114. reduce_dim: int = 64
  115. decoder_num_attention_heads: int = 4
  116. decoder_attention_dropout: float | int = 0.0
  117. decoder_hidden_act: str = "quick_gelu"
  118. decoder_intermediate_size: int = 2048
  119. conditional_layer: int = 0
  120. use_complex_transposed_convolution: bool = False
  121. def __post_init__(self, **kwargs):
  122. if self.text_config is None:
  123. text_config = {}
  124. logger.info("`text_config` is `None`. Initializing the `CLIPSegTextConfig` with default values.")
  125. elif isinstance(self.text_config, CLIPSegTextConfig):
  126. text_config = self.text_config.to_dict()
  127. else:
  128. text_config = self.text_config
  129. if self.vision_config is None:
  130. vision_config = {}
  131. logger.info("`vision_config` is `None`. initializing the `CLIPSegVisionConfig` with default values.")
  132. elif isinstance(self.vision_config, CLIPSegVisionConfig):
  133. vision_config = self.vision_config.to_dict()
  134. else:
  135. vision_config = self.vision_config
  136. # For backward compatibility check keyword args
  137. # Instead of simply assigning `[text|vision]_config_dict` to `[text|vision]_config`, we use the values in
  138. # `[text|vision]_config_dict` to update the values in `[text|vision]_config`. The values should be same in most
  139. # cases, but we don't want to break anything regarding `_config_dict` that existed before commit `8827e1b2`.
  140. text_config_dict = kwargs.pop("text_config_dict", None)
  141. vision_config_dict = kwargs.pop("vision_config_dict", None)
  142. if text_config_dict is not None:
  143. # This is the complete result when using `text_config_dict`.
  144. _text_config_dict = CLIPSegTextConfig(**text_config_dict).to_dict()
  145. # Give a warning if the values exist in both `_text_config_dict` and `text_config` but being different.
  146. for key, value in _text_config_dict.items():
  147. if key in text_config and value != text_config[key] and key != "transformers_version":
  148. # If specified in `text_config_dict`
  149. if key in text_config_dict:
  150. message = (
  151. f"`{key}` is found in both `text_config_dict` and `text_config` but with different values. "
  152. f'The value `text_config_dict["{key}"]` will be used instead.'
  153. )
  154. # If inferred from default argument values (just to be super careful)
  155. else:
  156. message = (
  157. f"`text_config_dict` is provided which will be used to initialize `CLIPSegTextConfig`. The "
  158. f'value `text_config["{key}"]` will be overridden.'
  159. )
  160. logger.info(message)
  161. # Update all values in `text_config` with the ones in `_text_config_dict`.
  162. text_config.update(_text_config_dict)
  163. if vision_config_dict is not None:
  164. # This is the complete result when using `vision_config_dict`.
  165. _vision_config_dict = CLIPSegVisionConfig(**vision_config_dict).to_dict()
  166. # convert keys to string instead of integer
  167. if "id2label" in _vision_config_dict:
  168. _vision_config_dict["id2label"] = {
  169. str(key): value for key, value in _vision_config_dict["id2label"].items()
  170. }
  171. # Give a warning if the values exist in both `_vision_config_dict` and `vision_config` but being different.
  172. for key, value in _vision_config_dict.items():
  173. if key in vision_config and value != vision_config[key] and key != "transformers_version":
  174. # If specified in `vision_config_dict`
  175. if key in vision_config_dict:
  176. message = (
  177. f"`{key}` is found in both `vision_config_dict` and `vision_config` but with different "
  178. f'values. The value `vision_config_dict["{key}"]` will be used instead.'
  179. )
  180. # If inferred from default argument values (just to be super careful)
  181. else:
  182. message = (
  183. f"`vision_config_dict` is provided which will be used to initialize `CLIPSegVisionConfig`. "
  184. f'The value `vision_config["{key}"]` will be overridden.'
  185. )
  186. logger.info(message)
  187. # Update all values in `vision_config` with the ones in `_vision_config_dict`.
  188. vision_config.update(_vision_config_dict)
  189. # Finally we can convert back our unified text/vision configs to `PretrainedConfig`
  190. self.text_config = CLIPSegTextConfig(**text_config)
  191. self.vision_config = CLIPSegVisionConfig(**vision_config)
  192. super().__post_init__(**kwargs)
  193. __all__ = ["CLIPSegConfig", "CLIPSegTextConfig", "CLIPSegVisionConfig"]