configuration_speecht5.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422
  1. # coding=utf-8
  2. # Copyright 2023 The Fairseq Authors, Microsoft Research, 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. """SpeechT5 model configuration"""
  16. import functools
  17. import operator
  18. from ...configuration_utils import PretrainedConfig
  19. from ...utils import logging
  20. logger = logging.get_logger(__name__)
  21. class SpeechT5Config(PretrainedConfig):
  22. r"""
  23. This is the configuration class to store the configuration of a [`SpeechT5Model`]. It is used to instantiate a
  24. SpeechT5 model according to the specified arguments, defining the model architecture. Instantiating a configuration
  25. with the defaults will yield a similar configuration to that of the SpeechT5
  26. [microsoft/speecht5_asr](https://huggingface.co/microsoft/speecht5_asr) 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 81):
  31. Vocabulary size of the SpeechT5 model. Defines the number of different tokens that can be represented by
  32. the `inputs_ids` passed to the forward method of [`SpeechT5Model`].
  33. hidden_size (`int`, *optional*, defaults to 768):
  34. Dimensionality of the encoder layers and the pooler layer.
  35. encoder_layers (`int`, *optional*, defaults to 12):
  36. Number of hidden layers in the Transformer encoder.
  37. encoder_attention_heads (`int`, *optional*, defaults to 12):
  38. Number of attention heads for each attention layer in the Transformer encoder.
  39. encoder_ffn_dim (`int`, *optional*, defaults to 3072):
  40. Dimensionality of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder.
  41. encoder_layerdrop (`float`, *optional*, defaults to 0.1):
  42. The LayerDrop probability for the encoder. See the [LayerDrop paper](see https://huggingface.co/papers/1909.11556)
  43. for more details.
  44. decoder_layers (`int`, *optional*, defaults to 6):
  45. Number of hidden layers in the Transformer decoder.
  46. decoder_attention_heads (`int`, *optional*, defaults to 12):
  47. Number of attention heads for each attention layer in the Transformer decoder.
  48. decoder_ffn_dim (`int`, *optional*, defaults to 3072):
  49. Dimensionality of the "intermediate" (often named feed-forward) layer in the Transformer decoder.
  50. decoder_layerdrop (`float`, *optional*, defaults to 0.1):
  51. The LayerDrop probability for the decoder. See the [LayerDrop paper](see https://huggingface.co/papers/1909.11556)
  52. for more details.
  53. hidden_act (`str` or `function`, *optional*, defaults to `"gelu"`):
  54. The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
  55. `"relu"`, `"selu"` and `"gelu_new"` are supported.
  56. positional_dropout (`float`, *optional*, defaults to 0.1):
  57. The dropout probability for the text position encoding layers.
  58. hidden_dropout (`float`, *optional*, defaults to 0.1):
  59. The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
  60. attention_dropout (`float`, *optional*, defaults to 0.1):
  61. The dropout ratio for the attention probabilities.
  62. activation_dropout (`float`, *optional*, defaults to 0.1):
  63. The dropout ratio for activations inside the fully connected layer.
  64. initializer_range (`float`, *optional*, defaults to 0.02):
  65. The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
  66. layer_norm_eps (`float`, *optional*, defaults to 1e-5):
  67. The epsilon used by the layer normalization layers.
  68. scale_embedding (`bool`, *optional*, defaults to `False`):
  69. Scale embeddings by diving by sqrt(d_model).
  70. feat_extract_norm (`str`, *optional*, defaults to `"group"`):
  71. The norm to be applied to 1D convolutional layers in the speech encoder pre-net. One of `"group"` for group
  72. normalization of only the first 1D convolutional layer or `"layer"` for layer normalization of all 1D
  73. convolutional layers.
  74. feat_proj_dropout (`float`, *optional*, defaults to 0.0):
  75. The dropout probability for output of the speech encoder pre-net.
  76. feat_extract_activation (`str, `optional`, defaults to `"gelu"`):
  77. The non-linear activation function (function or string) in the 1D convolutional layers of the feature
  78. extractor. If string, `"gelu"`, `"relu"`, `"selu"` and `"gelu_new"` are supported.
  79. conv_dim (`tuple[int]` or `list[int]`, *optional*, defaults to `(512, 512, 512, 512, 512, 512, 512)`):
  80. A tuple of integers defining the number of input and output channels of each 1D convolutional layer in the
  81. speech encoder pre-net. The length of *conv_dim* defines the number of 1D convolutional layers.
  82. conv_stride (`tuple[int]` or `list[int]`, *optional*, defaults to `(5, 2, 2, 2, 2, 2, 2)`):
  83. A tuple of integers defining the stride of each 1D convolutional layer in the speech encoder pre-net. The
  84. length of *conv_stride* defines the number of convolutional layers and has to match the length of
  85. *conv_dim*.
  86. conv_kernel (`tuple[int]` or `list[int]`, *optional*, defaults to `(10, 3, 3, 3, 3, 3, 3)`):
  87. A tuple of integers defining the kernel size of each 1D convolutional layer in the speech encoder pre-net.
  88. The length of *conv_kernel* defines the number of convolutional layers and has to match the length of
  89. *conv_dim*.
  90. conv_bias (`bool`, *optional*, defaults to `False`):
  91. Whether the 1D convolutional layers have a bias.
  92. num_conv_pos_embeddings (`int`, *optional*, defaults to 128):
  93. Number of convolutional positional embeddings. Defines the kernel size of 1D convolutional positional
  94. embeddings layer.
  95. num_conv_pos_embedding_groups (`int`, *optional*, defaults to 16):
  96. Number of groups of 1D convolutional positional embeddings layer.
  97. apply_spec_augment (`bool`, *optional*, defaults to `True`):
  98. Whether to apply *SpecAugment* data augmentation to the outputs of the speech encoder pre-net. For
  99. reference see [SpecAugment: A Simple Data Augmentation Method for Automatic Speech
  100. Recognition](https://huggingface.co/papers/1904.08779).
  101. mask_time_prob (`float`, *optional*, defaults to 0.05):
  102. Percentage (between 0 and 1) of all feature vectors along the time axis which will be masked. The masking
  103. procedure generates ''mask_time_prob*len(time_axis)/mask_time_length'' independent masks over the axis. If
  104. reasoning from the probability of each feature vector to be chosen as the start of the vector span to be
  105. masked, *mask_time_prob* should be `prob_vector_start*mask_time_length`. Note that overlap may decrease the
  106. actual percentage of masked vectors. This is only relevant if `apply_spec_augment is True`.
  107. mask_time_length (`int`, *optional*, defaults to 10):
  108. Length of vector span along the time axis.
  109. mask_time_min_masks (`int`, *optional*, defaults to 2),:
  110. The minimum number of masks of length `mask_feature_length` generated along the time axis, each time step,
  111. irrespectively of `mask_feature_prob`. Only relevant if ''mask_time_prob*len(time_axis)/mask_time_length <
  112. mask_time_min_masks''
  113. mask_feature_prob (`float`, *optional*, defaults to 0.0):
  114. Percentage (between 0 and 1) of all feature vectors along the feature axis which will be masked. The
  115. masking procedure generates ''mask_feature_prob*len(feature_axis)/mask_time_length'' independent masks over
  116. the axis. If reasoning from the probability of each feature vector to be chosen as the start of the vector
  117. span to be masked, *mask_feature_prob* should be `prob_vector_start*mask_feature_length`. Note that overlap
  118. may decrease the actual percentage of masked vectors. This is only relevant if `apply_spec_augment is
  119. True`.
  120. mask_feature_length (`int`, *optional*, defaults to 10):
  121. Length of vector span along the feature axis.
  122. mask_feature_min_masks (`int`, *optional*, defaults to 0),:
  123. The minimum number of masks of length `mask_feature_length` generated along the feature axis, each time
  124. step, irrespectively of `mask_feature_prob`. Only relevant if
  125. ''mask_feature_prob*len(feature_axis)/mask_feature_length < mask_feature_min_masks''
  126. num_mel_bins (`int`, *optional*, defaults to 80):
  127. Number of mel features used per input features. Used by the speech decoder pre-net. Should correspond to
  128. the value used in the [`SpeechT5Processor`] class.
  129. speech_decoder_prenet_layers (`int`, *optional*, defaults to 2):
  130. Number of layers in the speech decoder pre-net.
  131. speech_decoder_prenet_units (`int`, *optional*, defaults to 256):
  132. Dimensionality of the layers in the speech decoder pre-net.
  133. speech_decoder_prenet_dropout (`float`, *optional*, defaults to 0.5):
  134. The dropout probability for the speech decoder pre-net layers.
  135. speaker_embedding_dim (`int`, *optional*, defaults to 512):
  136. Dimensionality of the *XVector* embedding vectors.
  137. speech_decoder_postnet_layers (`int`, *optional*, defaults to 5):
  138. Number of layers in the speech decoder post-net.
  139. speech_decoder_postnet_units (`int`, *optional*, defaults to 256):
  140. Dimensionality of the layers in the speech decoder post-net.
  141. speech_decoder_postnet_kernel (`int`, *optional*, defaults to 5):
  142. Number of convolutional filter channels in the speech decoder post-net.
  143. speech_decoder_postnet_dropout (`float`, *optional*, defaults to 0.5):
  144. The dropout probability for the speech decoder post-net layers.
  145. reduction_factor (`int`, *optional*, defaults to 2):
  146. Spectrogram length reduction factor for the speech decoder inputs.
  147. max_speech_positions (`int`, *optional*, defaults to 4000):
  148. The maximum sequence length of speech features that this model might ever be used with.
  149. max_text_positions (`int`, *optional*, defaults to 450):
  150. The maximum sequence length of text features that this model might ever be used with.
  151. encoder_max_relative_position (`int`, *optional*, defaults to 160):
  152. Maximum distance for relative position embedding in the encoder.
  153. use_guided_attention_loss (`bool`, *optional*, defaults to `True`):
  154. Whether to apply guided attention loss while training the TTS model.
  155. guided_attention_loss_num_heads (`int`, *optional*, defaults to 2):
  156. Number of attention heads the guided attention loss will be applied to. Use -1 to apply this loss to all
  157. attention heads.
  158. guided_attention_loss_sigma (`float`, *optional*, defaults to 0.4):
  159. Standard deviation for guided attention loss.
  160. guided_attention_loss_scale (`float`, *optional*, defaults to 10.0):
  161. Scaling coefficient for guided attention loss (also known as lambda).
  162. use_cache (`bool`, *optional*, defaults to `True`):
  163. Whether or not the model should return the last key/values attentions (not used by all models).
  164. Example:
  165. ```python
  166. >>> from transformers import SpeechT5Model, SpeechT5Config
  167. >>> # Initializing a "microsoft/speecht5_asr" style configuration
  168. >>> configuration = SpeechT5Config()
  169. >>> # Initializing a model (with random weights) from the "microsoft/speecht5_asr" style configuration
  170. >>> model = SpeechT5Model(configuration)
  171. >>> # Accessing the model configuration
  172. >>> configuration = model.config
  173. ```"""
  174. model_type = "speecht5"
  175. attribute_map = {"num_attention_heads": "encoder_attention_heads", "num_hidden_layers": "encoder_layers"}
  176. def __init__(
  177. self,
  178. vocab_size=81,
  179. hidden_size=768,
  180. encoder_layers=12,
  181. encoder_attention_heads=12,
  182. encoder_ffn_dim=3072,
  183. encoder_layerdrop=0.1,
  184. decoder_layers=6,
  185. decoder_ffn_dim=3072,
  186. decoder_attention_heads=12,
  187. decoder_layerdrop=0.1,
  188. hidden_act="gelu",
  189. positional_dropout=0.1,
  190. hidden_dropout=0.1,
  191. attention_dropout=0.1,
  192. activation_dropout=0.1,
  193. initializer_range=0.02,
  194. layer_norm_eps=1e-5,
  195. scale_embedding=False,
  196. feat_extract_norm="group",
  197. feat_proj_dropout=0.0,
  198. feat_extract_activation="gelu",
  199. conv_dim=(512, 512, 512, 512, 512, 512, 512),
  200. conv_stride=(5, 2, 2, 2, 2, 2, 2),
  201. conv_kernel=(10, 3, 3, 3, 3, 2, 2),
  202. conv_bias=False,
  203. num_conv_pos_embeddings=128,
  204. num_conv_pos_embedding_groups=16,
  205. apply_spec_augment=True,
  206. mask_time_prob=0.05,
  207. mask_time_length=10,
  208. mask_time_min_masks=2,
  209. mask_feature_prob=0.0,
  210. mask_feature_length=10,
  211. mask_feature_min_masks=0,
  212. pad_token_id=1,
  213. bos_token_id=0,
  214. eos_token_id=2,
  215. decoder_start_token_id=2,
  216. num_mel_bins=80,
  217. speech_decoder_prenet_layers=2,
  218. speech_decoder_prenet_units=256,
  219. speech_decoder_prenet_dropout=0.5,
  220. speaker_embedding_dim=512,
  221. speech_decoder_postnet_layers=5,
  222. speech_decoder_postnet_units=256,
  223. speech_decoder_postnet_kernel=5,
  224. speech_decoder_postnet_dropout=0.5,
  225. reduction_factor=2,
  226. max_speech_positions=4000,
  227. max_text_positions=450,
  228. encoder_max_relative_position=160,
  229. use_guided_attention_loss=True,
  230. guided_attention_loss_num_heads=2,
  231. guided_attention_loss_sigma=0.4,
  232. guided_attention_loss_scale=10.0,
  233. use_cache=True,
  234. is_encoder_decoder=True,
  235. **kwargs,
  236. ):
  237. self.vocab_size = vocab_size
  238. self.hidden_size = hidden_size
  239. self.encoder_layers = encoder_layers
  240. self.encoder_ffn_dim = encoder_ffn_dim
  241. self.encoder_attention_heads = encoder_attention_heads
  242. self.encoder_layerdrop = encoder_layerdrop
  243. self.decoder_layers = decoder_layers
  244. self.decoder_ffn_dim = decoder_ffn_dim
  245. self.decoder_attention_heads = decoder_attention_heads
  246. self.decoder_layerdrop = decoder_layerdrop
  247. self.hidden_act = hidden_act
  248. self.positional_dropout = positional_dropout
  249. self.hidden_dropout = hidden_dropout
  250. self.attention_dropout = attention_dropout
  251. self.activation_dropout = activation_dropout
  252. self.initializer_range = initializer_range
  253. self.layer_norm_eps = layer_norm_eps
  254. self.scale_embedding = scale_embedding
  255. self.feat_extract_norm = feat_extract_norm
  256. self.feat_proj_dropout = feat_proj_dropout
  257. self.feat_extract_activation = feat_extract_activation
  258. self.conv_dim = list(conv_dim)
  259. self.conv_stride = list(conv_stride)
  260. self.conv_kernel = list(conv_kernel)
  261. self.conv_bias = conv_bias
  262. self.num_conv_pos_embeddings = num_conv_pos_embeddings
  263. self.num_conv_pos_embedding_groups = num_conv_pos_embedding_groups
  264. self.num_feat_extract_layers = len(self.conv_dim)
  265. if (
  266. (len(self.conv_stride) != self.num_feat_extract_layers)
  267. or (len(self.conv_kernel) != self.num_feat_extract_layers)
  268. or (len(self.conv_dim) != self.num_feat_extract_layers)
  269. ):
  270. raise ValueError(
  271. "Configuration for convolutional layers is incorrect. It is required that `len(config.conv_dim)` =="
  272. " `len(config.conv_stride)` == `len(config.conv_kernel)`, but is `len(config.conv_dim) ="
  273. f" {len(self.conv_dim)}`, `len(config.conv_stride) = {len(self.conv_stride)}`,"
  274. f" `len(config.conv_kernel) = {len(self.conv_kernel)}`."
  275. )
  276. # fine-tuning config parameters for SpecAugment: https://huggingface.co/papers/1904.08779
  277. self.apply_spec_augment = apply_spec_augment
  278. self.mask_time_prob = mask_time_prob
  279. self.mask_time_length = mask_time_length
  280. self.mask_time_min_masks = mask_time_min_masks
  281. self.mask_feature_prob = mask_feature_prob
  282. self.mask_feature_length = mask_feature_length
  283. self.mask_feature_min_masks = mask_feature_min_masks
  284. self.num_mel_bins = num_mel_bins
  285. self.speech_decoder_prenet_layers = speech_decoder_prenet_layers
  286. self.speech_decoder_prenet_units = speech_decoder_prenet_units
  287. self.speech_decoder_prenet_dropout = speech_decoder_prenet_dropout
  288. self.speaker_embedding_dim = speaker_embedding_dim
  289. self.speech_decoder_postnet_layers = speech_decoder_postnet_layers
  290. self.speech_decoder_postnet_units = speech_decoder_postnet_units
  291. self.speech_decoder_postnet_kernel = speech_decoder_postnet_kernel
  292. self.speech_decoder_postnet_dropout = speech_decoder_postnet_dropout
  293. self.reduction_factor = reduction_factor
  294. self.max_speech_positions = max_speech_positions
  295. self.max_text_positions = max_text_positions
  296. self.encoder_max_relative_position = encoder_max_relative_position
  297. self.use_guided_attention_loss = use_guided_attention_loss
  298. self.guided_attention_loss_num_heads = guided_attention_loss_num_heads
  299. self.guided_attention_loss_sigma = guided_attention_loss_sigma
  300. self.guided_attention_loss_scale = guided_attention_loss_scale
  301. self.use_cache = use_cache
  302. self.is_encoder_decoder = is_encoder_decoder
  303. super().__init__(
  304. pad_token_id=pad_token_id,
  305. bos_token_id=bos_token_id,
  306. eos_token_id=eos_token_id,
  307. is_encoder_decoder=is_encoder_decoder,
  308. decoder_start_token_id=decoder_start_token_id,
  309. **kwargs,
  310. )
  311. def inputs_to_logits_ratio(self):
  312. return functools.reduce(operator.mul, self.conv_stride, 1)
  313. class SpeechT5HifiGanConfig(PretrainedConfig):
  314. r"""
  315. This is the configuration class to store the configuration of a [`SpeechT5HifiGanModel`]. It is used to instantiate
  316. a SpeechT5 HiFi-GAN vocoder model according to the specified arguments, defining the model architecture.
  317. Instantiating a configuration with the defaults will yield a similar configuration to that of the SpeechT5
  318. [microsoft/speecht5_hifigan](https://huggingface.co/microsoft/speecht5_hifigan) architecture.
  319. Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
  320. documentation from [`PretrainedConfig`] for more information.
  321. Args:
  322. model_in_dim (`int`, *optional*, defaults to 80):
  323. The number of frequency bins in the input log-mel spectrogram.
  324. sampling_rate (`int`, *optional*, defaults to 16000):
  325. The sampling rate at which the output audio will be generated, expressed in hertz (Hz).
  326. upsample_initial_channel (`int`, *optional*, defaults to 512):
  327. The number of input channels into the upsampling network.
  328. upsample_rates (`tuple[int]` or `list[int]`, *optional*, defaults to `[4, 4, 4, 4]`):
  329. A tuple of integers defining the stride of each 1D convolutional layer in the upsampling network. The
  330. length of *upsample_rates* defines the number of convolutional layers and has to match the length of
  331. *upsample_kernel_sizes*.
  332. upsample_kernel_sizes (`tuple[int]` or `list[int]`, *optional*, defaults to `[8, 8, 8, 8]`):
  333. A tuple of integers defining the kernel size of each 1D convolutional layer in the upsampling network. The
  334. length of *upsample_kernel_sizes* defines the number of convolutional layers and has to match the length of
  335. *upsample_rates*.
  336. resblock_kernel_sizes (`tuple[int]` or `list[int]`, *optional*, defaults to `[3, 7, 11]`):
  337. A tuple of integers defining the kernel sizes of the 1D convolutional layers in the multi-receptive field
  338. fusion (MRF) module.
  339. resblock_dilation_sizes (`tuple[tuple[int]]` or `list[list[int]]`, *optional*, defaults to `[[1, 3, 5], [1, 3, 5], [1, 3, 5]]`):
  340. A nested tuple of integers defining the dilation rates of the dilated 1D convolutional layers in the
  341. multi-receptive field fusion (MRF) module.
  342. initializer_range (`float`, *optional*, defaults to 0.01):
  343. The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
  344. leaky_relu_slope (`float`, *optional*, defaults to 0.1):
  345. The angle of the negative slope used by the leaky ReLU activation.
  346. normalize_before (`bool`, *optional*, defaults to `True`):
  347. Whether or not to normalize the spectrogram before vocoding using the vocoder's learned mean and variance.
  348. Example:
  349. ```python
  350. >>> from transformers import SpeechT5HifiGan, SpeechT5HifiGanConfig
  351. >>> # Initializing a "microsoft/speecht5_hifigan" style configuration
  352. >>> configuration = SpeechT5HifiGanConfig()
  353. >>> # Initializing a model (with random weights) from the "microsoft/speecht5_hifigan" style configuration
  354. >>> model = SpeechT5HifiGan(configuration)
  355. >>> # Accessing the model configuration
  356. >>> configuration = model.config
  357. ```"""
  358. model_type = "hifigan"
  359. def __init__(
  360. self,
  361. model_in_dim=80,
  362. sampling_rate=16000,
  363. upsample_initial_channel=512,
  364. upsample_rates=[4, 4, 4, 4],
  365. upsample_kernel_sizes=[8, 8, 8, 8],
  366. resblock_kernel_sizes=[3, 7, 11],
  367. resblock_dilation_sizes=[[1, 3, 5], [1, 3, 5], [1, 3, 5]],
  368. initializer_range=0.01,
  369. leaky_relu_slope=0.1,
  370. normalize_before=True,
  371. **kwargs,
  372. ):
  373. self.model_in_dim = model_in_dim
  374. self.sampling_rate = sampling_rate
  375. self.upsample_initial_channel = upsample_initial_channel
  376. self.upsample_rates = upsample_rates
  377. self.upsample_kernel_sizes = upsample_kernel_sizes
  378. self.resblock_kernel_sizes = resblock_kernel_sizes
  379. self.resblock_dilation_sizes = resblock_dilation_sizes
  380. self.initializer_range = initializer_range
  381. self.leaky_relu_slope = leaky_relu_slope
  382. self.normalize_before = normalize_before
  383. super().__init__(**kwargs)
  384. __all__ = ["SpeechT5Config", "SpeechT5HifiGanConfig"]