configuration_hubert.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265
  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://huggingface.co/papers/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. conv_pos_batch_norm (`bool`, *optional*, defaults to `False`):
  89. Whether to use batch norm instead of weight norm in conv_pos
  90. do_stable_layer_norm (`bool`, *optional*, defaults to `False`):
  91. Whether do apply *stable* layer norm architecture of the Transformer encoder. `do_stable_layer_norm is
  92. True` corresponds to applying layer norm before the attention layer, whereas `do_stable_layer_norm is
  93. False` corresponds to applying layer norm after the attention layer.
  94. apply_spec_augment (`bool`, *optional*, defaults to `True`):
  95. Whether to apply *SpecAugment* data augmentation to the outputs of the feature encoder. For reference see
  96. [SpecAugment: A Simple Data Augmentation Method for Automatic Speech
  97. Recognition](https://huggingface.co/papers/1904.08779).
  98. mask_time_prob (`float`, *optional*, defaults to 0.05):
  99. Percentage (between 0 and 1) of all feature vectors along the time axis which will be masked. The masking
  100. procedure generates ''mask_time_prob*len(time_axis)/mask_time_length'' independent masks over the axis. If
  101. reasoning from the probability of each feature vector to be chosen as the start of the vector span to be
  102. masked, *mask_time_prob* should be `prob_vector_start*mask_time_length`. Note that overlap may decrease the
  103. actual percentage of masked vectors. This is only relevant if `apply_spec_augment is True`.
  104. mask_time_length (`int`, *optional*, defaults to 10):
  105. Length of vector span along the time axis.
  106. mask_time_min_masks (`int`, *optional*, defaults to 2),:
  107. The minimum number of masks of length `mask_feature_length` generated along the time axis, each time step,
  108. irrespectively of `mask_feature_prob`. Only relevant if ''mask_time_prob*len(time_axis)/mask_time_length <
  109. mask_time_min_masks''
  110. mask_feature_prob (`float`, *optional*, defaults to 0.0):
  111. Percentage (between 0 and 1) of all feature vectors along the feature axis which will be masked. The
  112. masking procedure generates ''mask_feature_prob*len(feature_axis)/mask_time_length'' independent masks over
  113. the axis. If reasoning from the probability of each feature vector to be chosen as the start of the vector
  114. span to be masked, *mask_feature_prob* should be `prob_vector_start*mask_feature_length`. Note that overlap
  115. may decrease the actual percentage of masked vectors. This is only relevant if `apply_spec_augment is
  116. True`.
  117. mask_feature_length (`int`, *optional*, defaults to 10):
  118. Length of vector span along the feature axis.
  119. mask_feature_min_masks (`int`, *optional*, defaults to 0),:
  120. The minimum number of masks of length `mask_feature_length` generated along the feature axis, each time
  121. step, irrespectively of `mask_feature_prob`. Only relevant if
  122. ''mask_feature_prob*len(feature_axis)/mask_feature_length < mask_feature_min_masks''
  123. ctc_loss_reduction (`str`, *optional*, defaults to `"sum"`):
  124. Specifies the reduction to apply to the output of `torch.nn.CTCLoss`. Only relevant when training an
  125. instance of [`HubertForCTC`].
  126. ctc_zero_infinity (`bool`, *optional*, defaults to `False`):
  127. Whether to zero infinite losses and the associated gradients of `torch.nn.CTCLoss`. Infinite losses mainly
  128. occur when the inputs are too short to be aligned to the targets. Only relevant when training an instance
  129. of [`HubertForCTC`].
  130. use_weighted_layer_sum (`bool`, *optional*, defaults to `False`):
  131. Whether to use a weighted average of layer outputs with learned weights. Only relevant when using an
  132. instance of [`HubertForSequenceClassification`].
  133. classifier_proj_size (`int`, *optional*, defaults to 256):
  134. Dimensionality of the projection before token mean-pooling for classification.
  135. Example:
  136. ```python
  137. >>> from transformers import HubertModel, HubertConfig
  138. >>> # Initializing a Hubert facebook/hubert-base-ls960 style configuration
  139. >>> configuration = HubertConfig()
  140. >>> # Initializing a model from the facebook/hubert-base-ls960 style configuration
  141. >>> model = HubertModel(configuration)
  142. >>> # Accessing the model configuration
  143. >>> configuration = model.config
  144. ```"""
  145. model_type = "hubert"
  146. def __init__(
  147. self,
  148. vocab_size=32,
  149. hidden_size=768,
  150. num_hidden_layers=12,
  151. num_attention_heads=12,
  152. intermediate_size=3072,
  153. hidden_act="gelu",
  154. hidden_dropout=0.1,
  155. activation_dropout=0.1,
  156. attention_dropout=0.1,
  157. feat_proj_layer_norm=True,
  158. feat_proj_dropout=0.0,
  159. final_dropout=0.1,
  160. layerdrop=0.1,
  161. initializer_range=0.02,
  162. layer_norm_eps=1e-5,
  163. feat_extract_norm="group",
  164. feat_extract_activation="gelu",
  165. conv_dim=(512, 512, 512, 512, 512, 512, 512),
  166. conv_stride=(5, 2, 2, 2, 2, 2, 2),
  167. conv_kernel=(10, 3, 3, 3, 3, 2, 2),
  168. conv_bias=False,
  169. num_conv_pos_embeddings=128,
  170. num_conv_pos_embedding_groups=16,
  171. conv_pos_batch_norm=False,
  172. do_stable_layer_norm=False,
  173. apply_spec_augment=True,
  174. mask_time_prob=0.05,
  175. mask_time_length=10,
  176. mask_time_min_masks=2,
  177. mask_feature_prob=0.0,
  178. mask_feature_length=10,
  179. mask_feature_min_masks=0,
  180. ctc_loss_reduction="sum",
  181. ctc_zero_infinity=False,
  182. use_weighted_layer_sum=False,
  183. classifier_proj_size=256,
  184. pad_token_id=0,
  185. bos_token_id=1,
  186. eos_token_id=2,
  187. **kwargs,
  188. ):
  189. super().__init__(**kwargs, pad_token_id=pad_token_id, bos_token_id=bos_token_id, eos_token_id=eos_token_id)
  190. self.hidden_size = hidden_size
  191. self.feat_extract_norm = feat_extract_norm
  192. self.feat_extract_activation = feat_extract_activation
  193. self.conv_dim = list(conv_dim)
  194. self.conv_stride = list(conv_stride)
  195. self.conv_kernel = list(conv_kernel)
  196. self.conv_bias = conv_bias
  197. self.num_conv_pos_embeddings = num_conv_pos_embeddings
  198. self.num_conv_pos_embedding_groups = num_conv_pos_embedding_groups
  199. self.conv_pos_batch_norm = conv_pos_batch_norm
  200. self.num_feat_extract_layers = len(self.conv_dim)
  201. self.num_hidden_layers = num_hidden_layers
  202. self.intermediate_size = intermediate_size
  203. self.hidden_act = hidden_act
  204. self.num_attention_heads = num_attention_heads
  205. self.hidden_dropout = hidden_dropout
  206. self.attention_dropout = attention_dropout
  207. self.activation_dropout = activation_dropout
  208. self.feat_proj_layer_norm = feat_proj_layer_norm
  209. self.feat_proj_dropout = feat_proj_dropout
  210. self.final_dropout = final_dropout
  211. self.layerdrop = layerdrop
  212. self.layer_norm_eps = layer_norm_eps
  213. self.initializer_range = initializer_range
  214. self.vocab_size = vocab_size
  215. self.do_stable_layer_norm = do_stable_layer_norm
  216. self.use_weighted_layer_sum = use_weighted_layer_sum
  217. self.classifier_proj_size = classifier_proj_size
  218. if (
  219. (len(self.conv_stride) != self.num_feat_extract_layers)
  220. or (len(self.conv_kernel) != self.num_feat_extract_layers)
  221. or (len(self.conv_dim) != self.num_feat_extract_layers)
  222. ):
  223. raise ValueError(
  224. "Configuration for convolutional layers is incorrect. It is required that `len(config.conv_dim)` =="
  225. " `len(config.conv_stride)` == `len(config.conv_kernel)`, but is `len(config.conv_dim) ="
  226. f" {len(self.conv_dim)}`, `len(config.conv_stride) = {len(self.conv_stride)}`,"
  227. f" `len(config.conv_kernel) = {len(self.conv_kernel)}`."
  228. )
  229. # fine-tuning config parameters for SpecAugment: https://huggingface.co/papers/1904.08779
  230. self.apply_spec_augment = apply_spec_augment
  231. self.mask_time_prob = mask_time_prob
  232. self.mask_time_length = mask_time_length
  233. self.mask_time_min_masks = mask_time_min_masks
  234. self.mask_feature_prob = mask_feature_prob
  235. self.mask_feature_length = mask_feature_length
  236. self.mask_feature_min_masks = mask_feature_min_masks
  237. # ctc loss
  238. self.ctc_loss_reduction = ctc_loss_reduction
  239. self.ctc_zero_infinity = ctc_zero_infinity
  240. @property
  241. def inputs_to_logits_ratio(self):
  242. return functools.reduce(operator.mul, self.conv_stride, 1)
  243. __all__ = ["HubertConfig"]