configuration_wav2vec2.py 14 KB

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