configuration_bark.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303
  1. # coding=utf-8
  2. # Copyright 2023 The Suno AI Authors and 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. """BARK model configuration"""
  16. from typing import Optional
  17. from ...configuration_utils import PretrainedConfig
  18. from ...utils import add_start_docstrings, logging
  19. from ..auto import CONFIG_MAPPING, AutoConfig
  20. logger = logging.get_logger(__name__)
  21. BARK_SUBMODELCONFIG_START_DOCSTRING = """
  22. This is the configuration class to store the configuration of a [`{model}`]. It is used to instantiate the model
  23. according to the specified arguments, defining the model architecture. Instantiating a configuration with the
  24. defaults will yield a similar configuration to that of the Bark [suno/bark](https://huggingface.co/suno/bark)
  25. architecture.
  26. Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
  27. documentation from [`PretrainedConfig`] for more information.
  28. Args:
  29. block_size (`int`, *optional*, defaults to 1024):
  30. The maximum sequence length that this model might ever be used with. Typically set this to something large
  31. just in case (e.g., 512 or 1024 or 2048).
  32. input_vocab_size (`int`, *optional*, defaults to 10_048):
  33. Vocabulary size of a Bark sub-model. Defines the number of different tokens that can be represented by the
  34. `inputs_ids` passed when calling [`{model}`]. Defaults to 10_048 but should be carefully thought with
  35. regards to the chosen sub-model.
  36. output_vocab_size (`int`, *optional*, defaults to 10_048):
  37. Output vocabulary size of a Bark sub-model. Defines the number of different tokens that can be represented
  38. by the: `output_ids` when passing forward a [`{model}`]. Defaults to 10_048 but should be carefully thought
  39. with regards to the chosen sub-model.
  40. num_layers (`int`, *optional*, defaults to 12):
  41. Number of hidden layers in the given sub-model.
  42. num_heads (`int`, *optional*, defaults to 12):
  43. Number of attention heads for each attention layer in the Transformer architecture.
  44. hidden_size (`int`, *optional*, defaults to 768):
  45. Dimensionality of the "intermediate" (often named feed-forward) layer in the architecture.
  46. dropout (`float`, *optional*, defaults to 0.0):
  47. The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
  48. bias (`bool`, *optional*, defaults to `True`):
  49. Whether or not to use bias in the linear layers and layer norm layers.
  50. initializer_range (`float`, *optional*, defaults to 0.02):
  51. The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
  52. use_cache (`bool`, *optional*, defaults to `True`):
  53. Whether or not the model should return the last key/values attentions (not used by all models).
  54. """
  55. class BarkSubModelConfig(PretrainedConfig):
  56. keys_to_ignore_at_inference = ["past_key_values"]
  57. attribute_map = {
  58. "num_attention_heads": "num_heads",
  59. "num_hidden_layers": "num_layers",
  60. "vocab_size": "input_vocab_size",
  61. "window_size": "block_size",
  62. }
  63. def __init__(
  64. self,
  65. block_size=1024,
  66. input_vocab_size=10_048,
  67. output_vocab_size=10_048,
  68. num_layers=12,
  69. num_heads=12,
  70. hidden_size=768,
  71. dropout=0.0,
  72. bias=True, # True: bias in Linears and LayerNorms, like GPT-2. False: a bit better and faster
  73. initializer_range=0.02,
  74. use_cache=True,
  75. **kwargs,
  76. ):
  77. self.block_size = block_size
  78. self.input_vocab_size = input_vocab_size
  79. self.output_vocab_size = output_vocab_size
  80. self.num_layers = num_layers
  81. self.num_heads = num_heads
  82. self.hidden_size = hidden_size
  83. self.dropout = dropout
  84. self.bias = bias
  85. self.use_cache = use_cache
  86. self.initializer_range = initializer_range
  87. super().__init__(**kwargs)
  88. @add_start_docstrings(
  89. BARK_SUBMODELCONFIG_START_DOCSTRING.format(config="BarkSemanticConfig", model="BarkSemanticModel"),
  90. """
  91. Example:
  92. ```python
  93. >>> from transformers import BarkSemanticConfig, BarkSemanticModel
  94. >>> # Initializing a Bark sub-module style configuration
  95. >>> configuration = BarkSemanticConfig()
  96. >>> # Initializing a model (with random weights) from the suno/bark style configuration
  97. >>> model = BarkSemanticModel(configuration)
  98. >>> # Accessing the model configuration
  99. >>> configuration = model.config
  100. ```""",
  101. )
  102. class BarkSemanticConfig(BarkSubModelConfig):
  103. model_type = "semantic"
  104. base_config_key = "semantic_config"
  105. @add_start_docstrings(
  106. BARK_SUBMODELCONFIG_START_DOCSTRING.format(config="BarkCoarseConfig", model="BarkCoarseModel"),
  107. """
  108. Example:
  109. ```python
  110. >>> from transformers import BarkCoarseConfig, BarkCoarseModel
  111. >>> # Initializing a Bark sub-module style configuration
  112. >>> configuration = BarkCoarseConfig()
  113. >>> # Initializing a model (with random weights) from the suno/bark style configuration
  114. >>> model = BarkCoarseModel(configuration)
  115. >>> # Accessing the model configuration
  116. >>> configuration = model.config
  117. ```""",
  118. )
  119. class BarkCoarseConfig(BarkSubModelConfig):
  120. model_type = "coarse_acoustics"
  121. base_config_key = "coarse_acoustics_config"
  122. @add_start_docstrings(
  123. BARK_SUBMODELCONFIG_START_DOCSTRING.format(config="BarkFineConfig", model="BarkFineModel"),
  124. """
  125. n_codes_total (`int`, *optional*, defaults to 8):
  126. The total number of audio codebooks predicted. Used in the fine acoustics sub-model.
  127. n_codes_given (`int`, *optional*, defaults to 1):
  128. The number of audio codebooks predicted in the coarse acoustics sub-model. Used in the acoustics
  129. sub-models.
  130. Example:
  131. ```python
  132. >>> from transformers import BarkFineConfig, BarkFineModel
  133. >>> # Initializing a Bark sub-module style configuration
  134. >>> configuration = BarkFineConfig()
  135. >>> # Initializing a model (with random weights) from the suno/bark style configuration
  136. >>> model = BarkFineModel(configuration)
  137. >>> # Accessing the model configuration
  138. >>> configuration = model.config
  139. ```""",
  140. )
  141. class BarkFineConfig(BarkSubModelConfig):
  142. model_type = "fine_acoustics"
  143. base_config_key = "fine_acoustics_config"
  144. def __init__(self, tie_word_embeddings=True, n_codes_total=8, n_codes_given=1, **kwargs):
  145. self.n_codes_total = n_codes_total
  146. self.n_codes_given = n_codes_given
  147. super().__init__(tie_word_embeddings=tie_word_embeddings, **kwargs)
  148. class BarkConfig(PretrainedConfig):
  149. """
  150. This is the configuration class to store the configuration of a [`BarkModel`]. It is used to instantiate a Bark
  151. model according to the specified sub-models configurations, defining the model architecture.
  152. Instantiating a configuration with the defaults will yield a similar configuration to that of the Bark
  153. [suno/bark](https://huggingface.co/suno/bark) architecture.
  154. Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
  155. documentation from [`PretrainedConfig`] for more information.
  156. Args:
  157. semantic_config ([`BarkSemanticConfig`], *optional*):
  158. Configuration of the underlying semantic sub-model.
  159. coarse_acoustics_config ([`BarkCoarseConfig`], *optional*):
  160. Configuration of the underlying coarse acoustics sub-model.
  161. fine_acoustics_config ([`BarkFineConfig`], *optional*):
  162. Configuration of the underlying fine acoustics sub-model.
  163. codec_config ([`AutoConfig`], *optional*):
  164. Configuration of the underlying codec sub-model.
  165. Example:
  166. ```python
  167. >>> from transformers import (
  168. ... BarkSemanticConfig,
  169. ... BarkCoarseConfig,
  170. ... BarkFineConfig,
  171. ... BarkModel,
  172. ... BarkConfig,
  173. ... AutoConfig,
  174. ... )
  175. >>> # Initializing Bark sub-modules configurations.
  176. >>> semantic_config = BarkSemanticConfig()
  177. >>> coarse_acoustics_config = BarkCoarseConfig()
  178. >>> fine_acoustics_config = BarkFineConfig()
  179. >>> codec_config = AutoConfig.from_pretrained("facebook/encodec_24khz")
  180. >>> # Initializing a Bark module style configuration
  181. >>> configuration = BarkConfig.from_sub_model_configs(
  182. ... semantic_config, coarse_acoustics_config, fine_acoustics_config, codec_config
  183. ... )
  184. >>> # Initializing a model (with random weights)
  185. >>> model = BarkModel(configuration)
  186. >>> # Accessing the model configuration
  187. >>> configuration = model.config
  188. ```
  189. """
  190. model_type = "bark"
  191. sub_configs = {
  192. "semantic_config": BarkSemanticConfig,
  193. "coarse_acoustics_config": BarkCoarseConfig,
  194. "fine_acoustics_config": BarkFineConfig,
  195. "codec_config": AutoConfig,
  196. }
  197. def __init__(
  198. self,
  199. semantic_config: Optional[dict] = None,
  200. coarse_acoustics_config: Optional[dict] = None,
  201. fine_acoustics_config: Optional[dict] = None,
  202. codec_config: Optional[dict] = None,
  203. initializer_range=0.02,
  204. **kwargs,
  205. ):
  206. if semantic_config is None:
  207. semantic_config = {}
  208. logger.info("semantic_config is None. initializing the semantic model with default values.")
  209. if coarse_acoustics_config is None:
  210. coarse_acoustics_config = {}
  211. logger.info("coarse_acoustics_config is None. initializing the coarse model with default values.")
  212. if fine_acoustics_config is None:
  213. fine_acoustics_config = {}
  214. logger.info("fine_acoustics_config is None. initializing the fine model with default values.")
  215. if codec_config is None:
  216. codec_config = {}
  217. logger.info("codec_config is None. initializing the codec model with default values.")
  218. self.semantic_config = BarkSemanticConfig(**semantic_config)
  219. self.coarse_acoustics_config = BarkCoarseConfig(**coarse_acoustics_config)
  220. self.fine_acoustics_config = BarkFineConfig(**fine_acoustics_config)
  221. codec_model_type = codec_config.get("model_type", "encodec")
  222. self.codec_config = CONFIG_MAPPING[codec_model_type](**codec_config)
  223. self.initializer_range = initializer_range
  224. super().__init__(**kwargs)
  225. @classmethod
  226. def from_sub_model_configs(
  227. cls,
  228. semantic_config: BarkSemanticConfig,
  229. coarse_acoustics_config: BarkCoarseConfig,
  230. fine_acoustics_config: BarkFineConfig,
  231. codec_config: PretrainedConfig,
  232. **kwargs,
  233. ):
  234. r"""
  235. Instantiate a [`BarkConfig`] (or a derived class) from bark sub-models configuration.
  236. Returns:
  237. [`BarkConfig`]: An instance of a configuration object
  238. """
  239. return cls(
  240. semantic_config=semantic_config.to_dict(),
  241. coarse_acoustics_config=coarse_acoustics_config.to_dict(),
  242. fine_acoustics_config=fine_acoustics_config.to_dict(),
  243. codec_config=codec_config.to_dict(),
  244. **kwargs,
  245. )
  246. __all__ = ["BarkCoarseConfig", "BarkConfig", "BarkFineConfig", "BarkSemanticConfig"]