configuration_sew.py 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176
  1. # Copyright 2021 ASAPP Inc. 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. """SEW 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="BAAI/seggpt-vit-large")
  21. @strict
  22. class SEWConfig(PreTrainedConfig):
  23. r"""
  24. squeeze_factor (`int`, *optional*, defaults to 2):
  25. Sequence length downsampling factor after the encoder and upsampling factor after the transformer.
  26. feat_proj_dropout (`float`, *optional*, defaults to 0.0):
  27. The dropout probability for output of the feature encoder.
  28. final_dropout (`float`, *optional*, defaults to 0.1):
  29. The dropout probability for the final projection layer of [`SEWForCTC`].
  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 `(64, 128, 128, 128, 128, 256, 256, 256, 256, 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, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1)`):
  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, 1, 3, 1, 3, 1, 3, 1, 2, 1, 2, 1)`):
  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. apply_spec_augment (`bool`, *optional*, defaults to `True`):
  55. Whether to apply *SpecAugment* data augmentation to the outputs of the feature encoder. For reference see
  56. [SpecAugment: A Simple Data Augmentation Method for Automatic Speech
  57. Recognition](https://huggingface.co/papers/1904.08779).
  58. mask_time_prob (`float`, *optional*, defaults to 0.05):
  59. Percentage (between 0 and 1) of all feature vectors along the time axis which will be masked. The masking
  60. procedure generates ''mask_time_prob*len(time_axis)/mask_time_length'' independent masks over the axis. If
  61. reasoning from the probability of each feature vector to be chosen as the start of the vector span to be
  62. masked, *mask_time_prob* should be `prob_vector_start*mask_time_length`. Note that overlap may decrease the
  63. actual percentage of masked vectors. This is only relevant if `apply_spec_augment is True`.
  64. mask_time_length (`int`, *optional*, defaults to 10):
  65. Length of vector span along the time axis.
  66. mask_time_min_masks (`int`, *optional*, defaults to 2),:
  67. The minimum number of masks of length `mask_feature_length` generated along the time axis, each time step,
  68. irrespectively of `mask_feature_prob`. Only relevant if ''mask_time_prob*len(time_axis)/mask_time_length <
  69. mask_time_min_masks''
  70. mask_feature_prob (`float`, *optional*, defaults to 0.0):
  71. Percentage (between 0 and 1) of all feature vectors along the feature axis which will be masked. The
  72. masking procedure generates ''mask_feature_prob*len(feature_axis)/mask_time_length'' independent masks over
  73. the axis. If reasoning from the probability of each feature vector to be chosen as the start of the vector
  74. span to be masked, *mask_feature_prob* should be `prob_vector_start*mask_feature_length`. Note that overlap
  75. may decrease the actual percentage of masked vectors. This is only relevant if `apply_spec_augment is
  76. True`.
  77. mask_feature_length (`int`, *optional*, defaults to 10):
  78. Length of vector span along the feature axis.
  79. mask_feature_min_masks (`int`, *optional*, defaults to 0):
  80. The minimum number of masks of length `mask_feature_length` generated along the feature axis, each time
  81. step, irrespectively of `mask_feature_prob`. Only relevant if
  82. ''mask_feature_prob*len(feature_axis)/mask_feature_length < mask_feature_min_masks''
  83. ctc_zero_infinity (`bool`, *optional*, defaults to `False`):
  84. Whether to zero infinite losses and the associated gradients of `torch.nn.CTCLoss`. Infinite losses mainly
  85. occur when the inputs are too short to be aligned to the targets. Only relevant when training an instance
  86. of [`SEWForCTC`].
  87. use_weighted_layer_sum (`bool`, *optional*, defaults to `False`):
  88. Whether to use a weighted average of layer outputs with learned weights. Only relevant when using an
  89. instance of [`Wav2Vec2ForSequenceClassification`].
  90. classifier_proj_size (`int`, *optional*, defaults to 256):
  91. Dimensionality of the projection before token mean-pooling for classification.
  92. Example:
  93. ```python
  94. >>> from transformers import SEWConfig, SEWModel
  95. >>> # Initializing a SEW asapp/sew-tiny-100k style configuration
  96. >>> configuration = SEWConfig()
  97. >>> # Initializing a model (with random weights) from the asapp/sew-tiny-100k style configuration
  98. >>> model = SEWModel(configuration)
  99. >>> # Accessing the model configuration
  100. >>> configuration = model.config
  101. ```"""
  102. model_type = "sew"
  103. vocab_size: int = 32
  104. hidden_size: int = 768
  105. num_hidden_layers: int = 12
  106. num_attention_heads: int = 12
  107. intermediate_size: int = 3072
  108. squeeze_factor: int = 2
  109. hidden_act: str = "gelu"
  110. hidden_dropout: float | int = 0.1
  111. activation_dropout: float | int = 0.1
  112. attention_dropout: float | int = 0.1
  113. feat_proj_dropout: float | int = 0.0
  114. final_dropout: float | int = 0.1
  115. layerdrop: float | int = 0.1
  116. initializer_range: float = 0.02
  117. layer_norm_eps: float = 1e-5
  118. feat_extract_norm: str = "group"
  119. feat_extract_activation: str = "gelu"
  120. conv_dim: list[int] | tuple[int, ...] = (64, 128, 128, 128, 128, 256, 256, 256, 256, 512, 512, 512, 512)
  121. conv_stride: list[int] | tuple[int, ...] = (5, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1)
  122. conv_kernel: list[int] | tuple[int, ...] = (10, 3, 1, 3, 1, 3, 1, 3, 1, 2, 1, 2, 1)
  123. conv_bias: bool = False
  124. num_conv_pos_embeddings: int = 128
  125. num_conv_pos_embedding_groups: int = 16
  126. apply_spec_augment: bool = True
  127. mask_time_prob: float | int = 0.05
  128. mask_time_length: int = 10
  129. mask_time_min_masks: int = 2
  130. mask_feature_prob: float | int = 0.0
  131. mask_feature_length: int = 10
  132. mask_feature_min_masks: int = 0
  133. ctc_loss_reduction: str = "mean"
  134. ctc_zero_infinity: bool = False
  135. use_weighted_layer_sum: bool = False
  136. classifier_proj_size: int = 256
  137. pad_token_id: int | None = 0
  138. bos_token_id: int | None = 1
  139. eos_token_id: int | list[int] | None = 2
  140. def __post_init__(self, **kwargs):
  141. self.num_feat_extract_layers = len(self.conv_dim)
  142. super().__post_init__(**kwargs)
  143. def validate_architecture(self):
  144. """Part of `@strict`-powered validation. Validates the architecture of the config."""
  145. if (
  146. (len(self.conv_stride) != self.num_feat_extract_layers)
  147. or (len(self.conv_kernel) != self.num_feat_extract_layers)
  148. or (len(self.conv_dim) != self.num_feat_extract_layers)
  149. ):
  150. raise ValueError(
  151. "Configuration for convolutional layers is incorrect. "
  152. "It is required that `len(config.conv_dim)` == `len(config.conv_stride)` == `len(config.conv_kernel)`, "
  153. f"but is `len(config.conv_dim) = {len(self.conv_dim)}`, `len(config.conv_stride) "
  154. f"= {len(self.conv_stride)}`, `len(config.conv_kernel) = {len(self.conv_kernel)}`."
  155. )
  156. @property
  157. def inputs_to_logits_ratio(self):
  158. return functools.reduce(operator.mul, self.conv_stride, 1)
  159. __all__ = ["SEWConfig"]