configuration_wav2vec2.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347
  1. # coding=utf-8
  2. # Copyright 2021 The Fairseq 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. """Wav2Vec2 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 Wav2Vec2Config(PretrainedConfig):
  22. r"""
  23. This is the configuration class to store the configuration of a [`Wav2Vec2Model`]. It is used to instantiate an
  24. Wav2Vec2 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 Wav2Vec2
  26. [facebook/wav2vec2-base-960h](https://huggingface.co/facebook/wav2vec2-base-960h) 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 32):
  31. Vocabulary size of the Wav2Vec2 model. Defines the number of different tokens that can be represented by
  32. the `inputs_ids` passed when calling [`Wav2Vec2Model`] or [`TFWav2Vec2Model`]. Vocabulary size of the
  33. model. Defines the different tokens that can be represented by the *inputs_ids* passed to the forward
  34. method of [`Wav2Vec2Model`].
  35. hidden_size (`int`, *optional*, defaults to 768):
  36. Dimensionality of the encoder layers and the pooler layer.
  37. num_hidden_layers (`int`, *optional*, defaults to 12):
  38. Number of hidden layers in the Transformer encoder.
  39. num_attention_heads (`int`, *optional*, defaults to 12):
  40. Number of attention heads for each attention layer in the Transformer encoder.
  41. intermediate_size (`int`, *optional*, defaults to 3072):
  42. Dimensionality of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder.
  43. hidden_act (`str` or `function`, *optional*, defaults to `"gelu"`):
  44. The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
  45. `"relu"`, `"selu"` and `"gelu_new"` are supported.
  46. hidden_dropout (`float`, *optional*, defaults to 0.1):
  47. The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
  48. activation_dropout (`float`, *optional*, defaults to 0.1):
  49. The dropout ratio for activations inside the fully connected layer.
  50. attention_dropout (`float`, *optional*, defaults to 0.1):
  51. The dropout ratio for the attention probabilities.
  52. final_dropout (`float`, *optional*, defaults to 0.1):
  53. The dropout probability for the final projection layer of [`Wav2Vec2ForCTC`].
  54. layerdrop (`float`, *optional*, defaults to 0.1):
  55. The LayerDrop probability. See the [LayerDrop paper](see https://huggingface.co/papers/1909.11556) for more
  56. details.
  57. initializer_range (`float`, *optional*, defaults to 0.02):
  58. The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
  59. layer_norm_eps (`float`, *optional*, defaults to 1e-12):
  60. The epsilon used by the layer normalization layers.
  61. feat_extract_norm (`str`, *optional*, defaults to `"group"`):
  62. The norm to be applied to 1D convolutional layers in feature encoder. One of `"group"` for group
  63. normalization of only the first 1D convolutional layer or `"layer"` for layer normalization of all 1D
  64. convolutional layers.
  65. feat_proj_dropout (`float`, *optional*, defaults to 0.0):
  66. The dropout probability for output of the feature encoder.
  67. feat_extract_activation (`str, `optional`, defaults to `"gelu"`):
  68. The non-linear activation function (function or string) in the 1D convolutional layers of the feature
  69. extractor. If string, `"gelu"`, `"relu"`, `"selu"` and `"gelu_new"` are supported.
  70. feat_quantizer_dropout (`float`, *optional*, defaults to 0.0):
  71. The dropout probability for quantized feature encoder states.
  72. conv_dim (`tuple[int]` or `list[int]`, *optional*, defaults to `(512, 512, 512, 512, 512, 512, 512)`):
  73. A tuple of integers defining the number of input and output channels of each 1D convolutional layer in the
  74. feature encoder. The length of *conv_dim* defines the number of 1D convolutional layers.
  75. conv_stride (`tuple[int]` or `list[int]`, *optional*, defaults to `(5, 2, 2, 2, 2, 2, 2)`):
  76. A tuple of integers defining the stride of each 1D convolutional layer in the feature encoder. The length
  77. of *conv_stride* defines the number of convolutional layers and has to match the length of *conv_dim*.
  78. conv_kernel (`tuple[int]` or `list[int]`, *optional*, defaults to `(10, 3, 3, 3, 3, 3, 3)`):
  79. A tuple of integers defining the kernel size of each 1D convolutional layer in the feature encoder. The
  80. length of *conv_kernel* defines the number of convolutional layers and has to match the length of
  81. *conv_dim*.
  82. conv_bias (`bool`, *optional*, defaults to `False`):
  83. Whether the 1D convolutional layers have a bias.
  84. num_conv_pos_embeddings (`int`, *optional*, defaults to 128):
  85. Number of convolutional positional embeddings. Defines the kernel size of 1D convolutional positional
  86. embeddings layer.
  87. num_conv_pos_embedding_groups (`int`, *optional*, defaults to 16):
  88. Number of groups of 1D convolutional positional embeddings layer.
  89. do_stable_layer_norm (`bool`, *optional*, defaults to `False`):
  90. Whether to apply *stable* layer norm architecture of the Transformer encoder. `do_stable_layer_norm is
  91. True` corresponds to applying layer norm before the attention layer, whereas `do_stable_layer_norm is
  92. False` corresponds to applying layer norm after the attention layer.
  93. apply_spec_augment (`bool`, *optional*, defaults to `True`):
  94. Whether to apply *SpecAugment* data augmentation to the outputs of the feature encoder. For reference see
  95. [SpecAugment: A Simple Data Augmentation Method for Automatic Speech
  96. Recognition](https://huggingface.co/papers/1904.08779).
  97. mask_time_prob (`float`, *optional*, defaults to 0.05):
  98. Percentage (between 0 and 1) of all feature vectors along the time axis which will be masked. The masking
  99. procedure generates ''mask_time_prob*len(time_axis)/mask_time_length'' independent masks over the axis. If
  100. reasoning from the probability of each feature vector to be chosen as the start of the vector span to be
  101. masked, *mask_time_prob* should be `prob_vector_start*mask_time_length`. Note that overlap may decrease the
  102. actual percentage of masked vectors. This is only relevant if `apply_spec_augment is True`.
  103. mask_time_length (`int`, *optional*, defaults to 10):
  104. Length of vector span along the time axis.
  105. mask_time_min_masks (`int`, *optional*, defaults to 2),:
  106. The minimum number of masks of length `mask_feature_length` generated along the time axis, each time step,
  107. irrespectively of `mask_feature_prob`. Only relevant if ''mask_time_prob*len(time_axis)/mask_time_length <
  108. mask_time_min_masks''
  109. mask_feature_prob (`float`, *optional*, defaults to 0.0):
  110. Percentage (between 0 and 1) of all feature vectors along the feature axis which will be masked. The
  111. masking procedure generates ''mask_feature_prob*len(feature_axis)/mask_time_length'' independent masks over
  112. the axis. If reasoning from the probability of each feature vector to be chosen as the start of the vector
  113. span to be masked, *mask_feature_prob* should be `prob_vector_start*mask_feature_length`. Note that overlap
  114. may decrease the actual percentage of masked vectors. This is only relevant if `apply_spec_augment is
  115. True`.
  116. mask_feature_length (`int`, *optional*, defaults to 10):
  117. Length of vector span along the feature axis.
  118. mask_feature_min_masks (`int`, *optional*, defaults to 0),:
  119. The minimum number of masks of length `mask_feature_length` generated along the feature axis, each time
  120. step, irrespectively of `mask_feature_prob`. Only relevant if
  121. ''mask_feature_prob*len(feature_axis)/mask_feature_length < mask_feature_min_masks''
  122. num_codevectors_per_group (`int`, *optional*, defaults to 320):
  123. Number of entries in each quantization codebook (group).
  124. num_codevector_groups (`int`, *optional*, defaults to 2):
  125. Number of codevector groups for product codevector quantization.
  126. contrastive_logits_temperature (`float`, *optional*, defaults to 0.1):
  127. The temperature *kappa* in the contrastive loss.
  128. feat_quantizer_dropout (`float`, *optional*, defaults to 0.0):
  129. The dropout probability for the output of the feature encoder that's used by the quantizer.
  130. num_negatives (`int`, *optional*, defaults to 100):
  131. Number of negative samples for the contrastive loss.
  132. codevector_dim (`int`, *optional*, defaults to 256):
  133. Dimensionality of the quantized feature vectors.
  134. proj_codevector_dim (`int`, *optional*, defaults to 256):
  135. Dimensionality of the final projection of both the quantized and the transformer features.
  136. diversity_loss_weight (`int`, *optional*, defaults to 0.1):
  137. The weight of the codebook diversity loss component.
  138. ctc_loss_reduction (`str`, *optional*, defaults to `"sum"`):
  139. Specifies the reduction to apply to the output of `torch.nn.CTCLoss`. Only relevant when training an
  140. instance of [`Wav2Vec2ForCTC`].
  141. ctc_zero_infinity (`bool`, *optional*, defaults to `False`):
  142. Whether to zero infinite losses and the associated gradients of `torch.nn.CTCLoss`. Infinite losses mainly
  143. occur when the inputs are too short to be aligned to the targets. Only relevant when training an instance
  144. of [`Wav2Vec2ForCTC`].
  145. use_weighted_layer_sum (`bool`, *optional*, defaults to `False`):
  146. Whether to use a weighted average of layer outputs with learned weights. Only relevant when using an
  147. instance of [`Wav2Vec2ForSequenceClassification`].
  148. classifier_proj_size (`int`, *optional*, defaults to 256):
  149. Dimensionality of the projection before token mean-pooling for classification.
  150. tdnn_dim (`tuple[int]` or `list[int]`, *optional*, defaults to `(512, 512, 512, 512, 1500)`):
  151. A tuple of integers defining the number of output channels of each 1D convolutional layer in the *TDNN*
  152. module of the *XVector* model. The length of *tdnn_dim* defines the number of *TDNN* layers.
  153. tdnn_kernel (`tuple[int]` or `list[int]`, *optional*, defaults to `(5, 3, 3, 1, 1)`):
  154. A tuple of integers defining the kernel size of each 1D convolutional layer in the *TDNN* module of the
  155. *XVector* model. The length of *tdnn_kernel* has to match the length of *tdnn_dim*.
  156. tdnn_dilation (`tuple[int]` or `list[int]`, *optional*, defaults to `(1, 2, 3, 1, 1)`):
  157. A tuple of integers defining the dilation factor of each 1D convolutional layer in *TDNN* module of the
  158. *XVector* model. The length of *tdnn_dilation* has to match the length of *tdnn_dim*.
  159. xvector_output_dim (`int`, *optional*, defaults to 512):
  160. Dimensionality of the *XVector* embedding vectors.
  161. add_adapter (`bool`, *optional*, defaults to `False`):
  162. Whether a convolutional network should be stacked on top of the Wav2Vec2 Encoder. Can be very useful for
  163. warm-starting Wav2Vec2 for SpeechEncoderDecoder models.
  164. adapter_kernel_size (`int`, *optional*, defaults to 3):
  165. Kernel size of the convolutional layers in the adapter network. Only relevant if `add_adapter is True`.
  166. adapter_stride (`int`, *optional*, defaults to 2):
  167. Stride of the convolutional layers in the adapter network. Only relevant if `add_adapter is True`.
  168. num_adapter_layers (`int`, *optional*, defaults to 3):
  169. Number of convolutional layers that should be used in the adapter network. Only relevant if `add_adapter is
  170. True`.
  171. adapter_attn_dim (`int`, *optional*):
  172. Dimension of the attention adapter weights to be used in each attention block. An example of a model using
  173. attention adapters is [facebook/mms-1b-all](https://huggingface.co/facebook/mms-1b-all).
  174. output_hidden_size (`int`, *optional*):
  175. Dimensionality of the encoder output layer. If not defined, this defaults to *hidden-size*. Only relevant
  176. if `add_adapter is True`.
  177. Example:
  178. ```python
  179. >>> from transformers import Wav2Vec2Config, Wav2Vec2Model
  180. >>> # Initializing a Wav2Vec2 facebook/wav2vec2-base-960h style configuration
  181. >>> configuration = Wav2Vec2Config()
  182. >>> # Initializing a model (with random weights) from the facebook/wav2vec2-base-960h style configuration
  183. >>> model = Wav2Vec2Model(configuration)
  184. >>> # Accessing the model configuration
  185. >>> configuration = model.config
  186. ```"""
  187. model_type = "wav2vec2"
  188. def __init__(
  189. self,
  190. vocab_size=32,
  191. hidden_size=768,
  192. num_hidden_layers=12,
  193. num_attention_heads=12,
  194. intermediate_size=3072,
  195. hidden_act="gelu",
  196. hidden_dropout=0.1,
  197. activation_dropout=0.1,
  198. attention_dropout=0.1,
  199. feat_proj_dropout=0.0,
  200. feat_quantizer_dropout=0.0,
  201. final_dropout=0.1,
  202. layerdrop=0.1,
  203. initializer_range=0.02,
  204. layer_norm_eps=1e-5,
  205. feat_extract_norm="group",
  206. feat_extract_activation="gelu",
  207. conv_dim=(512, 512, 512, 512, 512, 512, 512),
  208. conv_stride=(5, 2, 2, 2, 2, 2, 2),
  209. conv_kernel=(10, 3, 3, 3, 3, 2, 2),
  210. conv_bias=False,
  211. num_conv_pos_embeddings=128,
  212. num_conv_pos_embedding_groups=16,
  213. do_stable_layer_norm=False,
  214. apply_spec_augment=True,
  215. mask_time_prob=0.05,
  216. mask_time_length=10,
  217. mask_time_min_masks=2,
  218. mask_feature_prob=0.0,
  219. mask_feature_length=10,
  220. mask_feature_min_masks=0,
  221. num_codevectors_per_group=320,
  222. num_codevector_groups=2,
  223. contrastive_logits_temperature=0.1,
  224. num_negatives=100,
  225. codevector_dim=256,
  226. proj_codevector_dim=256,
  227. diversity_loss_weight=0.1,
  228. ctc_loss_reduction="sum",
  229. ctc_zero_infinity=False,
  230. use_weighted_layer_sum=False,
  231. classifier_proj_size=256,
  232. tdnn_dim=(512, 512, 512, 512, 1500),
  233. tdnn_kernel=(5, 3, 3, 1, 1),
  234. tdnn_dilation=(1, 2, 3, 1, 1),
  235. xvector_output_dim=512,
  236. pad_token_id=0,
  237. bos_token_id=1,
  238. eos_token_id=2,
  239. add_adapter=False,
  240. adapter_kernel_size=3,
  241. adapter_stride=2,
  242. num_adapter_layers=3,
  243. output_hidden_size=None,
  244. adapter_attn_dim=None,
  245. **kwargs,
  246. ):
  247. super().__init__(**kwargs, pad_token_id=pad_token_id, bos_token_id=bos_token_id, eos_token_id=eos_token_id)
  248. self.hidden_size = hidden_size
  249. self.feat_extract_norm = feat_extract_norm
  250. self.feat_extract_activation = feat_extract_activation
  251. self.conv_dim = list(conv_dim)
  252. self.conv_stride = list(conv_stride)
  253. self.conv_kernel = list(conv_kernel)
  254. self.conv_bias = conv_bias
  255. self.num_conv_pos_embeddings = num_conv_pos_embeddings
  256. self.num_conv_pos_embedding_groups = num_conv_pos_embedding_groups
  257. self.num_feat_extract_layers = len(self.conv_dim)
  258. self.num_hidden_layers = num_hidden_layers
  259. self.intermediate_size = intermediate_size
  260. self.hidden_act = hidden_act
  261. self.num_attention_heads = num_attention_heads
  262. self.hidden_dropout = hidden_dropout
  263. self.attention_dropout = attention_dropout
  264. self.activation_dropout = activation_dropout
  265. self.feat_proj_dropout = feat_proj_dropout
  266. self.final_dropout = final_dropout
  267. self.layerdrop = layerdrop
  268. self.layer_norm_eps = layer_norm_eps
  269. self.initializer_range = initializer_range
  270. self.vocab_size = vocab_size
  271. self.do_stable_layer_norm = do_stable_layer_norm
  272. self.use_weighted_layer_sum = use_weighted_layer_sum
  273. if (
  274. (len(self.conv_stride) != self.num_feat_extract_layers)
  275. or (len(self.conv_kernel) != self.num_feat_extract_layers)
  276. or (len(self.conv_dim) != self.num_feat_extract_layers)
  277. ):
  278. raise ValueError(
  279. "Configuration for convolutional layers is incorrect. It is required that `len(config.conv_dim)` =="
  280. " `len(config.conv_stride)` == `len(config.conv_kernel)`, but is `len(config.conv_dim) ="
  281. f" {len(self.conv_dim)}`, `len(config.conv_stride) = {len(self.conv_stride)}`,"
  282. f" `len(config.conv_kernel) = {len(self.conv_kernel)}`."
  283. )
  284. # fine-tuning config parameters for SpecAugment: https://huggingface.co/papers/1904.08779
  285. self.apply_spec_augment = apply_spec_augment
  286. self.mask_time_prob = mask_time_prob
  287. self.mask_time_length = mask_time_length
  288. self.mask_time_min_masks = mask_time_min_masks
  289. self.mask_feature_prob = mask_feature_prob
  290. self.mask_feature_length = mask_feature_length
  291. self.mask_feature_min_masks = mask_feature_min_masks
  292. # parameters for pretraining with codevector quantized representations
  293. self.num_codevectors_per_group = num_codevectors_per_group
  294. self.num_codevector_groups = num_codevector_groups
  295. self.contrastive_logits_temperature = contrastive_logits_temperature
  296. self.feat_quantizer_dropout = feat_quantizer_dropout
  297. self.num_negatives = num_negatives
  298. self.codevector_dim = codevector_dim
  299. self.proj_codevector_dim = proj_codevector_dim
  300. self.diversity_loss_weight = diversity_loss_weight
  301. # ctc loss
  302. self.ctc_loss_reduction = ctc_loss_reduction
  303. self.ctc_zero_infinity = ctc_zero_infinity
  304. # adapter
  305. self.add_adapter = add_adapter
  306. self.adapter_kernel_size = adapter_kernel_size
  307. self.adapter_stride = adapter_stride
  308. self.num_adapter_layers = num_adapter_layers
  309. self.output_hidden_size = output_hidden_size or hidden_size
  310. self.adapter_attn_dim = adapter_attn_dim
  311. # SequenceClassification-specific parameter. Feel free to ignore for other classes.
  312. self.classifier_proj_size = classifier_proj_size
  313. # XVector-specific parameters. Feel free to ignore for other classes.
  314. self.tdnn_dim = list(tdnn_dim)
  315. self.tdnn_kernel = list(tdnn_kernel)
  316. self.tdnn_dilation = list(tdnn_dilation)
  317. self.xvector_output_dim = xvector_output_dim
  318. @property
  319. def inputs_to_logits_ratio(self):
  320. return functools.reduce(operator.mul, self.conv_stride, 1)
  321. __all__ = ["Wav2Vec2Config"]