configuration_clvp.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439
  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. """CLVP 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 ClvpEncoderConfig(PretrainedConfig):
  22. r"""
  23. This is the configuration class to store the configuration of a [`ClvpEncoder`]. It is used to instantiate a CLVP
  24. text or CLVP speech encoder according to the specified arguments. Instantiating a configuration with the defaults
  25. will yield a similar configuration to that of the encoder of the CLVP
  26. [susnato/clvp_dev](https://huggingface.co/susnato/clvp_dev) 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 256):
  31. Vocabulary size of the CLVP Encoder model.
  32. hidden_size (`int`, *optional*, defaults to 768):
  33. Dimensionality of the encoder layers and the pooler layer.
  34. intermediate_size (`int`, *optional*, defaults to 1536):
  35. Dimensionality of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder.
  36. projection_dim (`int`, *optional*, defaults to 768):
  37. Dimensionality of the projection vector.
  38. num_hidden_layers (`int`, *optional*, defaults to 20):
  39. Number of hidden layers in the Transformer encoder.
  40. num_attention_heads (`int`, *optional*, defaults to 12):
  41. Number of attention heads for each attention layer in the Transformer encoder.
  42. hidden_act (`str` or `function`, *optional*, defaults to `"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.1):
  48. The dropout ratio for the attention probabilities.
  49. dropout (`float`, *optional*, defaults to 0.1):
  50. The dropout ratio for the feed-forward layers in [`ClvpEncoderMLP`].
  51. use_rotary_embedding (`bool`, *optional*, defaults to `True`):
  52. Whether to use rotary_embedding or not.
  53. use_attention_bias (`bool`, *optional*, defaults to `False`):
  54. Whether to use bias in Query, Key and Value layers during self attention.
  55. summary_type (`str`, *optional*, defaults to `"mean"`):
  56. What strategy to use to get pooler_output from the last_hidden_state. `"last"`, `"first"`, `"mean"` and
  57. `"cls_index"` are supported.
  58. initializer_factor (`float`, *optional*, defaults to 1.0):
  59. A factor for initializing all weight matrices (should be kept to 1.0, used internally for initialization
  60. testing).
  61. bos_token_id (`int`, *optional*, defaults to 255):
  62. Beginning of sequence token id.
  63. eos_token_id (`int`, *optional*, defaults to 0):
  64. End of sequence token id.
  65. Example:
  66. ```python
  67. >>> from transformers import ClvpEncoderConfig, ClvpEncoder
  68. >>> # Initializing a ClvpEncoderConfig with susnato/clvp_dev style configuration
  69. >>> encoder_configuration = ClvpEncoderConfig()
  70. >>> # Initializing a ClvpEncoder (with random weights) from the susnato/clvp_dev style configuration
  71. >>> model = ClvpEncoder(encoder_configuration)
  72. >>> # Accessing the model configuration
  73. >>> configuration = model.config
  74. ```"""
  75. model_type = "clvp_encoder"
  76. base_config_key = ["text_config", "speech_config"]
  77. def __init__(
  78. self,
  79. vocab_size=256,
  80. hidden_size=768,
  81. intermediate_size=1536,
  82. projection_dim=768,
  83. num_hidden_layers=20,
  84. num_attention_heads=12,
  85. hidden_act="gelu",
  86. layer_norm_eps=1e-5,
  87. attention_dropout=0.1,
  88. dropout=0.1,
  89. use_rotary_embedding=True,
  90. use_attention_bias=False,
  91. summary_type="mean",
  92. initializer_factor=1.0,
  93. bos_token_id=255,
  94. eos_token_id=0,
  95. **kwargs,
  96. ):
  97. self.vocab_size = vocab_size
  98. self.hidden_size = hidden_size
  99. self.intermediate_size = intermediate_size
  100. self.projection_dim = projection_dim
  101. self.num_hidden_layers = num_hidden_layers
  102. self.num_attention_heads = num_attention_heads
  103. self.layer_norm_eps = layer_norm_eps
  104. self.hidden_act = hidden_act
  105. self.initializer_factor = initializer_factor
  106. self.attention_dropout = attention_dropout
  107. self.dropout = dropout
  108. self.use_rotary_embedding = use_rotary_embedding
  109. self.use_attention_bias = use_attention_bias
  110. self.summary_type = summary_type
  111. self.bos_token_id = bos_token_id
  112. self.eos_token_id = eos_token_id
  113. super().__init__(bos_token_id=bos_token_id, eos_token_id=eos_token_id, **kwargs)
  114. @classmethod
  115. def from_pretrained(
  116. cls, pretrained_model_name_or_path: Union[str, os.PathLike], config_type: str = "text_config", **kwargs
  117. ):
  118. cls._set_token_in_kwargs(kwargs)
  119. config_dict, kwargs = cls.get_config_dict(pretrained_model_name_or_path, **kwargs)
  120. # make sure to have the config_type be either "text_config" or "speech_config"
  121. # this is to make sure that we can load only text or speech configs from the nested ClvpConfig.
  122. if config_type not in cls.base_config_key:
  123. raise ValueError(
  124. f"We can only load either 'text_config' or 'speech_config' but you are trying to load{config_type}"
  125. )
  126. # get the text config dict if we are loading from ClvpConfig
  127. if config_dict.get("model_type") == "clvp":
  128. config_dict = config_dict[config_type]
  129. if "model_type" in config_dict and hasattr(cls, "model_type") and config_dict["model_type"] != cls.model_type:
  130. logger.warning(
  131. f"You are using a model of type {config_dict['model_type']} to instantiate a model of type "
  132. f"{cls.model_type}. This is not supported for all configurations of models and can yield errors."
  133. )
  134. return cls.from_dict(config_dict, **kwargs)
  135. class ClvpDecoderConfig(PretrainedConfig):
  136. r"""
  137. This is the configuration class to store the configuration of a [`ClvpDecoder`]. It is used to instantiate a CLVP
  138. Decoder Model according to the specified arguments, defining the model architecture. Instantiating a configuration
  139. with the defaults will yield a similar configuration to that of the Decoder part of the CLVP
  140. [susnato/clvp_dev](https://huggingface.co/susnato/clvp_dev) architecture.
  141. Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
  142. documentation from [`PretrainedConfig`] for more information.
  143. The architecture is similar to GPT2.
  144. Args:
  145. vocab_size (`int`, *optional*, defaults to 8194):
  146. Vocabulary size of the model.
  147. max_position_embeddings (`int`, *optional*, defaults to 608):
  148. The maximum sequence length of mel tokens that this model might ever be used with. Similar to `n_positions`
  149. in `GPT2Config`.
  150. max_text_tokens (`int`, *optional*, defaults to 404):
  151. The maximum sequence length of text tokens that this model might ever be used with. Similar to
  152. `n_positions` in `GPT2Config`.
  153. hidden_size (`int`, *optional*, defaults to 1024):
  154. Dimensionality of the embeddings and hidden states.
  155. num_hidden_layers (`int`, *optional*, defaults to 30):
  156. Number of hidden layers in the Transformer encoder.
  157. num_attention_heads (`int`, *optional*, defaults to 16):
  158. Number of attention heads for each attention layer in the Transformer encoder.
  159. n_inner (`int`, *optional*):
  160. Dimensionality of the inner feed-forward layers. `None` will set it to 4 times `hidden_size`.
  161. num_mel_attn_blocks (`int`, *optional*, defaults to 6):
  162. Denotes the number of self attention layers in [`ClvpConditioningEncoder`].
  163. activation_function (`str`, *optional*, defaults to `"gelu_new"`):
  164. Activation function, to be selected in the list `["relu", "silu", "gelu", "tanh", "gelu_new"]`.
  165. resid_pdrop (`float`, *optional*, defaults to 0.1):
  166. The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
  167. embd_pdrop (`float`, *optional*, defaults to 0.1):
  168. The dropout ratio for the embeddings.
  169. attention_dropout (`float`, *optional*, defaults to 0.1):
  170. The dropout ratio for the attention.
  171. layer_norm_epsilon (`float`, *optional*, defaults to 1e-05):
  172. The epsilon to use in the layer normalization layers.
  173. initializer_range (`float`, *optional*, defaults to 0.02):
  174. The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
  175. summary_type (`string`, *optional*, defaults to `"cls_index"`):
  176. Argument used when doing sequence summary.
  177. Has to be one of the following options:
  178. - `"last"`: Take the last token hidden state (like XLNet).
  179. - `"first"`: Take the first token hidden state (like BERT).
  180. - `"mean"`: Take the mean of all tokens hidden states.
  181. - `"cls_index"`: Supply a Tensor of classification token position (like GPT/GPT-2).
  182. - `"attn"`: Not implemented now, use multi-head attention.
  183. summary_use_proj (`bool`, *optional*, defaults to `True`):
  184. Whether or not to add a projection after the vector extraction.
  185. summary_activation (`str`, *optional*):
  186. Pass `"tanh"` for a tanh activation to the output, any other value will result in no activation.
  187. summary_proj_to_labels (`bool`, *optional*, defaults to `True`):
  188. Whether the projection outputs should have `config.num_labels` or `config.hidden_size` classes.
  189. summary_first_dropout (`float`, *optional*, defaults to 0.1):
  190. The dropout ratio to be used after the projection and activation.
  191. use_cache (`bool`, *optional*, defaults to `True`):
  192. Whether or not the model should return the last key/values attentions (not used by all models).
  193. bos_token_id (`int`, *optional*, defaults to 8192):
  194. Beginning of sequence token id, used at the start of the generation.
  195. eos_token_id (`int`, *optional*, defaults to 8193):
  196. End of sequence token id, used in the method
  197. [`ClvpModelForConditionalGeneration.fix_speech_decoder_output()`] to correct decoder outputs.
  198. feature_size (`int`, *optional*, defaults to 80):
  199. The feature dimension of the extracted mel features. This value is used in [`ClvpConditioningEncoder`].
  200. use_attention_bias (`bool`, *optional*, defaults to `True`):
  201. Whether to use bias in Query, Key and Value layers during self attention.
  202. initializer_factor (`float`, *optional*, defaults to 1.0):
  203. A factor for initializing all weight matrices (should be kept to 1.0, used internally for initialization
  204. testing).
  205. decoder_fixing_codes (`list`, *optional*, defaults to `[83, 45, 45, 248]`):
  206. These values are used in the method `fix_speech_decoder_output` to fix decoder generated outputs.
  207. Example:
  208. ```python
  209. >>> from transformers import ClvpDecoderConfig, ClvpDecoder
  210. >>> # Initializing a ClvpDecoderConfig with susnato/clvp_dev style configuration
  211. >>> decoder_configuration = ClvpDecoderConfig()
  212. >>> # Initializing a ClvpDecoder (with random weights) from the susnato/clvp_dev style configuration
  213. >>> model = ClvpDecoder(decoder_configuration)
  214. >>> # Accessing the model configuration
  215. >>> configuration = model.config
  216. ```"""
  217. model_type = "clvp_decoder"
  218. base_config_key = "decoder_config"
  219. def __init__(
  220. self,
  221. vocab_size=8194,
  222. max_position_embeddings=608,
  223. max_text_tokens=404,
  224. hidden_size=1024,
  225. num_hidden_layers=30,
  226. num_attention_heads=16,
  227. n_inner=None,
  228. num_mel_attn_blocks=6,
  229. activation_function="gelu_new",
  230. resid_pdrop=0.1,
  231. embd_pdrop=0.1,
  232. attention_dropout=0.1,
  233. layer_norm_epsilon=1e-5,
  234. initializer_range=0.02,
  235. summary_type="cls_index",
  236. summary_use_proj=True,
  237. summary_activation=None,
  238. summary_proj_to_labels=True,
  239. summary_first_dropout=0.1,
  240. use_cache=True,
  241. bos_token_id=8192,
  242. eos_token_id=8193,
  243. feature_size=80,
  244. use_attention_bias=True,
  245. initializer_factor=1.0,
  246. decoder_fixing_codes=[83, 45, 45, 248],
  247. **kwargs,
  248. ):
  249. self.vocab_size = vocab_size
  250. self.max_position_embeddings = max_position_embeddings
  251. self.max_text_tokens = max_text_tokens
  252. self.hidden_size = hidden_size
  253. self.num_hidden_layers = num_hidden_layers
  254. self.num_attention_heads = num_attention_heads
  255. self.n_inner = n_inner
  256. self.num_mel_attn_blocks = num_mel_attn_blocks
  257. self.activation_function = activation_function
  258. self.resid_pdrop = resid_pdrop
  259. self.embd_pdrop = embd_pdrop
  260. self.attention_dropout = attention_dropout
  261. self.layer_norm_epsilon = layer_norm_epsilon
  262. self.initializer_range = initializer_range
  263. self.summary_type = summary_type
  264. self.summary_use_proj = summary_use_proj
  265. self.summary_activation = summary_activation
  266. self.summary_first_dropout = summary_first_dropout
  267. self.summary_proj_to_labels = summary_proj_to_labels
  268. self.use_cache = use_cache
  269. self.feature_size = feature_size
  270. self.use_attention_bias = use_attention_bias
  271. self.initializer_factor = initializer_factor
  272. self.decoder_fixing_codes = decoder_fixing_codes
  273. self.bos_token_id = bos_token_id
  274. self.eos_token_id = eos_token_id
  275. super().__init__(bos_token_id=bos_token_id, eos_token_id=eos_token_id, **kwargs)
  276. class ClvpConfig(PretrainedConfig):
  277. r"""
  278. [`ClvpConfig`] is the configuration class to store the configuration of a [`ClvpModelForConditionalGeneration`]. It
  279. is used to instantiate a CLVP model according to the specified arguments, defining the text model, speech model and
  280. decoder model configs. Instantiating a configuration with the defaults will yield a similar configuration to that
  281. of the CLVP [susnato/clvp_dev](https://huggingface.co/susnato/clvp_dev) architecture.
  282. Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
  283. documentation from [`PretrainedConfig`] for more information.
  284. Args:
  285. text_config (`dict`, *optional*):
  286. Dictionary of configuration options used to initialize the CLVP text encoder.
  287. speech_config (`dict`, *optional*):
  288. Dictionary of configuration options used to initialize CLVP speech encoder.
  289. decoder_config (`dict`, *optional*):
  290. Dictionary of configuration options used to initialize [`ClvpDecoderConfig`].
  291. projection_dim (`int`, *optional*, defaults to 768):
  292. Dimensionality of text and speech projection layers.
  293. logit_scale_init_value (`float`, *optional*, defaults to 2.6592):
  294. The initial value of the *logit_scale* parameter. Default is used as per the original CLVP implementation.
  295. initializer_factor (`float`, *optional*, defaults to 1.0):
  296. A factor for initializing all weight matrices (should be kept to 1.0, used internally for initialization
  297. testing).
  298. kwargs (*optional*):
  299. Dictionary of keyword arguments.
  300. Example:
  301. ```python
  302. >>> from transformers import ClvpConfig, ClvpModelForConditionalGeneration
  303. >>> # Initializing a ClvpConfig with susnato/clvp_dev style configuration
  304. >>> configuration = ClvpConfig()
  305. >>> # Initializing a ClvpModelForConditionalGeneration (with random weights) from the susnato/clvp_dev style configuration
  306. >>> model = ClvpModelForConditionalGeneration(configuration)
  307. >>> # Accessing the model configuration
  308. >>> configuration = model.config
  309. >>> # We can also initialize a CLVPConfig from a CLVPTextConfig, CLVPSpeechConfig and a CLVPAutoRegressiveConfig
  310. >>> from transformers import ClvpEncoderConfig, ClvpDecoderConfig
  311. >>> # Initializing a CLVP text, CLVP speech and CLVP decoder configuration
  312. >>> config_text = ClvpEncoderConfig()
  313. >>> config_speech = ClvpEncoderConfig()
  314. >>> decoder_config = ClvpDecoderConfig()
  315. >>> config = ClvpConfig.from_sub_model_configs(config_text, config_speech, decoder_config)
  316. ```"""
  317. model_type = "clvp"
  318. sub_configs = {
  319. "text_config": ClvpEncoderConfig,
  320. "speech_config": ClvpEncoderConfig,
  321. "decoder_config": ClvpDecoderConfig,
  322. }
  323. def __init__(
  324. self,
  325. text_config=None,
  326. speech_config=None,
  327. decoder_config=None,
  328. projection_dim=768,
  329. logit_scale_init_value=2.6592,
  330. initializer_factor=1.0,
  331. **kwargs,
  332. ):
  333. super().__init__(**kwargs)
  334. if text_config is None:
  335. text_config = {}
  336. logger.info("`text_config` is `None`. Initializing the `ClvpEncoderConfig` with default values.")
  337. if speech_config is None:
  338. speech_config = {}
  339. logger.info("`speech_config` is `None`. initializing the `ClvpEncoderConfig` with default values.")
  340. if decoder_config is None:
  341. decoder_config = {}
  342. logger.info("`decoder_config` is `None`. initializing the `ClvpDecoderConfig` with default values.")
  343. self.text_config = ClvpEncoderConfig(**text_config)
  344. self.speech_config = ClvpEncoderConfig(**speech_config)
  345. self.decoder_config = ClvpDecoderConfig(**decoder_config)
  346. self.projection_dim = projection_dim
  347. self.logit_scale_init_value = logit_scale_init_value
  348. self.initializer_factor = initializer_factor
  349. @classmethod
  350. def from_sub_model_configs(
  351. cls,
  352. text_config: ClvpEncoderConfig,
  353. speech_config: ClvpEncoderConfig,
  354. decoder_config: ClvpDecoderConfig,
  355. **kwargs,
  356. ):
  357. r"""
  358. Instantiate a [`ClvpConfig`] (or a derived class) from CLVP text model configuration, CLVP speech model
  359. configuration and CLVP decoder model configuration.
  360. Args:
  361. text_config (`ClvpEncoderConfig`):
  362. Text model configuration of type [`ClvpEncoderConfig`].
  363. speech_config (`ClvpEncoderConfig`):
  364. Speech model configuration of type [`ClvpEncoderConfig`].
  365. decoder_config (`ClvpDecoderConfig`):
  366. Decoder model configuration of type [`ClvpDecoderConfig`].
  367. Returns:
  368. [`ClvpConfig`]: An instance of a configuration object
  369. """
  370. return cls(
  371. text_config=text_config.to_dict(),
  372. speech_config=speech_config.to_dict(),
  373. decoder_config=decoder_config.to_dict(),
  374. **kwargs,
  375. )
  376. __all__ = ["ClvpConfig", "ClvpDecoderConfig", "ClvpEncoderConfig"]