Aluode/PerceptionLabPortable
0
1# coding=utf-82# Copyright 2022 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 at7#8# http://www.apache.org/licenses/LICENSE-2.09#10# Unless required by applicable law or agreed to in writing, software11# 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 and14# limitations under the License.15"""Data2VecText configuration"""16 17import math18 19from ...configuration_utils import PretrainedConfig20from ...utils import logging21 22 23logger = logging.get_logger(__name__)24 25 26class Data2VecAudioConfig(PretrainedConfig):27 r"""28 This is the configuration class to store the configuration of a [`Data2VecAudioModel`]. It is used to instantiate29 an Data2VecAudio model according to the specified arguments, defining the model architecture. Instantiating a30 configuration with the defaults will yield a similar configuration to that of the Data2VecAudio31 [facebook/data2vec-audio-base-960h](https://huggingface.co/facebook/data2vec-audio-base-960h) architecture.32 33 Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the34 documentation from [`PretrainedConfig`] for more information.35 36 37 Args:38 vocab_size (`int`, *optional*, defaults to 32):39 Vocabulary size of the Data2VecAudio model. Defines the number of different tokens that can be represented40 by the `inputs_ids` passed when calling [`Data2VecAudioModel`] or [`TFData2VecAudioModel`]. Vocabulary size41 of the model. Defines the different tokens that can be represented by the *inputs_ids* passed to the42 forward method of [`Data2VecAudioModel`].43 hidden_size (`int`, *optional*, defaults to 768):44 Dimensionality of the encoder layers and the pooler layer.45 num_hidden_layers (`int`, *optional*, defaults to 12):46 Number of hidden layers in the Transformer encoder.47 num_attention_heads (`int`, *optional*, defaults to 12):48 Number of attention heads for each attention layer in the Transformer encoder.49 intermediate_size (`int`, *optional*, defaults to 3072):50 Dimensionality of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder.51 hidden_act (`str` or `function`, *optional*, defaults to `"gelu"`):52 The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,53 `"relu"`, `"selu"` and `"gelu_new"` are supported.54 hidden_dropout (`float`, *optional*, defaults to 0.1):55 The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.56 activation_dropout (`float`, *optional*, defaults to 0.1):57 The dropout ratio for activations inside the fully connected layer.58 attention_dropout (`float`, *optional*, defaults to 0.1):59 The dropout ratio for the attention probabilities.60 final_dropout (`float`, *optional*, defaults to 0.1):61 The dropout probability for the final projection layer of [`Data2VecAudioForCTC`].62 layerdrop (`float`, *optional*, defaults to 0.1):63 The LayerDrop probability. See the [LayerDrop paper](see https://huggingface.co/papers/1909.11556) for more64 details.65 initializer_range (`float`, *optional*, defaults to 0.02):66 The standard deviation of the truncated_normal_initializer for initializing all weight matrices.67 layer_norm_eps (`float`, *optional*, defaults to 1e-12):68 The epsilon used by the layer normalization layers.69 feat_proj_dropout (`float`, *optional*, defaults to 0.0):70 The dropout probability for output of the feature encoder.71 feat_extract_activation (`str, `optional`, defaults to `"gelu"`):72 The non-linear activation function (function or string) in the 1D convolutional layers of the feature73 extractor. If string, `"gelu"`, `"relu"`, `"selu"` and `"gelu_new"` are supported.74 conv_dim (`tuple[int]` or `list[int]`, *optional*, defaults to `(512, 512, 512, 512, 512, 512, 512)`):75 A tuple of integers defining the number of input and output channels of each 1D convolutional layer in the76 feature encoder. The length of *conv_dim* defines the number of 1D convolutional layers.77 conv_stride (`tuple[int]` or `list[int]`, *optional*, defaults to `(5, 2, 2, 2, 2, 2, 2)`):78 A tuple of integers defining the stride of each 1D convolutional layer in the feature encoder. The length79 of *conv_stride* defines the number of convolutional layers and has to match the length of *conv_dim*.80 conv_kernel (`tuple[int]` or `list[int]`, *optional*, defaults to `(10, 3, 3, 3, 3, 3, 3)`):81 A tuple of integers defining the kernel size of each 1D convolutional layer in the feature encoder. The82 length of *conv_kernel* defines the number of convolutional layers and has to match the length of83 *conv_dim*.84 conv_bias (`bool`, *optional*, defaults to `False`):85 Whether the 1D convolutional layers have a bias.86 num_conv_pos_embeddings (`int`, *optional*, defaults to 128):87 Number of convolutional positional embeddings. Defines the kernel size of 1D convolutional positional88 embeddings layer.89 num_conv_pos_embedding_groups (`int`, *optional*, defaults to 16):90 Number of groups of 1D convolutional positional embeddings layer.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 masking93 procedure generates ''mask_time_prob*len(time_axis)/mask_time_length'' independent masks over the axis. If94 reasoning from the probability of each feature vector to be chosen as the start of the vector span to be95 masked, *mask_time_prob* should be `prob_vector_start*mask_time_length`. Note that overlap may decrease the96 mask_time_length (`int`, *optional*, defaults to 10):97 Length of vector span along the time axis.98 mask_time_min_masks (`int`, *optional*, defaults to 2),:99 The minimum number of masks of length `mask_feature_length` generated along the time axis, each time step,100 irrespectively of `mask_feature_prob`. Only relevant if ''mask_time_prob*len(time_axis)/mask_time_length <101 mask_time_min_masks''102 mask_feature_prob (`float`, *optional*, defaults to 0.0):103 Percentage (between 0 and 1) of all feature vectors along the feature axis which will be masked. The104 masking procedure generates ''mask_feature_prob*len(feature_axis)/mask_time_length'' independent masks over105 the axis. If reasoning from the probability of each feature vector to be chosen as the start of the vector106 span to be masked, *mask_feature_prob* should be `prob_vector_start*mask_feature_length`. Note that overlap107 may decrease the actual percentage of masked vectors. This is only relevant if `apply_spec_augment is108 True`.109 mask_feature_length (`int`, *optional*, defaults to 10):110 Length of vector span along the feature axis.111 mask_feature_min_masks (`int`, *optional*, defaults to 0),:112 The minimum number of masks of length `mask_feature_length` generated along the feature axis, each time113 step, irrespectively of `mask_feature_prob`. Only relevant if114 ''mask_feature_prob*len(feature_axis)/mask_feature_length < mask_feature_min_masks''115 ctc_loss_reduction (`str`, *optional*, defaults to `"sum"`):116 Specifies the reduction to apply to the output of `torch.nn.CTCLoss`. Only relevant when training an117 instance of [`Data2VecAudioForCTC`].118 ctc_zero_infinity (`bool`, *optional*, defaults to `False`):119 Whether to zero infinite losses and the associated gradients of `torch.nn.CTCLoss`. Infinite losses mainly120 occur when the inputs are too short to be aligned to the targets. Only relevant when training an instance121 of [`Data2VecAudioForCTC`].122 use_weighted_layer_sum (`bool`, *optional*, defaults to `False`):123 Whether to use a weighted average of layer outputs with learned weights. Only relevant when using an124 instance of [`Data2VecAudioForSequenceClassification`].125 classifier_proj_size (`int`, *optional*, defaults to 256):126 Dimensionality of the projection before token mean-pooling for classification.127 tdnn_dim (`tuple[int]` or `list[int]`, *optional*, defaults to `(512, 512, 512, 512, 1500)`):128 A tuple of integers defining the number of output channels of each 1D convolutional layer in the *TDNN*129 module of the *XVector* model. The length of *tdnn_dim* defines the number of *TDNN* layers.130 tdnn_kernel (`tuple[int]` or `list[int]`, *optional*, defaults to `(5, 3, 3, 1, 1)`):131 A tuple of integers defining the kernel size of each 1D convolutional layer in the *TDNN* module of the132 *XVector* model. The length of *tdnn_kernel* has to match the length of *tdnn_dim*.133 tdnn_dilation (`tuple[int]` or `list[int]`, *optional*, defaults to `(1, 2, 3, 1, 1)`):134 A tuple of integers defining the dilation factor of each 1D convolutional layer in *TDNN* module of the135 *XVector* model. The length of *tdnn_dilation* has to match the length of *tdnn_dim*.136 xvector_output_dim (`int`, *optional*, defaults to 512):137 Dimensionality of the *XVector* embedding vectors.138 add_adapter (`bool`, *optional*, defaults to `False`):139 Whether a convolutional network should be stacked on top of the Data2VecAudio Encoder. Can be very useful140 for warm-starting Data2VecAudio for SpeechEncoderDecoder models.141 adapter_kernel_size (`int`, *optional*, defaults to 3):142 Kernel size of the convolutional layers in the adapter network. Only relevant if `add_adapter is True`.143 adapter_stride (`int`, *optional*, defaults to 2):144 Stride of the convolutional layers in the adapter network. Only relevant if `add_adapter is True`.145 num_adapter_layers (`int`, *optional*, defaults to 3):146 Number of convolutional layers that should be used in the adapter network. Only relevant if `add_adapter is147 True`.148 output_hidden_size (`int`, *optional*):149 Dimensionality of the encoder output layer. If not defined, this defaults to *hidden-size*. Only relevant150 if `add_adapter is True`.151 152 Example:153 154 ```python155 >>> from transformers import Data2VecAudioConfig, Data2VecAudioModel156 157 >>> # Initializing a Data2VecAudio facebook/data2vec-audio-base-960h style configuration158 >>> configuration = Data2VecAudioConfig()159 160 >>> # Initializing a model (with random weights) from the facebook/data2vec-audio-base-960h style configuration161 >>> model = Data2VecAudioModel(configuration)162 163 >>> # Accessing the model configuration164 >>> configuration = model.config165 ```"""166 167 model_type = "data2vec-audio"168 169 def __init__(170 self,171 vocab_size=32,172 hidden_size=768,173 num_hidden_layers=12,174 num_attention_heads=12,175 intermediate_size=3072,176 hidden_act="gelu",177 hidden_dropout=0.1,178 activation_dropout=0.1,179 attention_dropout=0.1,180 feat_proj_dropout=0.0,181 final_dropout=0.1,182 layerdrop=0.1,183 initializer_range=0.02,184 layer_norm_eps=1e-5,185 feat_extract_activation="gelu",186 conv_dim=(512, 512, 512, 512, 512, 512, 512),187 conv_stride=(5, 2, 2, 2, 2, 2, 2),188 conv_kernel=(10, 3, 3, 3, 3, 2, 2),189 conv_bias=False,190 num_conv_pos_embedding_groups=16,191 conv_pos_kernel_size=19,192 num_conv_pos_embeddings=5,193 mask_time_prob=0.05,194 mask_time_length=10,195 mask_time_min_masks=2,196 mask_feature_prob=0.0,197 mask_feature_length=10,198 mask_feature_min_masks=0,199 ctc_loss_reduction="sum",200 ctc_zero_infinity=False,201 use_weighted_layer_sum=False,202 classifier_proj_size=256,203 tdnn_dim=(512, 512, 512, 512, 1500),204 tdnn_kernel=(5, 3, 3, 1, 1),205 tdnn_dilation=(1, 2, 3, 1, 1),206 xvector_output_dim=512,207 pad_token_id=0,208 bos_token_id=1,209 eos_token_id=2,210 add_adapter=False,211 adapter_kernel_size=3,212 adapter_stride=2,213 num_adapter_layers=3,214 output_hidden_size=None,215 **kwargs,216 ):217 super().__init__(**kwargs, pad_token_id=pad_token_id, bos_token_id=bos_token_id, eos_token_id=eos_token_id)218 self.hidden_size = hidden_size219 self.feat_extract_activation = feat_extract_activation220 self.conv_dim = list(conv_dim)221 self.conv_stride = list(conv_stride)222 self.conv_kernel = list(conv_kernel)223 self.conv_bias = conv_bias224 self.num_conv_pos_embeddings = num_conv_pos_embeddings225 self.num_conv_pos_embedding_groups = num_conv_pos_embedding_groups226 self.conv_pos_kernel_size = conv_pos_kernel_size227 self.num_feat_extract_layers = len(self.conv_dim)228 self.num_hidden_layers = num_hidden_layers229 self.intermediate_size = intermediate_size230 self.hidden_act = hidden_act231 self.num_attention_heads = num_attention_heads232 self.hidden_dropout = hidden_dropout233 self.attention_dropout = attention_dropout234 self.activation_dropout = activation_dropout235 self.feat_proj_dropout = feat_proj_dropout236 self.final_dropout = final_dropout237 self.layerdrop = layerdrop238 self.layer_norm_eps = layer_norm_eps239 self.initializer_range = initializer_range240 self.vocab_size = vocab_size241 self.use_weighted_layer_sum = use_weighted_layer_sum242 243 if (244 (len(self.conv_stride) != self.num_feat_extract_layers)245 or (len(self.conv_kernel) != self.num_feat_extract_layers)246 or (len(self.conv_dim) != self.num_feat_extract_layers)247 ):248 raise ValueError(249 "Configuration for convolutional layers is incorrect. It is required that `len(config.conv_dim)` =="250 " `len(config.conv_stride)` == `len(config.conv_kernel)`, but is `len(config.conv_dim) ="251 f" {len(self.conv_dim)}`, `len(config.conv_stride) = {len(self.conv_stride)}`,"252 f" `len(config.conv_kernel) = {len(self.conv_kernel)}`."253 )254 255 # fine-tuning config parameters for SpecAugment: https://huggingface.co/papers/1904.08779256 self.mask_time_prob = mask_time_prob257 self.mask_time_length = mask_time_length258 self.mask_time_min_masks = mask_time_min_masks259 self.mask_feature_prob = mask_feature_prob260 self.mask_feature_length = mask_feature_length261 self.mask_feature_min_masks = mask_feature_min_masks262 263 # ctc loss264 self.ctc_loss_reduction = ctc_loss_reduction265 self.ctc_zero_infinity = ctc_zero_infinity266 267 # adapter268 self.add_adapter = add_adapter269 self.adapter_kernel_size = adapter_kernel_size270 self.adapter_stride = adapter_stride271 self.num_adapter_layers = num_adapter_layers272 self.output_hidden_size = output_hidden_size or hidden_size273 274 # SequenceClassification-specific parameter. Feel free to ignore for other classes.275 self.classifier_proj_size = classifier_proj_size276 277 # XVector-specific parameters. Feel free to ignore for other classes.278 self.tdnn_dim = list(tdnn_dim)279 self.tdnn_kernel = list(tdnn_kernel)280 self.tdnn_dilation = list(tdnn_dilation)281 self.xvector_output_dim = xvector_output_dim282 283 @property284 def inputs_to_logits_ratio(self):285 return math.prod(self.conv_stride)286 287 288__all__ = ["Data2VecAudioConfig"]289 