configuration_hubert.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258
  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. """Hubert 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 HubertConfig(PretrainedConfig):
  22. r"""
  23. This is the configuration class to store the configuration of a [`HubertModel`]. It is used to instantiate an
  24. Hubert 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 Hubert
  26. [facebook/hubert-base-ls960](https://huggingface.co/facebook/hubert-base-ls960) 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 Hubert model. Defines the number of different tokens that can be represented by the
  32. `inputs_ids` passed when calling [`HubertModel`]. Vocabulary size of the model. Defines the different
  33. tokens that can be represented by the *inputs_ids* passed to the forward method of [`HubertModel`].
  34. hidden_size (`int`, *optional*, defaults to 768):
  35. Dimensionality of the encoder layers and the pooler layer.
  36. num_hidden_layers (`int`, *optional*, defaults to 12):
  37. Number of hidden layers in the Transformer encoder.
  38. num_attention_heads (`int`, *optional*, defaults to 12):
  39. Number of attention heads for each attention layer in the Transformer encoder.
  40. intermediate_size (`int`, *optional*, defaults to 3072):
  41. Dimensionality of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder.
  42. hidden_act (`str` or `function`, *optional*, defaults to `"gelu"`):
  43. The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
  44. `"relu"`, `"selu"` and `"gelu_new"` are supported.
  45. hidden_dropout(`float`, *optional*, defaults to 0.1):
  46. The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
  47. activation_dropout (`float`, *optional*, defaults to 0.1):
  48. The dropout ratio for activations inside the fully connected layer.
  49. attention_dropout(`float`, *optional*, defaults to 0.1):
  50. The dropout ratio for the attention probabilities.
  51. final_dropout (`float`, *optional*, defaults to 0.1):
  52. The dropout probability for the final projection layer of [`Wav2Vec2ForCTC`].
  53. layerdrop (`float`, *optional*, defaults to 0.1):
  54. The LayerDrop probability. See the [LayerDrop paper](see https://arxiv.org/abs/1909.11556) for more
  55. details.
  56. initializer_range (`float`, *optional*, defaults to 0.02):
  57. The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
  58. layer_norm_eps (`float`, *optional*, defaults to 1e-12):
  59. The epsilon used by the layer normalization layers.
  60. feat_extract_norm (`str`, *optional*, defaults to `"group"`):
  61. The norm to be applied to 1D convolutional layers in feature encoder. One of `"group"` for group
  62. normalization of only the first 1D convolutional layer or `"layer"` for layer normalization of all 1D
  63. convolutional layers.
  64. feat_proj_dropout (`float`, *optional*, defaults to 0.0):
  65. The dropout probability for output of the feature encoder.
  66. feat_proj_layer_norm (`bool`, *optional*, defaults to `True`):
  67. Whether to apply LayerNorm to the output of the feature encoder.
  68. feat_extract_activation (`str, `optional`, defaults to `"gelu"`):
  69. The non-linear activation function (function or string) in the 1D convolutional layers of the feature
  70. extractor. If string, `"gelu"`, `"relu"`, `"selu"` and `"gelu_new"` are supported.
  71. conv_dim (`Tuple[int]`, *optional*, defaults to `(512, 512, 512, 512, 512, 512, 512)`):
  72. A tuple of integers defining the number of input and output channels of each 1D convolutional layer in the
  73. feature encoder. The length of *conv_dim* defines the number of 1D convolutional layers.
  74. conv_stride (`Tuple[int]`, *optional*, defaults to `(5, 2, 2, 2, 2, 2, 2)`):
  75. A tuple of integers defining the stride of each 1D convolutional layer in the feature encoder. The length
  76. of *conv_stride* defines the number of convolutional layers and has to match the length of *conv_dim*.
  77. conv_kernel (`Tuple[int]`, *optional*, defaults to `(10, 3, 3, 3, 3, 3, 3)`):
  78. A tuple of integers defining the kernel size of each 1D convolutional layer in the feature encoder. The
  79. length of *conv_kernel* defines the number of convolutional layers and has to match the length of
  80. *conv_dim*.
  81. conv_bias (`bool`, *optional*, defaults to `False`):
  82. Whether the 1D convolutional layers have a bias.
  83. num_conv_pos_embeddings (`int`, *optional*, defaults to 128):
  84. Number of convolutional positional embeddings. Defines the kernel size of 1D convolutional positional
  85. embeddings layer.
  86. num_conv_pos_embedding_groups (`int`, *optional*, defaults to 16):
  87. Number of groups of 1D convolutional positional embeddings layer.
  88. do_stable_layer_norm (`bool`, *optional*, defaults to `False`):
  89. Whether do apply *stable* layer norm architecture of the Transformer encoder. `do_stable_layer_norm is
  90. True` corresponds to applying layer norm before the attention layer, whereas `do_stable_layer_norm is
  91. False` corresponds to applying layer norm after the attention layer.
  92. apply_spec_augment (`bool`, *optional*, defaults to `True`):
  93. Whether to apply *SpecAugment* data augmentation to the outputs of the feature encoder. For reference see
  94. [SpecAugment: A Simple Data Augmentation Method for Automatic Speech
  95. Recognition](https://arxiv.org/abs/1904.08779).
  96. mask_time_prob (`float`, *optional*, defaults to 0.05):
  97. Percentage (between 0 and 1) of all feature vectors along the time axis which will be masked. The masking
  98. procecure generates ''mask_time_prob*len(time_axis)/mask_time_length'' independent masks over the axis. If
  99. reasoning from the propability of each feature vector to be chosen as the start of the vector span to be
  100. masked, *mask_time_prob* should be `prob_vector_start*mask_time_length`. Note that overlap may decrease the
  101. actual percentage of masked vectors. This is only relevant if `apply_spec_augment is True`.
  102. mask_time_length (`int`, *optional*, defaults to 10):
  103. Length of vector span along the time axis.
  104. mask_time_min_masks (`int`, *optional*, defaults to 2),:
  105. The minimum number of masks of length `mask_feature_length` generated along the time axis, each time step,
  106. irrespectively of `mask_feature_prob`. Only relevant if ''mask_time_prob*len(time_axis)/mask_time_length <
  107. mask_time_min_masks''
  108. mask_feature_prob (`float`, *optional*, defaults to 0.0):
  109. Percentage (between 0 and 1) of all feature vectors along the feature axis which will be masked. The
  110. masking procecure generates ''mask_feature_prob*len(feature_axis)/mask_time_length'' independent masks over
  111. the axis. If reasoning from the propability of each feature vector to be chosen as the start of the vector
  112. span to be masked, *mask_feature_prob* should be `prob_vector_start*mask_feature_length`. Note that overlap
  113. may decrease the actual percentage of masked vectors. This is only relevant if `apply_spec_augment is
  114. True`.
  115. mask_feature_length (`int`, *optional*, defaults to 10):
  116. Length of vector span along the feature axis.
  117. mask_feature_min_masks (`int`, *optional*, defaults to 0),:
  118. The minimum number of masks of length `mask_feature_length` generated along the feature axis, each time
  119. step, irrespectively of `mask_feature_prob`. Only relevant if
  120. ''mask_feature_prob*len(feature_axis)/mask_feature_length < mask_feature_min_masks''
  121. ctc_loss_reduction (`str`, *optional*, defaults to `"sum"`):
  122. Specifies the reduction to apply to the output of `torch.nn.CTCLoss`. Only relevant when training an
  123. instance of [`HubertForCTC`].
  124. ctc_zero_infinity (`bool`, *optional*, defaults to `False`):
  125. Whether to zero infinite losses and the associated gradients of `torch.nn.CTCLoss`. Infinite losses mainly
  126. occur when the inputs are too short to be aligned to the targets. Only relevant when training an instance
  127. of [`HubertForCTC`].
  128. use_weighted_layer_sum (`bool`, *optional*, defaults to `False`):
  129. Whether to use a weighted average of layer outputs with learned weights. Only relevant when using an
  130. instance of [`HubertForSequenceClassification`].
  131. classifier_proj_size (`int`, *optional*, defaults to 256):
  132. Dimensionality of the projection before token mean-pooling for classification.
  133. Example:
  134. ```python
  135. >>> from transformers import HubertModel, HubertConfig
  136. >>> # Initializing a Hubert facebook/hubert-base-ls960 style configuration
  137. >>> configuration = HubertConfig()
  138. >>> # Initializing a model from the facebook/hubert-base-ls960 style configuration
  139. >>> model = HubertModel(configuration)
  140. >>> # Accessing the model configuration
  141. >>> configuration = model.config
  142. ```"""
  143. model_type = "hubert"
  144. def __init__(
  145. self,
  146. vocab_size=32,
  147. hidden_size=768,
  148. num_hidden_layers=12,
  149. num_attention_heads=12,
  150. intermediate_size=3072,
  151. hidden_act="gelu",
  152. hidden_dropout=0.1,
  153. activation_dropout=0.1,
  154. attention_dropout=0.1,
  155. feat_proj_layer_norm=True,
  156. feat_proj_dropout=0.0,
  157. final_dropout=0.1,
  158. layerdrop=0.1,
  159. initializer_range=0.02,
  160. layer_norm_eps=1e-5,
  161. feat_extract_norm="group",
  162. feat_extract_activation="gelu",
  163. conv_dim=(512, 512, 512, 512, 512, 512, 512),
  164. conv_stride=(5, 2, 2, 2, 2, 2, 2),
  165. conv_kernel=(10, 3, 3, 3, 3, 2, 2),
  166. conv_bias=False,
  167. num_conv_pos_embeddings=128,
  168. num_conv_pos_embedding_groups=16,
  169. do_stable_layer_norm=False,
  170. apply_spec_augment=True,
  171. mask_time_prob=0.05,
  172. mask_time_length=10,
  173. mask_time_min_masks=2,
  174. mask_feature_prob=0.0,
  175. mask_feature_length=10,
  176. mask_feature_min_masks=0,
  177. ctc_loss_reduction="sum",
  178. ctc_zero_infinity=False,
  179. use_weighted_layer_sum=False,
  180. classifier_proj_size=256,
  181. pad_token_id=0,
  182. bos_token_id=1,
  183. eos_token_id=2,
  184. **kwargs,
  185. ):
  186. super().__init__(**kwargs, pad_token_id=pad_token_id, bos_token_id=bos_token_id, eos_token_id=eos_token_id)
  187. self.hidden_size = hidden_size
  188. self.feat_extract_norm = feat_extract_norm
  189. self.feat_extract_activation = feat_extract_activation
  190. self.conv_dim = list(conv_dim)
  191. self.conv_stride = list(conv_stride)
  192. self.conv_kernel = list(conv_kernel)
  193. self.conv_bias = conv_bias
  194. self.num_conv_pos_embeddings = num_conv_pos_embeddings
  195. self.num_conv_pos_embedding_groups = num_conv_pos_embedding_groups
  196. self.num_feat_extract_layers = len(self.conv_dim)
  197. self.num_hidden_layers = num_hidden_layers
  198. self.intermediate_size = intermediate_size
  199. self.hidden_act = hidden_act
  200. self.num_attention_heads = num_attention_heads
  201. self.hidden_dropout = hidden_dropout
  202. self.attention_dropout = attention_dropout
  203. self.activation_dropout = activation_dropout
  204. self.feat_proj_layer_norm = feat_proj_layer_norm
  205. self.feat_proj_dropout = feat_proj_dropout
  206. self.final_dropout = final_dropout
  207. self.layerdrop = layerdrop
  208. self.layer_norm_eps = layer_norm_eps
  209. self.initializer_range = initializer_range
  210. self.vocab_size = vocab_size
  211. self.do_stable_layer_norm = do_stable_layer_norm
  212. self.use_weighted_layer_sum = use_weighted_layer_sum
  213. self.classifier_proj_size = classifier_proj_size
  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. # fine-tuning config parameters for SpecAugment: https://arxiv.org/abs/1904.08779
  226. self.apply_spec_augment = apply_spec_augment
  227. self.mask_time_prob = mask_time_prob
  228. self.mask_time_length = mask_time_length
  229. self.mask_time_min_masks = mask_time_min_masks
  230. self.mask_feature_prob = mask_feature_prob
  231. self.mask_feature_length = mask_feature_length
  232. self.mask_feature_min_masks = mask_feature_min_masks
  233. # ctc loss
  234. self.ctc_loss_reduction = ctc_loss_reduction
  235. self.ctc_zero_infinity = ctc_zero_infinity
  236. @property
  237. def inputs_to_logits_ratio(self):
  238. return functools.reduce(operator.mul, self.conv_stride, 1)