configuration_sew.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256
  1. # coding=utf-8
  2. # Copyright 2021 ASAPP Inc. 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. """SEW 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 SEWConfig(PretrainedConfig):
  22. r"""
  23. This is the configuration class to store the configuration of a [`SEWModel`]. It is used to instantiate a SEW model
  24. according to the specified arguments, defining the model architecture. Instantiating a configuration with the
  25. defaults will yield a similar configuration to that of the SEW
  26. [asapp/sew-tiny-100k](https://huggingface.co/asapp/sew-tiny-100k) 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 SEW model. Defines the number of different tokens that can be represented by the
  32. `inputs_ids` passed when calling [`SEW`].
  33. hidden_size (`int`, *optional*, defaults to 768):
  34. Dimensionality of the encoder layers and the pooler layer.
  35. num_hidden_layers (`int`, *optional*, defaults to 12):
  36. Number of hidden layers in the Transformer encoder.
  37. num_attention_heads (`int`, *optional*, defaults to 12):
  38. Number of attention heads for each attention layer in the Transformer encoder.
  39. intermediate_size (`int`, *optional*, defaults to 3072):
  40. Dimensionality of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder.
  41. squeeze_factor (`int`, *optional*, defaults to 2):
  42. Sequence length downsampling factor after the encoder and upsampling factor after the transformer.
  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 [`SEWForCTC`].
  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. conv_dim (`tuple[int]` or `list[int]`, *optional*, defaults to `(64, 128, 128, 128, 128, 256, 256, 256, 256, 512, 512, 512, 512)`):
  71. A tuple of integers defining the number of input and output channels of each 1D convolutional layer in the
  72. feature encoder. The length of *conv_dim* defines the number of 1D convolutional layers.
  73. conv_stride (`tuple[int]` or `list[int]`, *optional*, defaults to `(5, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1)`):
  74. A tuple of integers defining the stride of each 1D convolutional layer in the feature encoder. The length
  75. of *conv_stride* defines the number of convolutional layers and has to match the length of *conv_dim*.
  76. conv_kernel (`tuple[int]` or `list[int]`, *optional*, defaults to `(10, 3, 1, 3, 1, 3, 1, 3, 1, 2, 1, 2, 1)`):
  77. A tuple of integers defining the kernel size of each 1D convolutional layer in the feature encoder. The
  78. length of *conv_kernel* defines the number of convolutional layers and has to match the length of
  79. *conv_dim*.
  80. conv_bias (`bool`, *optional*, defaults to `False`):
  81. Whether the 1D convolutional layers have a bias.
  82. num_conv_pos_embeddings (`int`, *optional*, defaults to 128):
  83. Number of convolutional positional embeddings. Defines the kernel size of 1D convolutional positional
  84. embeddings layer.
  85. num_conv_pos_embedding_groups (`int`, *optional*, defaults to 16):
  86. Number of groups of 1D convolutional positional embeddings layer.
  87. apply_spec_augment (`bool`, *optional*, defaults to `True`):
  88. Whether to apply *SpecAugment* data augmentation to the outputs of the feature encoder. For reference see
  89. [SpecAugment: A Simple Data Augmentation Method for Automatic Speech
  90. Recognition](https://huggingface.co/papers/1904.08779).
  91. mask_time_prob (`float`, *optional*, defaults to 0.05):
  92. Percentage (between 0 and 1) of all feature vectors along the time axis which will be masked. The masking
  93. procedure generates ''mask_time_prob*len(time_axis)/mask_time_length'' independent masks over the axis. If
  94. reasoning from the probability of each feature vector to be chosen as the start of the vector span to be
  95. masked, *mask_time_prob* should be `prob_vector_start*mask_time_length`. Note that overlap may decrease the
  96. actual percentage of masked vectors. This is only relevant if `apply_spec_augment is True`.
  97. mask_time_length (`int`, *optional*, defaults to 10):
  98. Length of vector span along the time axis.
  99. mask_time_min_masks (`int`, *optional*, defaults to 2),:
  100. The minimum number of masks of length `mask_feature_length` generated along the time axis, each time step,
  101. irrespectively of `mask_feature_prob`. Only relevant if ''mask_time_prob*len(time_axis)/mask_time_length <
  102. mask_time_min_masks''
  103. mask_feature_prob (`float`, *optional*, defaults to 0.0):
  104. Percentage (between 0 and 1) of all feature vectors along the feature axis which will be masked. The
  105. masking procedure generates ''mask_feature_prob*len(feature_axis)/mask_time_length'' independent masks over
  106. the axis. If reasoning from the probability of each feature vector to be chosen as the start of the vector
  107. span to be masked, *mask_feature_prob* should be `prob_vector_start*mask_feature_length`. Note that overlap
  108. may decrease the actual percentage of masked vectors. This is only relevant if `apply_spec_augment is
  109. True`.
  110. mask_feature_length (`int`, *optional*, defaults to 10):
  111. Length of vector span along the feature axis.
  112. mask_feature_min_masks (`int`, *optional*, defaults to 0),:
  113. The minimum number of masks of length `mask_feature_length` generated along the feature axis, each time
  114. step, irrespectively of `mask_feature_prob`. Only relevant if
  115. ''mask_feature_prob*len(feature_axis)/mask_feature_length < mask_feature_min_masks''
  116. ctc_loss_reduction (`str`, *optional*, defaults to `"sum"`):
  117. Specifies the reduction to apply to the output of `torch.nn.CTCLoss`. Only relevant when training an
  118. instance of [`SEWForCTC`].
  119. ctc_zero_infinity (`bool`, *optional*, defaults to `False`):
  120. Whether to zero infinite losses and the associated gradients of `torch.nn.CTCLoss`. Infinite losses mainly
  121. occur when the inputs are too short to be aligned to the targets. Only relevant when training an instance
  122. of [`SEWForCTC`].
  123. use_weighted_layer_sum (`bool`, *optional*, defaults to `False`):
  124. Whether to use a weighted average of layer outputs with learned weights. Only relevant when using an
  125. instance of [`Wav2Vec2ForSequenceClassification`].
  126. classifier_proj_size (`int`, *optional*, defaults to 256):
  127. Dimensionality of the projection before token mean-pooling for classification.
  128. Example:
  129. ```python
  130. >>> from transformers import SEWConfig, SEWModel
  131. >>> # Initializing a SEW asapp/sew-tiny-100k style configuration
  132. >>> configuration = SEWConfig()
  133. >>> # Initializing a model (with random weights) from the asapp/sew-tiny-100k style configuration
  134. >>> model = SEWModel(configuration)
  135. >>> # Accessing the model configuration
  136. >>> configuration = model.config
  137. ```"""
  138. model_type = "sew"
  139. def __init__(
  140. self,
  141. vocab_size=32,
  142. hidden_size=768,
  143. num_hidden_layers=12,
  144. num_attention_heads=12,
  145. intermediate_size=3072,
  146. squeeze_factor=2,
  147. hidden_act="gelu",
  148. hidden_dropout=0.1,
  149. activation_dropout=0.1,
  150. attention_dropout=0.1,
  151. feat_proj_dropout=0.0,
  152. final_dropout=0.1,
  153. layerdrop=0.1,
  154. initializer_range=0.02,
  155. layer_norm_eps=1e-5,
  156. feat_extract_norm="group",
  157. feat_extract_activation="gelu",
  158. conv_dim=(64, 128, 128, 128, 128, 256, 256, 256, 256, 512, 512, 512, 512),
  159. conv_stride=(5, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1),
  160. conv_kernel=(10, 3, 1, 3, 1, 3, 1, 3, 1, 2, 1, 2, 1),
  161. conv_bias=False,
  162. num_conv_pos_embeddings=128,
  163. num_conv_pos_embedding_groups=16,
  164. apply_spec_augment=True,
  165. mask_time_prob=0.05,
  166. mask_time_length=10,
  167. mask_time_min_masks=2,
  168. mask_feature_prob=0.0,
  169. mask_feature_length=10,
  170. mask_feature_min_masks=0,
  171. ctc_loss_reduction="mean",
  172. ctc_zero_infinity=False,
  173. use_weighted_layer_sum=False,
  174. classifier_proj_size=256,
  175. pad_token_id=0,
  176. bos_token_id=1,
  177. eos_token_id=2,
  178. **kwargs,
  179. ):
  180. super().__init__(**kwargs, pad_token_id=pad_token_id, bos_token_id=bos_token_id, eos_token_id=eos_token_id)
  181. self.hidden_size = hidden_size
  182. self.feat_extract_norm = feat_extract_norm
  183. self.feat_extract_activation = feat_extract_activation
  184. self.conv_dim = list(conv_dim)
  185. self.conv_stride = list(conv_stride)
  186. self.conv_kernel = list(conv_kernel)
  187. self.conv_bias = conv_bias
  188. self.num_conv_pos_embeddings = num_conv_pos_embeddings
  189. self.num_conv_pos_embedding_groups = num_conv_pos_embedding_groups
  190. self.num_feat_extract_layers = len(self.conv_dim)
  191. self.num_hidden_layers = num_hidden_layers
  192. self.intermediate_size = intermediate_size
  193. self.squeeze_factor = squeeze_factor
  194. self.hidden_act = hidden_act
  195. self.num_attention_heads = num_attention_heads
  196. self.hidden_dropout = hidden_dropout
  197. self.attention_dropout = attention_dropout
  198. self.activation_dropout = activation_dropout
  199. self.feat_proj_dropout = feat_proj_dropout
  200. self.final_dropout = final_dropout
  201. self.layerdrop = layerdrop
  202. self.layer_norm_eps = layer_norm_eps
  203. self.initializer_range = initializer_range
  204. self.vocab_size = vocab_size
  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. "
  212. "It is required that `len(config.conv_dim)` == `len(config.conv_stride)` == `len(config.conv_kernel)`, "
  213. f"but is `len(config.conv_dim) = {len(self.conv_dim)}`, `len(config.conv_stride) "
  214. f"= {len(self.conv_stride)}`, `len(config.conv_kernel) = {len(self.conv_kernel)}`."
  215. )
  216. # fine-tuning config parameters for SpecAugment: https://huggingface.co/papers/1904.08779
  217. self.apply_spec_augment = apply_spec_augment
  218. self.mask_time_prob = mask_time_prob
  219. self.mask_time_length = mask_time_length
  220. self.mask_time_min_masks = mask_time_min_masks
  221. self.mask_feature_prob = mask_feature_prob
  222. self.mask_feature_length = mask_feature_length
  223. self.mask_feature_min_masks = mask_feature_min_masks
  224. # ctc loss
  225. self.ctc_loss_reduction = ctc_loss_reduction
  226. self.ctc_zero_infinity = ctc_zero_infinity
  227. # sequence classification
  228. self.use_weighted_layer_sum = use_weighted_layer_sum
  229. self.classifier_proj_size = classifier_proj_size
  230. @property
  231. def inputs_to_logits_ratio(self):
  232. return functools.reduce(operator.mul, self.conv_stride, 1)
  233. __all__ = ["SEWConfig"]