configuration_clap.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382
  1. # coding=utf-8
  2. # Copyright 2023 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. """CLAP model configuration"""
  16. from ...configuration_utils import PretrainedConfig
  17. from ...utils import logging
  18. logger = logging.get_logger(__name__)
  19. class ClapTextConfig(PretrainedConfig):
  20. r"""
  21. This is the configuration class to store the configuration of a [`ClapTextModel`]. It is used to instantiate a CLAP
  22. model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
  23. defaults will yield a similar configuration to that of the CLAP
  24. [calp-hsat-fused](https://huggingface.co/laion/clap-hsat-fused) 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 30522):
  29. Vocabulary size of the CLAP model. Defines the number of different tokens that can be represented by the
  30. `inputs_ids` passed when calling [`ClapTextModel`].
  31. hidden_size (`int`, *optional*, defaults to 768):
  32. Dimensionality of the encoder layers and the pooler layer.
  33. num_hidden_layers (`int`, *optional*, defaults to 12):
  34. Number of hidden layers in the Transformer encoder.
  35. num_attention_heads (`int`, *optional*, defaults to 12):
  36. Number of attention heads for each attention layer in the Transformer encoder.
  37. intermediate_size (`int`, *optional*, defaults to 3072):
  38. Dimensionality of the "intermediate" (often named feed-forward) layer in the Transformer encoder.
  39. hidden_act (`str` or `Callable`, *optional*, defaults to `"relu"`):
  40. The non-linear activation function (function or string) in the encoder and pooler. If string, `"relu"`,
  41. `"relu"`, `"silu"` and `"relu_new"` are supported.
  42. hidden_dropout_prob (`float`, *optional*, defaults to 0.1):
  43. The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
  44. attention_probs_dropout_prob (`float`, *optional*, defaults to 0.1):
  45. The dropout ratio for the attention probabilities.
  46. max_position_embeddings (`int`, *optional*, defaults to 512):
  47. The maximum sequence length that this model might ever be used with. Typically set this to something large
  48. just in case (e.g., 512 or 1024 or 2048).
  49. type_vocab_size (`int`, *optional*, defaults to 2):
  50. The vocabulary size of the `token_type_ids` passed when calling [`ClapTextModel`].
  51. layer_norm_eps (`float`, *optional*, defaults to 1e-12):
  52. The epsilon used by the layer normalization layers.
  53. position_embedding_type (`str`, *optional*, defaults to `"absolute"`):
  54. Type of position embedding. Choose one of `"absolute"`, `"relative_key"`, `"relative_key_query"`. For
  55. positional embeddings use `"absolute"`. For more information on `"relative_key"`, please refer to
  56. [Self-Attention with Relative Position Representations (Shaw et al.)](https://huggingface.co/papers/1803.02155).
  57. For more information on `"relative_key_query"`, please refer to *Method 4* in [Improve Transformer Models
  58. with Better Relative Position Embeddings (Huang et al.)](https://huggingface.co/papers/2009.13658).
  59. is_decoder (`bool`, *optional*, defaults to `False`):
  60. Whether the model is used as a decoder or not. If `False`, the model is used as an encoder.
  61. use_cache (`bool`, *optional*, defaults to `True`):
  62. Whether or not the model should return the last key/values attentions (not used by all models). Only
  63. relevant if `config.is_decoder=True`.
  64. projection_hidden_act (`str`, *optional*, defaults to `"relu"`):
  65. The non-linear activation function (function or string) in the projection layer. If string, `"gelu"`,
  66. `"relu"`, `"silu"` and `"gelu_new"` are supported.
  67. projection_dim (`int`, *optional*, defaults to 512)
  68. Dimension of the projection head of the `ClapTextModelWithProjection`.
  69. Examples:
  70. ```python
  71. >>> from transformers import ClapTextConfig, ClapTextModel
  72. >>> # Initializing a CLAP text configuration
  73. >>> configuration = ClapTextConfig()
  74. >>> # Initializing a model (with random weights) from the configuration
  75. >>> model = ClapTextModel(configuration)
  76. >>> # Accessing the model configuration
  77. >>> configuration = model.config
  78. ```"""
  79. model_type = "clap_text_model"
  80. base_config_key = "text_config"
  81. def __init__(
  82. self,
  83. vocab_size=50265,
  84. hidden_size=768,
  85. num_hidden_layers=12,
  86. num_attention_heads=12,
  87. intermediate_size=3072,
  88. hidden_act="gelu",
  89. hidden_dropout_prob=0.1,
  90. attention_probs_dropout_prob=0.1,
  91. max_position_embeddings=514,
  92. type_vocab_size=1,
  93. initializer_factor=1.0,
  94. layer_norm_eps=1e-12,
  95. projection_dim=512,
  96. pad_token_id=1,
  97. bos_token_id=0,
  98. eos_token_id=2,
  99. position_embedding_type="absolute",
  100. use_cache=True,
  101. projection_hidden_act="relu",
  102. **kwargs,
  103. ):
  104. super().__init__(pad_token_id=pad_token_id, bos_token_id=bos_token_id, eos_token_id=eos_token_id, **kwargs)
  105. self.vocab_size = vocab_size
  106. self.hidden_size = hidden_size
  107. self.num_hidden_layers = num_hidden_layers
  108. self.num_attention_heads = num_attention_heads
  109. self.hidden_act = hidden_act
  110. self.intermediate_size = intermediate_size
  111. self.hidden_dropout_prob = hidden_dropout_prob
  112. self.attention_probs_dropout_prob = attention_probs_dropout_prob
  113. self.max_position_embeddings = max_position_embeddings
  114. self.type_vocab_size = type_vocab_size
  115. self.initializer_factor = initializer_factor
  116. self.layer_norm_eps = layer_norm_eps
  117. self.position_embedding_type = position_embedding_type
  118. self.use_cache = use_cache
  119. self.projection_hidden_act = projection_hidden_act
  120. self.projection_dim = projection_dim
  121. class ClapAudioConfig(PretrainedConfig):
  122. r"""
  123. This is the configuration class to store the configuration of a [`ClapAudioModel`]. It is used to instantiate a
  124. CLAP audio encoder according to the specified arguments, defining the model architecture. Instantiating a
  125. configuration with the defaults will yield a similar configuration to that of the audio encoder of the CLAP
  126. [laion/clap-htsat-fused](https://huggingface.co/laion/clap-htsat-fused) architecture.
  127. Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
  128. documentation from [`PretrainedConfig`] for more information.
  129. Args:
  130. window_size (`int`, *optional*, defaults to 8):
  131. Image size of the spectrogram
  132. num_mel_bins (`int`, *optional*, defaults to 64):
  133. Number of mel features used per frames. Should correspond to the value used in the `ClapProcessor` class.
  134. spec_size (`int`, *optional*, defaults to 256):
  135. Desired input size of the spectrogram that the model supports. It can be different from the output of the
  136. `ClapFeatureExtractor`, in which case the input features will be resized. Corresponds to the `image_size`
  137. of the audio models.
  138. hidden_act (`str`, *optional*, defaults to `"gelu"`):
  139. The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
  140. `"relu"`, `"silu"` and `"gelu_new"` are supported.
  141. patch_size (`int`, *optional*, defaults to 4):
  142. Patch size for the audio spectrogram
  143. patch_stride (`list`, *optional*, defaults to `[4, 4]`):
  144. Patch stride for the audio spectrogram
  145. num_classes (`int`, *optional*, defaults to 527):
  146. Number of classes used for the head training
  147. hidden_size (`int`, *optional*, defaults to 768):
  148. Hidden size of the output of the audio encoder. Correspond to the dimension of the penultimate layer's
  149. output,which is sent to the projection MLP layer.
  150. projection_dim (`int`, *optional*, defaults to 512):
  151. Hidden size of the projection layer.
  152. depths (`list`, *optional*, defaults to `[2, 2, 6, 2]`):
  153. Depths used for the Swin Layers of the audio model
  154. num_attention_heads (`list`, *optional*, defaults to `[4, 8, 16, 32]`):
  155. Number of attention heads used for the Swin Layers of the audio model
  156. enable_fusion (`bool`, *optional*, defaults to `False`):
  157. Whether or not to enable patch fusion. This is the main contribution of the authors, and should give the
  158. best results.
  159. hidden_dropout_prob (`float`, *optional*, defaults to 0.1):
  160. The dropout probability for all fully connected layers in the encoder.
  161. fusion_type (`[type]`, *optional*):
  162. Fusion type used for the patch fusion.
  163. patch_embed_input_channels (`int`, *optional*, defaults to 1):
  164. Number of channels used for the input spectrogram
  165. flatten_patch_embeds (`bool`, *optional*, defaults to `True`):
  166. Whether or not to flatten the patch embeddings
  167. patch_embeds_hidden_size (`int`, *optional*, defaults to 96):
  168. Hidden size of the patch embeddings. It is used as the number of output channels.
  169. enable_patch_layer_norm (`bool`, *optional*, defaults to `True`):
  170. Whether or not to enable layer normalization for the patch embeddings
  171. drop_path_rate (`float`, *optional*, defaults to 0.0):
  172. Drop path rate for the patch fusion
  173. attention_probs_dropout_prob (`float`, *optional*, defaults to 0.0):
  174. The dropout ratio for the attention probabilities.
  175. qkv_bias (`bool`, *optional*, defaults to `True`):
  176. Whether or not to add a bias to the query, key, value projections.
  177. mlp_ratio (`float`, *optional*, defaults to 4.0):
  178. Ratio of the mlp hidden dim to embedding dim.
  179. aff_block_r (`int`, *optional*, defaults to 4):
  180. downsize_ratio used in the AudioFF block
  181. num_hidden_layers (`int`, *optional*, defaults to 4):
  182. Number of hidden layers in the Transformer encoder.
  183. projection_hidden_act (`str`, *optional*, defaults to `"relu"`):
  184. The non-linear activation function (function or string) in the projection layer. If string, `"gelu"`,
  185. `"relu"`, `"silu"` and `"gelu_new"` are supported.
  186. layer_norm_eps (`[type]`, *optional*, defaults to 1e-05):
  187. The epsilon used by the layer normalization layers.
  188. initializer_factor (`float`, *optional*, defaults to 1.0):
  189. A factor for initializing all weight matrices (should be kept to 1, used internally for initialization
  190. testing).
  191. Example:
  192. ```python
  193. >>> from transformers import ClapAudioConfig, ClapAudioModel
  194. >>> # Initializing a ClapAudioConfig with laion/clap-htsat-fused style configuration
  195. >>> configuration = ClapAudioConfig()
  196. >>> # Initializing a ClapAudioModel (with random weights) from the laion/clap-htsat-fused style configuration
  197. >>> model = ClapAudioModel(configuration)
  198. >>> # Accessing the model configuration
  199. >>> configuration = model.config
  200. ```"""
  201. model_type = "clap_audio_model"
  202. base_config_key = "audio_config"
  203. def __init__(
  204. self,
  205. window_size=8,
  206. num_mel_bins=64,
  207. spec_size=256,
  208. hidden_act="gelu",
  209. patch_size=4,
  210. patch_stride=[4, 4],
  211. num_classes=527,
  212. hidden_size=768,
  213. projection_dim=512,
  214. depths=[2, 2, 6, 2],
  215. num_attention_heads=[4, 8, 16, 32],
  216. enable_fusion=False,
  217. hidden_dropout_prob=0.1,
  218. fusion_type=None,
  219. patch_embed_input_channels=1,
  220. flatten_patch_embeds=True,
  221. patch_embeds_hidden_size=96,
  222. enable_patch_layer_norm=True,
  223. drop_path_rate=0.0,
  224. attention_probs_dropout_prob=0.0,
  225. qkv_bias=True,
  226. mlp_ratio=4.0,
  227. aff_block_r=4,
  228. num_hidden_layers=4,
  229. projection_hidden_act="relu",
  230. layer_norm_eps=1e-5,
  231. initializer_factor=1.0,
  232. **kwargs,
  233. ):
  234. super().__init__(**kwargs)
  235. self.window_size = window_size
  236. self.num_mel_bins = num_mel_bins
  237. self.spec_size = spec_size
  238. self.patch_size = patch_size
  239. self.patch_stride = patch_stride
  240. self.num_classes = num_classes
  241. self.hidden_size = hidden_size
  242. self.depths = depths
  243. self.num_hidden_layers = num_hidden_layers
  244. self.num_attention_heads = num_attention_heads
  245. self.window_size = window_size
  246. self.enable_fusion = enable_fusion
  247. self.fusion_type = fusion_type
  248. self.hidden_act = hidden_act
  249. self.hidden_dropout_prob = hidden_dropout_prob
  250. self.projection_dim = projection_dim
  251. self.flatten_patch_embeds = flatten_patch_embeds
  252. self.patch_embeds_hidden_size = patch_embeds_hidden_size
  253. self.enable_patch_layer_norm = enable_patch_layer_norm
  254. self.drop_path_rate = drop_path_rate
  255. self.attention_probs_dropout_prob = attention_probs_dropout_prob
  256. self.qkv_bias = qkv_bias
  257. self.mlp_ratio = mlp_ratio
  258. self.patch_embed_input_channels = patch_embed_input_channels
  259. self.aff_block_r = aff_block_r
  260. self.layer_norm_eps = layer_norm_eps
  261. self.initializer_factor = initializer_factor
  262. self.projection_hidden_act = projection_hidden_act
  263. class ClapConfig(PretrainedConfig):
  264. r"""
  265. [`ClapConfig`] is the configuration class to store the configuration of a [`ClapModel`]. It is used to instantiate
  266. a CLAP model according to the specified arguments, defining the text model and audio model configs. Instantiating a
  267. configuration with the defaults will yield a similar configuration to that of the CLAP
  268. [laion/clap-htsat-fused](https://huggingface.co/laion/clap-htsat-fused) architecture.
  269. Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
  270. documentation from [`PretrainedConfig`] for more information.
  271. Args:
  272. text_config (`dict`, *optional*):
  273. Dictionary of configuration options used to initialize [`ClapTextConfig`].
  274. audio_config (`dict`, *optional*):
  275. Dictionary of configuration options used to initialize [`ClapAudioConfig`].
  276. logit_scale_init_value (`float`, *optional*, defaults to 14.29):
  277. The initial value of the *logit_scale* parameter. Default is used as per the original CLAP implementation.
  278. projection_dim (`int`, *optional*, defaults to 512):
  279. Dimensionality of text and audio projection layers.
  280. projection_hidden_act (`str`, *optional*, defaults to `"relu"`):
  281. Activation function for the projection layers.
  282. initializer_factor (`float`, *optional*, defaults to 1.0):
  283. Factor to scale the initialization of the model weights.
  284. kwargs (*optional*):
  285. Dictionary of keyword arguments.
  286. Example:
  287. ```python
  288. >>> from transformers import ClapConfig, ClapModel
  289. >>> # Initializing a ClapConfig with laion-ai/base style configuration
  290. >>> configuration = ClapConfig()
  291. >>> # Initializing a ClapModel (with random weights) from the laion-ai/base style configuration
  292. >>> model = ClapModel(configuration)
  293. >>> # Accessing the model configuration
  294. >>> configuration = model.config
  295. >>> # We can also initialize a ClapConfig from a ClapTextConfig and a ClapAudioConfig
  296. >>> from transformers import ClapTextConfig, ClapAudioConfig
  297. >>> # Initializing a ClapText and ClapAudioConfig configuration
  298. >>> config_text = ClapTextConfig()
  299. >>> config_audio = ClapAudioConfig()
  300. >>> config = ClapConfig.from_text_audio_configs(config_text, config_audio)
  301. ```"""
  302. model_type = "clap"
  303. sub_configs = {"text_config": ClapTextConfig, "audio_config": ClapAudioConfig}
  304. def __init__(
  305. self,
  306. text_config=None,
  307. audio_config=None,
  308. logit_scale_init_value=(1 / 0.07),
  309. projection_dim=512,
  310. projection_hidden_act="relu",
  311. initializer_factor=1.0,
  312. **kwargs,
  313. ):
  314. super().__init__(**kwargs)
  315. if text_config is None:
  316. text_config = {}
  317. logger.info("text_config is None. Initializing the ClapTextConfig with default values.")
  318. if audio_config is None:
  319. audio_config = {}
  320. logger.info("audio_config is None. initializing the ClapAudioConfig with default values.")
  321. self.text_config = ClapTextConfig(**text_config)
  322. self.audio_config = ClapAudioConfig(**audio_config)
  323. self.text_config.projection_dim = projection_dim
  324. self.audio_config.projection_dim = projection_dim
  325. self.text_config.projection_hidden_act = projection_hidden_act
  326. self.audio_config.projection_hidden_act = projection_hidden_act
  327. self.projection_dim = projection_dim
  328. self.projection_hidden_act = projection_hidden_act
  329. self.hidden_size = self.text_config.hidden_size
  330. self.logit_scale_init_value = logit_scale_init_value
  331. self.initializer_factor = initializer_factor
  332. self.num_hidden_layers = self.text_config.num_hidden_layers + len(self.audio_config.depths)
  333. __all__ = ["ClapAudioConfig", "ClapConfig", "ClapTextConfig"]