CoolFace
Apppublic

Aluode/PerceptionLabPortable

sourceHugging Faceupdated 9mo agoView on Hugging Face
0likes
configuration_wav2vec2.py348 linesDownload Raw Back to wav2vec2
1# coding=utf-82# 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 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"""Wav2Vec2 model configuration"""16 17import functools18import operator19 20from ...configuration_utils import PretrainedConfig21from ...utils import logging22 23 24logger = logging.get_logger(__name__)25 26 27class Wav2Vec2Config(PretrainedConfig):28    r"""29    This is the configuration class to store the configuration of a [`Wav2Vec2Model`]. It is used to instantiate an30    Wav2Vec2 model according to the specified arguments, defining the model architecture. Instantiating a configuration31    with the defaults will yield a similar configuration to that of the Wav2Vec232    [facebook/wav2vec2-base-960h](https://huggingface.co/facebook/wav2vec2-base-960h) architecture.33 34    Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the35    documentation from [`PretrainedConfig`] for more information.36 37 38    Args:39        vocab_size (`int`, *optional*, defaults to 32):40            Vocabulary size of the Wav2Vec2 model. Defines the number of different tokens that can be represented by41            the `inputs_ids` passed when calling [`Wav2Vec2Model`] or [`TFWav2Vec2Model`]. Vocabulary size of the42            model. Defines the different tokens that can be represented by the *inputs_ids* passed to the forward43            method of [`Wav2Vec2Model`].44        hidden_size (`int`, *optional*, defaults to 768):45            Dimensionality of the encoder layers and the pooler layer.46        num_hidden_layers (`int`, *optional*, defaults to 12):47            Number of hidden layers in the Transformer encoder.48        num_attention_heads (`int`, *optional*, defaults to 12):49            Number of attention heads for each attention layer in the Transformer encoder.50        intermediate_size (`int`, *optional*, defaults to 3072):51            Dimensionality of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder.52        hidden_act (`str` or `function`, *optional*, defaults to `"gelu"`):53            The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,54            `"relu"`, `"selu"` and `"gelu_new"` are supported.55        hidden_dropout (`float`, *optional*, defaults to 0.1):56            The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.57        activation_dropout (`float`, *optional*, defaults to 0.1):58            The dropout ratio for activations inside the fully connected layer.59        attention_dropout (`float`, *optional*, defaults to 0.1):60            The dropout ratio for the attention probabilities.61        final_dropout (`float`, *optional*, defaults to 0.1):62            The dropout probability for the final projection layer of [`Wav2Vec2ForCTC`].63        layerdrop (`float`, *optional*, defaults to 0.1):64            The LayerDrop probability. See the [LayerDrop paper](see https://huggingface.co/papers/1909.11556) for more65            details.66        initializer_range (`float`, *optional*, defaults to 0.02):67            The standard deviation of the truncated_normal_initializer for initializing all weight matrices.68        layer_norm_eps (`float`, *optional*, defaults to 1e-12):69            The epsilon used by the layer normalization layers.70        feat_extract_norm (`str`, *optional*, defaults to `"group"`):71            The norm to be applied to 1D convolutional layers in feature encoder. One of `"group"` for group72            normalization of only the first 1D convolutional layer or `"layer"` for layer normalization of all 1D73            convolutional layers.74        feat_proj_dropout (`float`, *optional*, defaults to 0.0):75            The dropout probability for output of the feature encoder.76        feat_extract_activation (`str, `optional`, defaults to `"gelu"`):77            The non-linear activation function (function or string) in the 1D convolutional layers of the feature78            extractor. If string, `"gelu"`, `"relu"`, `"selu"` and `"gelu_new"` are supported.79        feat_quantizer_dropout (`float`, *optional*, defaults to 0.0):80            The dropout probability for quantized feature encoder states.81        conv_dim (`tuple[int]` or `list[int]`, *optional*, defaults to `(512, 512, 512, 512, 512, 512, 512)`):82            A tuple of integers defining the number of input and output channels of each 1D convolutional layer in the83            feature encoder. The length of *conv_dim* defines the number of 1D convolutional layers.84        conv_stride (`tuple[int]` or `list[int]`, *optional*, defaults to `(5, 2, 2, 2, 2, 2, 2)`):85            A tuple of integers defining the stride of each 1D convolutional layer in the feature encoder. The length86            of *conv_stride* defines the number of convolutional layers and has to match the length of *conv_dim*.87        conv_kernel (`tuple[int]` or `list[int]`, *optional*, defaults to `(10, 3, 3, 3, 3, 3, 3)`):88            A tuple of integers defining the kernel size of each 1D convolutional layer in the feature encoder. The89            length of *conv_kernel* defines the number of convolutional layers and has to match the length of90            *conv_dim*.91        conv_bias (`bool`, *optional*, defaults to `False`):92            Whether the 1D convolutional layers have a bias.93        num_conv_pos_embeddings (`int`, *optional*, defaults to 128):94            Number of convolutional positional embeddings. Defines the kernel size of 1D convolutional positional95            embeddings layer.96        num_conv_pos_embedding_groups (`int`, *optional*, defaults to 16):97            Number of groups of 1D convolutional positional embeddings layer.98        do_stable_layer_norm (`bool`, *optional*, defaults to `False`):99            Whether to apply *stable* layer norm architecture of the Transformer encoder. `do_stable_layer_norm is100            True` corresponds to applying layer norm before the attention layer, whereas `do_stable_layer_norm is101            False` corresponds to applying layer norm after the attention layer.102        apply_spec_augment (`bool`, *optional*, defaults to `True`):103            Whether to apply *SpecAugment* data augmentation to the outputs of the feature encoder. For reference see104            [SpecAugment: A Simple Data Augmentation Method for Automatic Speech105            Recognition](https://huggingface.co/papers/1904.08779).106        mask_time_prob (`float`, *optional*, defaults to 0.05):107            Percentage (between 0 and 1) of all feature vectors along the time axis which will be masked. The masking108            procedure generates ''mask_time_prob*len(time_axis)/mask_time_length'' independent masks over the axis. If109            reasoning from the probability of each feature vector to be chosen as the start of the vector span to be110            masked, *mask_time_prob* should be `prob_vector_start*mask_time_length`. Note that overlap may decrease the111            actual percentage of masked vectors. This is only relevant if `apply_spec_augment is True`.112        mask_time_length (`int`, *optional*, defaults to 10):113            Length of vector span along the time axis.114        mask_time_min_masks (`int`, *optional*, defaults to 2),:115            The minimum number of masks of length `mask_feature_length` generated along the time axis, each time step,116            irrespectively of `mask_feature_prob`. Only relevant if ''mask_time_prob*len(time_axis)/mask_time_length <117            mask_time_min_masks''118        mask_feature_prob (`float`, *optional*, defaults to 0.0):119            Percentage (between 0 and 1) of all feature vectors along the feature axis which will be masked. The120            masking procedure generates ''mask_feature_prob*len(feature_axis)/mask_time_length'' independent masks over121            the axis. If reasoning from the probability of each feature vector to be chosen as the start of the vector122            span to be masked, *mask_feature_prob* should be `prob_vector_start*mask_feature_length`. Note that overlap123            may decrease the actual percentage of masked vectors. This is only relevant if `apply_spec_augment is124            True`.125        mask_feature_length (`int`, *optional*, defaults to 10):126            Length of vector span along the feature axis.127        mask_feature_min_masks (`int`, *optional*, defaults to 0),:128            The minimum number of masks of length `mask_feature_length` generated along the feature axis, each time129            step, irrespectively of `mask_feature_prob`. Only relevant if130            ''mask_feature_prob*len(feature_axis)/mask_feature_length < mask_feature_min_masks''131        num_codevectors_per_group (`int`, *optional*, defaults to 320):132            Number of entries in each quantization codebook (group).133        num_codevector_groups (`int`, *optional*, defaults to 2):134            Number of codevector groups for product codevector quantization.135        contrastive_logits_temperature (`float`, *optional*, defaults to 0.1):136            The temperature *kappa* in the contrastive loss.137        feat_quantizer_dropout (`float`, *optional*, defaults to 0.0):138            The dropout probability for the output of the feature encoder that's used by the quantizer.139        num_negatives (`int`, *optional*, defaults to 100):140            Number of negative samples for the contrastive loss.141        codevector_dim (`int`, *optional*, defaults to 256):142            Dimensionality of the quantized feature vectors.143        proj_codevector_dim (`int`, *optional*, defaults to 256):144            Dimensionality of the final projection of both the quantized and the transformer features.145        diversity_loss_weight (`int`, *optional*, defaults to 0.1):146            The weight of the codebook diversity loss component.147        ctc_loss_reduction (`str`, *optional*, defaults to `"sum"`):148            Specifies the reduction to apply to the output of `torch.nn.CTCLoss`. Only relevant when training an149            instance of [`Wav2Vec2ForCTC`].150        ctc_zero_infinity (`bool`, *optional*, defaults to `False`):151            Whether to zero infinite losses and the associated gradients of `torch.nn.CTCLoss`. Infinite losses mainly152            occur when the inputs are too short to be aligned to the targets. Only relevant when training an instance153            of [`Wav2Vec2ForCTC`].154        use_weighted_layer_sum (`bool`, *optional*, defaults to `False`):155            Whether to use a weighted average of layer outputs with learned weights. Only relevant when using an156            instance of [`Wav2Vec2ForSequenceClassification`].157        classifier_proj_size (`int`, *optional*, defaults to 256):158            Dimensionality of the projection before token mean-pooling for classification.159        tdnn_dim (`tuple[int]` or `list[int]`, *optional*, defaults to `(512, 512, 512, 512, 1500)`):160            A tuple of integers defining the number of output channels of each 1D convolutional layer in the *TDNN*161            module of the *XVector* model. The length of *tdnn_dim* defines the number of *TDNN* layers.162        tdnn_kernel (`tuple[int]` or `list[int]`, *optional*, defaults to `(5, 3, 3, 1, 1)`):163            A tuple of integers defining the kernel size of each 1D convolutional layer in the *TDNN* module of the164            *XVector* model. The length of *tdnn_kernel* has to match the length of *tdnn_dim*.165        tdnn_dilation (`tuple[int]` or `list[int]`, *optional*, defaults to `(1, 2, 3, 1, 1)`):166            A tuple of integers defining the dilation factor of each 1D convolutional layer in *TDNN* module of the167            *XVector* model. The length of *tdnn_dilation* has to match the length of *tdnn_dim*.168        xvector_output_dim (`int`, *optional*, defaults to 512):169            Dimensionality of the *XVector* embedding vectors.170        add_adapter (`bool`, *optional*, defaults to `False`):171            Whether a convolutional network should be stacked on top of the Wav2Vec2 Encoder. Can be very useful for172            warm-starting Wav2Vec2 for SpeechEncoderDecoder models.173        adapter_kernel_size (`int`, *optional*, defaults to 3):174            Kernel size of the convolutional layers in the adapter network. Only relevant if `add_adapter is True`.175        adapter_stride (`int`, *optional*, defaults to 2):176            Stride of the convolutional layers in the adapter network. Only relevant if `add_adapter is True`.177        num_adapter_layers (`int`, *optional*, defaults to 3):178            Number of convolutional layers that should be used in the adapter network. Only relevant if `add_adapter is179            True`.180        adapter_attn_dim (`int`, *optional*):181            Dimension of the attention adapter weights to be used in each attention block. An example of a model using182            attention adapters is [facebook/mms-1b-all](https://huggingface.co/facebook/mms-1b-all).183        output_hidden_size (`int`, *optional*):184            Dimensionality of the encoder output layer. If not defined, this defaults to *hidden-size*. Only relevant185            if `add_adapter is True`.186 187    Example:188 189    ```python190    >>> from transformers import Wav2Vec2Config, Wav2Vec2Model191 192    >>> # Initializing a Wav2Vec2 facebook/wav2vec2-base-960h style configuration193    >>> configuration = Wav2Vec2Config()194 195    >>> # Initializing a model (with random weights) from the facebook/wav2vec2-base-960h style configuration196    >>> model = Wav2Vec2Model(configuration)197 198    >>> # Accessing the model configuration199    >>> configuration = model.config200    ```"""201 202    model_type = "wav2vec2"203 204    def __init__(205        self,206        vocab_size=32,207        hidden_size=768,208        num_hidden_layers=12,209        num_attention_heads=12,210        intermediate_size=3072,211        hidden_act="gelu",212        hidden_dropout=0.1,213        activation_dropout=0.1,214        attention_dropout=0.1,215        feat_proj_dropout=0.0,216        feat_quantizer_dropout=0.0,217        final_dropout=0.1,218        layerdrop=0.1,219        initializer_range=0.02,220        layer_norm_eps=1e-5,221        feat_extract_norm="group",222        feat_extract_activation="gelu",223        conv_dim=(512, 512, 512, 512, 512, 512, 512),224        conv_stride=(5, 2, 2, 2, 2, 2, 2),225        conv_kernel=(10, 3, 3, 3, 3, 2, 2),226        conv_bias=False,227        num_conv_pos_embeddings=128,228        num_conv_pos_embedding_groups=16,229        do_stable_layer_norm=False,230        apply_spec_augment=True,231        mask_time_prob=0.05,232        mask_time_length=10,233        mask_time_min_masks=2,234        mask_feature_prob=0.0,235        mask_feature_length=10,236        mask_feature_min_masks=0,237        num_codevectors_per_group=320,238        num_codevector_groups=2,239        contrastive_logits_temperature=0.1,240        num_negatives=100,241        codevector_dim=256,242        proj_codevector_dim=256,243        diversity_loss_weight=0.1,244        ctc_loss_reduction="sum",245        ctc_zero_infinity=False,246        use_weighted_layer_sum=False,247        classifier_proj_size=256,248        tdnn_dim=(512, 512, 512, 512, 1500),249        tdnn_kernel=(5, 3, 3, 1, 1),250        tdnn_dilation=(1, 2, 3, 1, 1),251        xvector_output_dim=512,252        pad_token_id=0,253        bos_token_id=1,254        eos_token_id=2,255        add_adapter=False,256        adapter_kernel_size=3,257        adapter_stride=2,258        num_adapter_layers=3,259        output_hidden_size=None,260        adapter_attn_dim=None,261        **kwargs,262    ):263        super().__init__(**kwargs, pad_token_id=pad_token_id, bos_token_id=bos_token_id, eos_token_id=eos_token_id)264        self.hidden_size = hidden_size265        self.feat_extract_norm = feat_extract_norm266        self.feat_extract_activation = feat_extract_activation267        self.conv_dim = list(conv_dim)268        self.conv_stride = list(conv_stride)269        self.conv_kernel = list(conv_kernel)270        self.conv_bias = conv_bias271        self.num_conv_pos_embeddings = num_conv_pos_embeddings272        self.num_conv_pos_embedding_groups = num_conv_pos_embedding_groups273        self.num_feat_extract_layers = len(self.conv_dim)274        self.num_hidden_layers = num_hidden_layers275        self.intermediate_size = intermediate_size276        self.hidden_act = hidden_act277        self.num_attention_heads = num_attention_heads278        self.hidden_dropout = hidden_dropout279        self.attention_dropout = attention_dropout280        self.activation_dropout = activation_dropout281        self.feat_proj_dropout = feat_proj_dropout282        self.final_dropout = final_dropout283        self.layerdrop = layerdrop284        self.layer_norm_eps = layer_norm_eps285        self.initializer_range = initializer_range286        self.vocab_size = vocab_size287        self.do_stable_layer_norm = do_stable_layer_norm288        self.use_weighted_layer_sum = use_weighted_layer_sum289 290        if (291            (len(self.conv_stride) != self.num_feat_extract_layers)292            or (len(self.conv_kernel) != self.num_feat_extract_layers)293            or (len(self.conv_dim) != self.num_feat_extract_layers)294        ):295            raise ValueError(296                "Configuration for convolutional layers is incorrect. It is required that `len(config.conv_dim)` =="297                " `len(config.conv_stride)` == `len(config.conv_kernel)`, but is `len(config.conv_dim) ="298                f" {len(self.conv_dim)}`, `len(config.conv_stride) = {len(self.conv_stride)}`,"299                f" `len(config.conv_kernel) = {len(self.conv_kernel)}`."300            )301 302        # fine-tuning config parameters for SpecAugment: https://huggingface.co/papers/1904.08779303        self.apply_spec_augment = apply_spec_augment304        self.mask_time_prob = mask_time_prob305        self.mask_time_length = mask_time_length306        self.mask_time_min_masks = mask_time_min_masks307        self.mask_feature_prob = mask_feature_prob308        self.mask_feature_length = mask_feature_length309        self.mask_feature_min_masks = mask_feature_min_masks310 311        # parameters for pretraining with codevector quantized representations312        self.num_codevectors_per_group = num_codevectors_per_group313        self.num_codevector_groups = num_codevector_groups314        self.contrastive_logits_temperature = contrastive_logits_temperature315        self.feat_quantizer_dropout = feat_quantizer_dropout316        self.num_negatives = num_negatives317        self.codevector_dim = codevector_dim318        self.proj_codevector_dim = proj_codevector_dim319        self.diversity_loss_weight = diversity_loss_weight320 321        # ctc loss322        self.ctc_loss_reduction = ctc_loss_reduction323        self.ctc_zero_infinity = ctc_zero_infinity324 325        # adapter326        self.add_adapter = add_adapter327        self.adapter_kernel_size = adapter_kernel_size328        self.adapter_stride = adapter_stride329        self.num_adapter_layers = num_adapter_layers330        self.output_hidden_size = output_hidden_size or hidden_size331        self.adapter_attn_dim = adapter_attn_dim332 333        # SequenceClassification-specific parameter. Feel free to ignore for other classes.334        self.classifier_proj_size = classifier_proj_size335 336        # XVector-specific parameters. Feel free to ignore for other classes.337        self.tdnn_dim = list(tdnn_dim)338        self.tdnn_kernel = list(tdnn_kernel)339        self.tdnn_dilation = list(tdnn_dilation)340        self.xvector_output_dim = xvector_output_dim341 342    @property343    def inputs_to_logits_ratio(self):344        return functools.reduce(operator.mul, self.conv_stride, 1)345 346 347__all__ = ["Wav2Vec2Config"]348 
Aluode/PerceptionLabPortable · CoolFace