configuration_wavlm.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239
  1. # Copyright 2021 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. """WavLM 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/wavlm-base")
  21. @strict
  22. class WavLMConfig(PreTrainedConfig):
  23. r"""
  24. feat_proj_dropout (`float`, *optional*, defaults to 0.0):
  25. The dropout probability for output of the feature encoder.
  26. final_dropout (`float`, *optional*, defaults to 0.1):
  27. The dropout probability for the final projection layer of [`WavLMForCTC`].
  28. feat_extract_norm (`str`, *optional*, defaults to `"group"`):
  29. The norm to be applied to 1D convolutional layers in feature encoder. One of `"group"` for group
  30. normalization of only the first 1D convolutional layer or `"layer"` for layer normalization of all 1D
  31. convolutional layers.
  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. feature encoder. 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 feature encoder. The length
  40. of *conv_stride* defines the number of convolutional layers and has to match the length of *conv_dim*.
  41. conv_kernel (`tuple[int]` or `list[int]`, *optional*, defaults to `(10, 3, 3, 3, 3, 3, 3)`):
  42. A tuple of integers defining the kernel size of each 1D convolutional layer in the feature encoder. The
  43. length of *conv_kernel* defines the number of convolutional layers and has to match the length of
  44. *conv_dim*.
  45. conv_bias (`bool`, *optional*, defaults to `False`):
  46. Whether the 1D convolutional layers have a bias.
  47. num_conv_pos_embeddings (`int`, *optional*, defaults to 128):
  48. Number of convolutional positional embeddings. Defines the kernel size of 1D convolutional positional
  49. embeddings layer.
  50. num_conv_pos_embedding_groups (`int`, *optional*, defaults to 16):
  51. Number of groups of 1D convolutional positional embeddings layer.
  52. num_buckets (`int`, *optional*, defaults to 320):
  53. The number of buckets to use for each attention layer
  54. max_bucket_distance (`int`, *optional*, defaults to 800):
  55. Maximum bucket distance
  56. do_stable_layer_norm (`bool`, *optional*, defaults to `False`):
  57. Whether to apply *stable* layer norm architecture of the Transformer encoder. `do_stable_layer_norm is
  58. True` corresponds to applying layer norm before the attention layer, whereas `do_stable_layer_norm is
  59. False` corresponds to applying layer norm after the attention layer.
  60. apply_spec_augment (`bool`, *optional*, defaults to `True`):
  61. Whether to apply *SpecAugment* data augmentation to the outputs of the feature encoder. For reference see
  62. [SpecAugment: A Simple Data Augmentation Method for Automatic Speech
  63. Recognition](https://huggingface.co/papers/1904.08779).
  64. mask_time_prob (`float`, *optional*, defaults to 0.05):
  65. Probability of each feature vector along the time axis to be chosen as the start of the vector span to be
  66. masked. Approximately `mask_time_prob * sequence_length // mask_time_length` feature vectors will be masked
  67. along the time axis. This is only relevant if `apply_spec_augment is True`.
  68. mask_time_length (`int`, *optional*, defaults to 10):
  69. Length of vector span along the time axis.
  70. mask_time_min_masks (`int`, *optional*, defaults to 2),:
  71. The minimum number of masks of length `mask_feature_length` generated along the time axis, each time step,
  72. irrespectively of `mask_feature_prob`. Only relevant if ''mask_time_prob*len(time_axis)/mask_time_length <
  73. mask_time_min_masks''
  74. mask_feature_prob (`float`, *optional*, defaults to 0.0):
  75. Probability of each feature vector along the feature axis to be chosen as the start of the vector span to
  76. be masked. Approximately `mask_time_prob * hidden_size // mask_time_length` feature vectors will be masked
  77. along the time axis. This is only relevant if `apply_spec_augment is True`.
  78. mask_feature_length (`int`, *optional*, defaults to 10):
  79. Length of vector span along the feature axis.
  80. num_codevectors_per_group (`int`, *optional*, defaults to 320):
  81. Number of entries in each quantization codebook (group).
  82. num_codevector_groups (`int`, *optional*, defaults to 2):
  83. Number of codevector groups for product codevector quantization.
  84. contrastive_logits_temperature (`float`, *optional*, defaults to 0.1):
  85. The temperature *kappa* in the contrastive loss.
  86. num_negatives (`int`, *optional*, defaults to 100):
  87. Number of negative samples for the contrastive loss.
  88. codevector_dim (`int`, *optional*, defaults to 256):
  89. Dimensionality of the quantized feature vectors.
  90. proj_codevector_dim (`int`, *optional*, defaults to 256):
  91. Dimensionality of the final projection of both the quantized and the transformer features.
  92. diversity_loss_weight (`int`, *optional*, defaults to 0.1):
  93. The weight of the codebook diversity loss component.
  94. ctc_zero_infinity (`bool`, *optional*, defaults to `False`):
  95. Whether to zero infinite losses and the associated gradients of `torch.nn.CTCLoss`. Infinite losses mainly
  96. occur when the inputs are too short to be aligned to the targets. Only relevant when training an instance
  97. of [`WavLMForCTC`].
  98. use_weighted_layer_sum (`bool`, *optional*, defaults to `False`):
  99. Whether to use a weighted average of layer outputs with learned weights. Only relevant when using an
  100. instance of [`WavLMForSequenceClassification`].
  101. classifier_proj_size (`int`, *optional*, defaults to 256):
  102. Dimensionality of the projection before token mean-pooling for classification.
  103. tdnn_dim (`tuple[int]` or `list[int]`, *optional*, defaults to `(512, 512, 512, 512, 1500)`):
  104. A tuple of integers defining the number of output channels of each 1D convolutional layer in the *TDNN*
  105. module of the *XVector* model. The length of *tdnn_dim* defines the number of *TDNN* layers.
  106. tdnn_kernel (`tuple[int]` or `list[int]`, *optional*, defaults to `(5, 3, 3, 1, 1)`):
  107. A tuple of integers defining the kernel size of each 1D convolutional layer in the *TDNN* module of the
  108. *XVector* model. The length of *tdnn_kernel* has to match the length of *tdnn_dim*.
  109. tdnn_dilation (`tuple[int]` or `list[int]`, *optional*, defaults to `(1, 2, 3, 1, 1)`):
  110. A tuple of integers defining the dilation factor of each 1D convolutional layer in *TDNN* module of the
  111. *XVector* model. The length of *tdnn_dilation* has to match the length of *tdnn_dim*.
  112. xvector_output_dim (`int`, *optional*, defaults to 512):
  113. Dimensionality of the *XVector* embedding vectors.
  114. num_ctc_classes (`int`, *optional*, defaults to 80):
  115. Specifies the number of classes (phoneme tokens and blank token) for phoneme-level CTC loss. Only relevant
  116. when using an instance of [`UniSpeechForPreTraining`].
  117. add_adapter (`bool`, *optional*, defaults to `False`):
  118. Whether a convolutional network should be stacked on top of the Wav2Vec2 Encoder. Can be very useful for
  119. warm-starting Wav2Vec2 for SpeechEncoderDecoder models.
  120. adapter_kernel_size (`int`, *optional*, defaults to 3):
  121. Kernel size of the convolutional layers in the adapter network. Only relevant if `add_adapter is True`.
  122. adapter_stride (`int`, *optional*, defaults to 2):
  123. Stride of the convolutional layers in the adapter network. Only relevant if `add_adapter is True`.
  124. num_adapter_layers (`int`, *optional*, defaults to 3):
  125. Number of convolutional layers that should be used in the adapter network. Only relevant if `add_adapter is
  126. True`.
  127. output_hidden_size (`int`, *optional*):
  128. Dimensionality of the encoder output layer. If not defined, this defaults to *hidden-size*. Only relevant
  129. if `add_adapter is True`.
  130. Example:
  131. ```python
  132. ```
  133. Example:
  134. ```python
  135. >>> from transformers import WavLMConfig, WavLMModel
  136. >>> # Initializing a WavLM facebook/wavlm-base-960h style configuration
  137. >>> configuration = WavLMConfig()
  138. >>> # Initializing a model (with random weights) from the facebook/wavlm-base-960h style configuration
  139. >>> model = WavLMModel(configuration)
  140. >>> # Accessing the model configuration
  141. >>> configuration = model.config
  142. ```"""
  143. model_type = "wavlm"
  144. vocab_size: int = 32
  145. hidden_size: int = 768
  146. num_hidden_layers: int = 12
  147. num_attention_heads: int = 12
  148. intermediate_size: int = 3072
  149. hidden_act: str = "gelu"
  150. hidden_dropout: float | int = 0.1
  151. activation_dropout: float | int = 0.1
  152. attention_dropout: float | int = 0.1
  153. feat_proj_dropout: float | int = 0.0
  154. final_dropout: float | int = 0.1
  155. layerdrop: float | int = 0.1
  156. initializer_range: float = 0.02
  157. layer_norm_eps: float = 1e-5
  158. feat_extract_norm: str = "group"
  159. feat_extract_activation: str = "gelu"
  160. conv_dim: list[int] | tuple[int, ...] = (512, 512, 512, 512, 512, 512, 512)
  161. conv_stride: list[int] | tuple[int, ...] = (5, 2, 2, 2, 2, 2, 2)
  162. conv_kernel: list[int] | tuple[int, ...] = (10, 3, 3, 3, 3, 2, 2)
  163. conv_bias: bool = False
  164. num_conv_pos_embeddings: int = 128
  165. num_conv_pos_embedding_groups: int = 16
  166. num_buckets: int = 320
  167. max_bucket_distance: int = 800
  168. do_stable_layer_norm: bool = False
  169. apply_spec_augment: bool = True
  170. mask_time_prob: float | int = 0.05
  171. mask_time_length: int = 10
  172. mask_time_min_masks: int = 2
  173. mask_feature_prob: float | int = 0.0
  174. mask_feature_length: int = 10
  175. num_codevectors_per_group: int = 320
  176. num_codevector_groups: int = 2
  177. contrastive_logits_temperature: float = 0.1
  178. num_negatives: int = 100
  179. codevector_dim: int = 256
  180. proj_codevector_dim: int = 256
  181. diversity_loss_weight: float = 0.1
  182. ctc_loss_reduction: str = "mean"
  183. ctc_zero_infinity: bool = False
  184. use_weighted_layer_sum: bool = False
  185. classifier_proj_size: int = 256
  186. tdnn_dim: list[int] | tuple[int, ...] = (512, 512, 512, 512, 1500)
  187. tdnn_kernel: list[int] | tuple[int, ...] = (5, 3, 3, 1, 1)
  188. tdnn_dilation: list[int] | tuple[int, ...] = (1, 2, 3, 1, 1)
  189. xvector_output_dim: int = 512
  190. num_ctc_classes: int = 80
  191. pad_token_id: int | None = 0
  192. bos_token_id: int | None = 1
  193. eos_token_id: int | list[int] | None = 2
  194. add_adapter: bool = False
  195. adapter_kernel_size: int = 3
  196. adapter_stride: int = 2
  197. num_adapter_layers: int = 3
  198. output_hidden_size: int | None = None
  199. def __post_init__(self, **kwargs):
  200. self.num_feat_extract_layers = len(self.conv_dim)
  201. self.output_hidden_size = self.output_hidden_size or self.hidden_size
  202. super().__post_init__(**kwargs)
  203. def validate_architecture(self):
  204. """Part of `@strict`-powered validation. Validates the architecture of the config."""
  205. if (
  206. (len(self.conv_stride) != self.num_feat_extract_layers)
  207. or (len(self.conv_kernel) != self.num_feat_extract_layers)
  208. or (len(self.conv_dim) != self.num_feat_extract_layers)
  209. ):
  210. raise ValueError(
  211. "Configuration for convolutional layers is incorrect. It is required that `len(config.conv_dim)` =="
  212. " `len(config.conv_stride)` == `len(config.conv_kernel)`, but is `len(config.conv_dim) ="
  213. f" {len(self.conv_dim)}`, `len(config.conv_stride) = {len(self.conv_stride)}`,"
  214. f" `len(config.conv_kernel) = {len(self.conv_kernel)}`."
  215. )
  216. @property
  217. def inputs_to_logits_ratio(self):
  218. return functools.reduce(operator.mul, self.conv_stride, 1)
  219. __all__ = ["WavLMConfig"]