configuration_speecht5.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279
  1. # Copyright 2023 The Fairseq Authors, Microsoft Research, and 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. """SpeechT5 model configuration"""
  15. import functools
  16. import operator
  17. from huggingface_hub.dataclasses import strict
  18. from ...configuration_utils import PreTrainedConfig
  19. from ...utils import auto_docstring
  20. @auto_docstring(checkpoint="microsoft/speecht5_asr")
  21. @strict
  22. class SpeechT5Config(PreTrainedConfig):
  23. r"""
  24. positional_dropout (`float`, *optional*, defaults to 0.1):
  25. The dropout probability for the text position encoding layers.
  26. feat_extract_norm (`str`, *optional*, defaults to `"group"`):
  27. The norm to be applied to 1D convolutional layers in the speech encoder pre-net. One of `"group"` for group
  28. normalization of only the first 1D convolutional layer or `"layer"` for layer normalization of all 1D
  29. convolutional layers.
  30. feat_proj_dropout (`float`, *optional*, defaults to 0.0):
  31. The dropout probability for output of the speech encoder pre-net.
  32. feat_extract_activation (`str, `optional`, defaults to `"gelu"`):
  33. The non-linear activation function (function or string) in the 1D convolutional layers of the feature
  34. extractor. If string, `"gelu"`, `"relu"`, `"selu"` and `"gelu_new"` are supported.
  35. conv_dim (`tuple[int]` or `list[int]`, *optional*, defaults to `(512, 512, 512, 512, 512, 512, 512)`):
  36. A tuple of integers defining the number of input and output channels of each 1D convolutional layer in the
  37. speech encoder pre-net. The length of *conv_dim* defines the number of 1D convolutional layers.
  38. conv_stride (`tuple[int]` or `list[int]`, *optional*, defaults to `(5, 2, 2, 2, 2, 2, 2)`):
  39. A tuple of integers defining the stride of each 1D convolutional layer in the speech encoder pre-net. The
  40. length of *conv_stride* defines the number of convolutional layers and has to match the length of
  41. *conv_dim*.
  42. conv_kernel (`tuple[int]` or `list[int]`, *optional*, defaults to `(10, 3, 3, 3, 3, 3, 3)`):
  43. A tuple of integers defining the kernel size of each 1D convolutional layer in the speech encoder pre-net.
  44. The length of *conv_kernel* defines the number of convolutional layers and has to match the length of
  45. *conv_dim*.
  46. conv_bias (`bool`, *optional*, defaults to `False`):
  47. Whether the 1D convolutional layers have a bias.
  48. num_conv_pos_embeddings (`int`, *optional*, defaults to 128):
  49. Number of convolutional positional embeddings. Defines the kernel size of 1D convolutional positional
  50. embeddings layer.
  51. num_conv_pos_embedding_groups (`int`, *optional*, defaults to 16):
  52. Number of groups of 1D convolutional positional embeddings layer.
  53. apply_spec_augment (`bool`, *optional*, defaults to `True`):
  54. Whether to apply *SpecAugment* data augmentation to the outputs of the speech encoder pre-net. For
  55. reference see [SpecAugment: A Simple Data Augmentation Method for Automatic Speech
  56. Recognition](https://huggingface.co/papers/1904.08779).
  57. mask_time_prob (`float`, *optional*, defaults to 0.05):
  58. Percentage (between 0 and 1) of all feature vectors along the time axis which will be masked. The masking
  59. procedure generates ''mask_time_prob*len(time_axis)/mask_time_length'' independent masks over the axis. If
  60. reasoning from the probability of each feature vector to be chosen as the start of the vector span to be
  61. masked, *mask_time_prob* should be `prob_vector_start*mask_time_length`. Note that overlap may decrease the
  62. actual percentage of masked vectors. This is only relevant if `apply_spec_augment is True`.
  63. mask_time_length (`int`, *optional*, defaults to 10):
  64. Length of vector span along the time axis.
  65. mask_time_min_masks (`int`, *optional*, defaults to 2),:
  66. The minimum number of masks of length `mask_feature_length` generated along the time axis, each time step,
  67. irrespectively of `mask_feature_prob`. Only relevant if ''mask_time_prob*len(time_axis)/mask_time_length <
  68. mask_time_min_masks''
  69. mask_feature_prob (`float`, *optional*, defaults to 0.0):
  70. Percentage (between 0 and 1) of all feature vectors along the feature axis which will be masked. The
  71. masking procedure generates ''mask_feature_prob*len(feature_axis)/mask_time_length'' independent masks over
  72. the axis. If reasoning from the probability of each feature vector to be chosen as the start of the vector
  73. span to be masked, *mask_feature_prob* should be `prob_vector_start*mask_feature_length`. Note that overlap
  74. may decrease the actual percentage of masked vectors. This is only relevant if `apply_spec_augment is
  75. True`.
  76. mask_feature_length (`int`, *optional*, defaults to 10):
  77. Length of vector span along the feature axis.
  78. mask_feature_min_masks (`int`, *optional*, defaults to 0),:
  79. The minimum number of masks of length `mask_feature_length` generated along the feature axis, each time
  80. step, irrespectively of `mask_feature_prob`. Only relevant if
  81. ''mask_feature_prob*len(feature_axis)/mask_feature_length < mask_feature_min_masks''
  82. num_mel_bins (`int`, *optional*, defaults to 80):
  83. Number of mel features used per input features. Used by the speech decoder pre-net. Should correspond to
  84. the value used in the [`SpeechT5Processor`] class.
  85. speech_decoder_prenet_layers (`int`, *optional*, defaults to 2):
  86. Number of layers in the speech decoder pre-net.
  87. speech_decoder_prenet_units (`int`, *optional*, defaults to 256):
  88. Dimensionality of the layers in the speech decoder pre-net.
  89. speech_decoder_prenet_dropout (`float`, *optional*, defaults to 0.5):
  90. The dropout probability for the speech decoder pre-net layers.
  91. speaker_embedding_dim (`int`, *optional*, defaults to 512):
  92. Dimensionality of the *XVector* embedding vectors.
  93. speech_decoder_postnet_layers (`int`, *optional*, defaults to 5):
  94. Number of layers in the speech decoder post-net.
  95. speech_decoder_postnet_units (`int`, *optional*, defaults to 256):
  96. Dimensionality of the layers in the speech decoder post-net.
  97. speech_decoder_postnet_kernel (`int`, *optional*, defaults to 5):
  98. Number of convolutional filter channels in the speech decoder post-net.
  99. speech_decoder_postnet_dropout (`float`, *optional*, defaults to 0.5):
  100. The dropout probability for the speech decoder post-net layers.
  101. reduction_factor (`int`, *optional*, defaults to 2):
  102. Spectrogram length reduction factor for the speech decoder inputs.
  103. max_speech_positions (`int`, *optional*, defaults to 4000):
  104. The maximum sequence length of speech features that this model might ever be used with.
  105. max_text_positions (`int`, *optional*, defaults to 450):
  106. The maximum sequence length of text features that this model might ever be used with.
  107. encoder_max_relative_position (`int`, *optional*, defaults to 160):
  108. Maximum distance for relative position embedding in the encoder.
  109. use_guided_attention_loss (`bool`, *optional*, defaults to `True`):
  110. Whether to apply guided attention loss while training the TTS model.
  111. guided_attention_loss_num_heads (`int`, *optional*, defaults to 2):
  112. Number of attention heads the guided attention loss will be applied to. Use -1 to apply this loss to all
  113. attention heads.
  114. guided_attention_loss_sigma (`float`, *optional*, defaults to 0.4):
  115. Standard deviation for guided attention loss.
  116. guided_attention_loss_scale (`float`, *optional*, defaults to 10.0):
  117. Scaling coefficient for guided attention loss (also known as lambda).
  118. Example:
  119. ```python
  120. >>> from transformers import SpeechT5Model, SpeechT5Config
  121. >>> # Initializing a "microsoft/speecht5_asr" style configuration
  122. >>> configuration = SpeechT5Config()
  123. >>> # Initializing a model (with random weights) from the "microsoft/speecht5_asr" style configuration
  124. >>> model = SpeechT5Model(configuration)
  125. >>> # Accessing the model configuration
  126. >>> configuration = model.config
  127. ```"""
  128. model_type = "speecht5"
  129. attribute_map = {"num_attention_heads": "encoder_attention_heads", "num_hidden_layers": "encoder_layers"}
  130. vocab_size: int = 81
  131. hidden_size: int = 768
  132. encoder_layers: int = 12
  133. encoder_attention_heads: int = 12
  134. encoder_ffn_dim: int = 3072
  135. encoder_layerdrop: float | int = 0.1
  136. decoder_layers: int = 6
  137. decoder_ffn_dim: int = 3072
  138. decoder_attention_heads: int = 12
  139. decoder_layerdrop: float | int = 0.1
  140. hidden_act: str = "gelu"
  141. positional_dropout: float | int = 0.1
  142. hidden_dropout: float | int = 0.1
  143. attention_dropout: float | int = 0.1
  144. activation_dropout: float | int = 0.1
  145. initializer_range: float = 0.02
  146. layer_norm_eps: float = 1e-5
  147. scale_embedding: bool = False
  148. feat_extract_norm: str = "group"
  149. feat_proj_dropout: float | int = 0.0
  150. feat_extract_activation: str = "gelu"
  151. conv_dim: list[int] | tuple[int, ...] = (512, 512, 512, 512, 512, 512, 512)
  152. conv_stride: list[int] | tuple[int, ...] = (5, 2, 2, 2, 2, 2, 2)
  153. conv_kernel: list[int] | tuple[int, ...] = (10, 3, 3, 3, 3, 2, 2)
  154. conv_bias: bool = False
  155. num_conv_pos_embeddings: int = 128
  156. num_conv_pos_embedding_groups: int = 16
  157. apply_spec_augment: bool = True
  158. mask_time_prob: float | int = 0.05
  159. mask_time_length: int = 10
  160. mask_time_min_masks: int = 2
  161. mask_feature_prob: float | int = 0.0
  162. mask_feature_length: int = 10
  163. mask_feature_min_masks: int = 0
  164. pad_token_id: int | None = 1
  165. bos_token_id: int | None = 0
  166. eos_token_id: int | list[int] | None = 2
  167. decoder_start_token_id: int | None = 2
  168. num_mel_bins: int = 80
  169. speech_decoder_prenet_layers: int = 2
  170. speech_decoder_prenet_units: int = 256
  171. speech_decoder_prenet_dropout: float | int = 0.5
  172. speaker_embedding_dim: int = 512
  173. speech_decoder_postnet_layers: int = 5
  174. speech_decoder_postnet_units: int = 256
  175. speech_decoder_postnet_kernel: int = 5
  176. speech_decoder_postnet_dropout: float | int = 0.5
  177. reduction_factor: int = 2
  178. max_speech_positions: int = 4000
  179. max_text_positions: int = 450
  180. encoder_max_relative_position: int = 160
  181. use_guided_attention_loss: bool = True
  182. guided_attention_loss_num_heads: int = 2
  183. guided_attention_loss_sigma: float = 0.4
  184. guided_attention_loss_scale: float = 10.0
  185. use_cache: bool = True
  186. is_encoder_decoder: bool = True
  187. tie_word_embeddings: bool = True
  188. def __post_init__(self, **kwargs):
  189. self.num_feat_extract_layers = len(self.conv_dim)
  190. super().__post_init__(**kwargs)
  191. def validate_architecture(self):
  192. """Part of `@strict`-powered validation. Validates the architecture of the config."""
  193. if (
  194. (len(self.conv_stride) != self.num_feat_extract_layers)
  195. or (len(self.conv_kernel) != self.num_feat_extract_layers)
  196. or (len(self.conv_dim) != self.num_feat_extract_layers)
  197. ):
  198. raise ValueError(
  199. "Configuration for convolutional layers is incorrect. It is required that `len(config.conv_dim)` =="
  200. " `len(config.conv_stride)` == `len(config.conv_kernel)`, but is `len(config.conv_dim) ="
  201. f" {len(self.conv_dim)}`, `len(config.conv_stride) = {len(self.conv_stride)}`,"
  202. f" `len(config.conv_kernel) = {len(self.conv_kernel)}`."
  203. )
  204. def inputs_to_logits_ratio(self):
  205. return functools.reduce(operator.mul, self.conv_stride, 1)
  206. @auto_docstring(checkpoint="microsoft/speecht5_asr")
  207. @strict
  208. class SpeechT5HifiGanConfig(PreTrainedConfig):
  209. r"""
  210. model_in_dim (`int`, *optional*, defaults to 80):
  211. The number of frequency bins in the input log-mel spectrogram.
  212. upsample_initial_channel (`int`, *optional*, defaults to 512):
  213. The number of input channels into the upsampling network.
  214. upsample_rates (`tuple[int]` or `list[int]`, *optional*, defaults to `[4, 4, 4, 4]`):
  215. A tuple of integers defining the stride of each 1D convolutional layer in the upsampling network. The
  216. length of *upsample_rates* defines the number of convolutional layers and has to match the length of
  217. *upsample_kernel_sizes*.
  218. upsample_kernel_sizes (`tuple[int]` or `list[int]`, *optional*, defaults to `[8, 8, 8, 8]`):
  219. A tuple of integers defining the kernel size of each 1D convolutional layer in the upsampling network. The
  220. length of *upsample_kernel_sizes* defines the number of convolutional layers and has to match the length of
  221. *upsample_rates*.
  222. resblock_kernel_sizes (`tuple[int]` or `list[int]`, *optional*, defaults to `[3, 7, 11]`):
  223. A tuple of integers defining the kernel sizes of the 1D convolutional layers in the multi-receptive field
  224. fusion (MRF) module.
  225. resblock_dilation_sizes (`tuple[tuple[int]]` or `list[list[int]]`, *optional*, defaults to `[[1, 3, 5], [1, 3, 5], [1, 3, 5]]`):
  226. A nested tuple of integers defining the dilation rates of the dilated 1D convolutional layers in the
  227. multi-receptive field fusion (MRF) module.
  228. leaky_relu_slope (`float`, *optional*, defaults to 0.1):
  229. The angle of the negative slope used by the leaky ReLU activation.
  230. normalize_before (`bool`, *optional*, defaults to `True`):
  231. Whether or not to normalize the spectrogram before vocoding using the vocoder's learned mean and variance.
  232. Example:
  233. ```python
  234. >>> from transformers import SpeechT5HifiGan, SpeechT5HifiGanConfig
  235. >>> # Initializing a "microsoft/speecht5_hifigan" style configuration
  236. >>> configuration = SpeechT5HifiGanConfig()
  237. >>> # Initializing a model (with random weights) from the "microsoft/speecht5_hifigan" style configuration
  238. >>> model = SpeechT5HifiGan(configuration)
  239. >>> # Accessing the model configuration
  240. >>> configuration = model.config
  241. ```"""
  242. model_type = "hifigan"
  243. model_in_dim: int = 80
  244. sampling_rate: int = 16000
  245. upsample_initial_channel: int = 512
  246. upsample_rates: list[int] | tuple[int, ...] = (4, 4, 4, 4)
  247. upsample_kernel_sizes: list[int] | tuple[int, ...] = (8, 8, 8, 8)
  248. resblock_kernel_sizes: list[int] | tuple[int, ...] = (3, 7, 11)
  249. resblock_dilation_sizes: list | tuple = ((1, 3, 5), (1, 3, 5), (1, 3, 5))
  250. initializer_range: float = 0.01
  251. leaky_relu_slope: float = 0.1
  252. normalize_before: bool = True
  253. __all__ = ["SpeechT5Config", "SpeechT5HifiGanConfig"]