o
    @TiT                  9   @   s  d Z ddlZddlmZmZmZ ddlZddlm  m	Z
 ddlmZ ddlmZ ddlmZ G dd	 d	eZd
efddZ					d2dedeeeeeef   dededededededee dee dee dededee dedededed ee d!ed"ed#ed$ed%ed&ed
ef4d'd(Z					d2dedeeeeeef   dededededededee dee d)ee d*eee  d+ed,ededee dedededed ee d!ed"ed#ed$ed%ed&ed
ef8d-d.Z	/	/	/	/	/	d3dededededed ee d
efd0d1ZdS )4zSpeech SSL models supporting pruning.

Originally from:
https://github.com/pytorch/audio/blob/main/torchaudio/models/wav2vec2/model.py

    N)ListOptionalTuple)Tensor)Module   )
componentsc                       s   e Zd ZdZ	ddedededee f fddZej	j
		dd	ed
ee dee deee ee f fddZdd Zdd Z	dd	ed
ee deeee f fddZ  ZS )Wav2Vec2Modela  Acoustic model used in *wav2vec 2.0* :cite:`baevski2020wav2vec`.

    Note:
        To build the model, please use one of the factory functions.
        :py:func:`wav2vec2_model`, :py:func:`wav2vec2_base`, :py:func:`wav2vec2_large`,
        :py:func:`wav2vec2_large_lv60k`, :py:func:`hubert_base`, :py:func:`hubert_large`,
        and :py:func:`hubert_xlarge`.

    See Also:
        * :class:`torchaudio.pipelines.Wav2Vec2Bundle`: Pretrained models (without fine-tuning)
        * :class:`torchaudio.pipelines.Wav2Vec2ASRBundle`: ASR pipelines with pretrained models.

    Args:
        feature_extractor (torch.nn.Module):
            Feature extractor that extracts feature vectors from raw audio Tensor.

        encoder (torch.nn.Module):
            Encoder that converts the audio features into the sequence of probability
            distribution (in negative log-likelihood) over labels.

        aux (torch.nn.Module or None, optional):
            Auxiliary module. If provided, the output from encoder is passed to this module.
    Nnormalize_waveformfeature_extractorencoderauxc                    s&   t    || _|| _|| _|| _d S N)super__init__r
   r   r   r   )selfr
   r   r   r   	__class__ R/home/ubuntu/.local/lib/python3.10/site-packages/linacodec/module/distill_wavlm.pyr   ,   s
   

zWav2Vec2Model.__init__	waveformslengths
num_layersreturnc                 C   sv   | j r'|durdd t||D }tjjjj|dd}nt||j	dd }| 
||\}}| j|||}||fS )a%  Extract feature vectors from raw waveforms

        This returns the list of outputs from the intermediate layers of
        transformer block in encoder.

        Args:
            waveforms (Tensor): Audio tensor of shape `(batch, frames)`.
            lengths (Tensor or None, optional):
                Indicates the valid length of each audio in the batch.
                Shape: `(batch, )`.
                When the ``waveforms`` contains audios with different durations,
                by providing ``lengths`` argument, the model will compute
                the corresponding valid output lengths and apply proper mask in
                transformer attention layer.
                If ``None``, it is assumed that the entire audio waveform
                length is valid.
            num_layers (int or None, optional):
                If given, limit the number of intermediate layers to go through.
                Providing `1` will stop the computation after going through one
                intermediate layers. If not given, the outputs from all the
                intermediate layers are returned.

        Returns:
            (List[Tensor], Optional[Tensor]):
            List of Tensors
                Features from requested layers.
                Each Tensor is of shape: `(batch, time frame, feature dimension)`
            Tensor or None
                If ``lengths`` argument was provided, a Tensor of shape `(batch, )`
                is returned.
                It indicates the valid length in time axis of each feature Tensor.
        Nc                 S   &   g | ]\}}t |d | |fqS r   F
layer_norm.0wavelengthr   r   r   
<listcomp>b       z2Wav2Vec2Model.extract_features.<locals>.<listcomp>Tbatch_first)r
   ziptorchnnutilsrnnpad_sequencer   r   shaper   r   extract_features)r   r   r   r   xr   r   r   r.   9   s   'zWav2Vec2Model.extract_featuresc                 C   s"   | j  \}}| j|}|| S )zCalculate the current size.)r   %get_num_params_and_final_out_channelsr   get_num_params)r   feature_extractor_sizeencoder_in_featuresencoder_sizer   r   r   r1   m   s   zWav2Vec2Model.get_num_paramsc           	      C   sZ   |    | j \}}| j|}|d }|d }|d }|d }|d }||||||fS )Nuse_attentionuse_feed_forward	num_headsremaining_headsff_interm_features)evalr   pruner   )	r   conv_configconv_out_indextransformer_configr5   r6   r7   r8   r9   r   r   r   r;   s   s   zWav2Vec2Model.prunec                 C   s   | j r'|durdd t||D }tjjjj|dd}nt||j	dd }| 
||\}}| ||}| jdur?| |}||fS )a  Compute the sequence of probability distribution over labels.

        Args:
            waveforms (Tensor): Audio tensor of shape `(batch, frames)`.
            lengths (Tensor or None, optional):
                Indicates the valid length of each audio in the batch.
                Shape: `(batch, )`.
                When the ``waveforms`` contains audios with different durations,
                by providing ``lengths`` argument, the model will compute
                the corresponding valid output lengths and apply proper mask in
                transformer attention layer.
                If ``None``, it is assumed that all the audio in ``waveforms``
                have valid length. Default: ``None``.

        Returns:
            (Tensor, Optional[Tensor]):
            Tensor
                The sequences of probability distribution (in logit) over labels.
                Shape: `(batch, frames, num labels)`.
            Tensor or None
                If ``lengths`` argument was provided, a Tensor of shape `(batch, )`
                is returned.
                It indicates the valid length in time axis of the output Tensor.
        Nc                 S   r   r   r   r   r   r   r   r"      r#   z)Wav2Vec2Model.forward.<locals>.<listcomp>Tr$   r&   )r
   r'   r(   r)   r*   r+   r,   r   r   r-   r   r   r   )r   r   r   r/   r   r   r   forward   s   

zWav2Vec2Model.forwardr   )NN)__name__
__module____qualname____doc__boolr   r   r   r(   jitexportr   intr   r   r.   r1   r;   r?   __classcell__r   r   r   r   r	      sD    3r	   r   c                  K   s$   d| v rt di | S tdi | S )z2Wraps the original wav2vec2_model and wavlm_model.encoder_remaining_headsNr   )wavlm_modelwav2vec2_model_original)configsr   r   r   wav2vec2_model   s   rM   Fextractor_modeextractor_conv_layer_configextractor_conv_biasencoder_embed_dimencoder_projection_dropoutencoder_pos_conv_kernelencoder_pos_conv_groupsencoder_num_layersencoder_use_attentionencoder_use_feed_forwardencoder_num_headsencoder_head_dimencoder_attention_dropoutencoder_ff_interm_featuresencoder_ff_interm_dropoutencoder_dropoutencoder_layer_norm_firstencoder_layer_dropaux_num_outr
   extractor_prune_conv_channelsencoder_prune_attention_headsencoder_prune_attention_layer'encoder_prune_feed_forward_intermediate encoder_prune_feed_forward_layerc                 C   s   |du rdgdgd  dgd  }t j| |||d}t jdi d|d	 d
 d|d|d|d|d|d|d|	d|
d|d|d|d|d|d|d|d|d|d|d|}d}|durntjj||d}t||||S ) as  Builds custom :class:`~torchaudio.models.Wav2Vec2Model`.

    Note:
        The "feature extractor" below corresponds to
        `ConvFeatureExtractionModel <https://github.com/pytorch/fairseq/blob/dd3bd3c0497ae9a7ae7364404a6b0a4c501780b3/fairseq/models/wav2vec/wav2vec2.py#L736>`__
        in the original ``fairseq`` implementation.
        This is referred as "(convolutional) feature encoder" in the *wav2vec 2.0*
        :cite:`baevski2020wav2vec` paper.

        The "encoder" below corresponds to `TransformerEncoder <https://github.com/pytorch/fairseq/blob/dd3bd3c0497ae9a7ae7364404a6b0a4c501780b3/fairseq/models/wav2vec/wav2vec2.py#L817>`__,
        and this is referred as "Transformer" in the paper.

    Args:
        extractor_mode (str): Operation mode of feature extractor.
            Valid values are ``"group_norm"`` or ``"layer_norm"``.
            If ``"group_norm"``, then a single normalization is applied
            in the first convolution block. Otherwise, all the convolution
            blocks will have layer normalization.

            This option corresponds to ``extractor_mode`` from ``fairseq``.
        extractor_conv_layer_config (list of integer tuples or None):
            Configuration of convolution layers in feature extractor.
            List of convolution configuration,
            i.e. ``[(output_channel, kernel_size, stride), ...]``

            If ``None`` is provided, then the following default value is used.

            .. code-block:: python

               [
                 (512, 10, 5),
                 (512, 3, 2),
                 (512, 3, 2),
                 (512, 3, 2),
                 (512, 3, 2),
                 (512, 2, 2),
                 (512, 2, 2),
               ]

            This option corresponds to ``conv_feature_layers`` from ``fairseq``.

        extractor_conv_bias (bool):
            Whether to include bias term to each convolution operation.

            This option corresponds to ``conv_bias`` from ``fairseq``.

        encoder_embed_dim (int):
            The dimension of embedding in encoder.

            This option corresponds to ``encoder_embed_dim`` from ``fairseq``.

        encoder_projection_dropout (float):
            The dropout probability applied after the input feature is projected
            to ``encoder_embed_dim``.

            This option corresponds to ``dropout_input`` from ``fairseq``.

        encoder_pos_conv_kernel (int):
            The kernel size of convolutional positional embeddings.

            This option corresponds to ``conv_pos`` from ``fairseq``.

        encoder_pos_conv_groups (int):
            The number of groups of convolutional positional embeddings.

            This option corresponds to ``conv_pos_groups`` from ``fairseq``.

        encoder_num_layers (int):
            The number of self attention layers in transformer block.

            This option corresponds to ``encoder_layers`` from ``fairseq``.

        encoder_num_heads (int):
            The number of heads in self attention layers.

            This option corresponds to ``encoder_attention_heads`` from ``fairseq``.

        encoder_attention_dropout (float):
            The dropout probability applied after softmax in self-attention layer.

            This option corresponds to ``attention_dropout`` from ``fairseq``.

        encoder_ff_interm_features (int):
            The dimension of hidden features in feed forward layer.

            This option corresponds to ``encoder_ffn_embed_dim`` from ``fairseq``.

        encoder_ff_interm_dropout (float):
            The dropout probability applied in feedforward layer.

            This option correspinds to ``activation_dropout`` from ``fairseq``.

        encoder_dropout (float):
            The dropout probability applied at the end of feed forward layer.

            This option corresponds to ``dropout`` from ``fairseq``.

        encoder_layer_norm_first (bool):
            Control the order of layer norm in transformer layer and each encoder layer.
            If True, in transformer layer, layer norm is applied before features are fed
            to encoder layers. In encoder layer, two layer norms are applied before and after
            self attention.
            If False, in transformer layer, layer norm is applied after features are fed
            to encoder layers. In encoder layer, two layer norms are applied after self
            attention, before and after feed forward.

            This option corresponds to ``layer_norm_first`` from ``fairseq``.

        encoder_layer_drop (float):
            Probability to drop each encoder layer during training.

            This option corresponds to ``layerdrop`` from ``fairseq``.

        aux_num_out (int or None):
            When provided, attach an extra linear layer on top of encoder, which can be
            used for fine-tuning.

    Returns:
        Wav2Vec2Model:
            The resulting model.
    N   
      rg            rg   rl   rl   rl   prune_conv_channelsin_featuresr&   r   	embed_dimdropout_inputpos_conv_kernelpos_conv_groupsr   r5   r6   r7   head_dimattention_dropoutr9   ff_interm_dropoutdropoutlayer_norm_first
layer_dropprune_attention_headsprune_attention_layerprune_feed_forward_intermediateprune_feed_forward_layerrq   out_featuresr   )r   _get_feature_extractor_get_encoderr(   r)   Linearr	   )rN   rO   rP   rQ   rR   rS   rT   rU   rV   rW   rX   rY   rZ   r[   r\   r]   r^   r_   r`   r
   ra   rb   rc   rd   re   r   r   r   r   r   r   rK      sh    
	
rK   encoder_total_num_headsrI   encoder_num_bucketsencoder_max_distancec                 C   s   |du rdgdgd  dgd  }t j| |||d}t jd!i d|d	 d
 d|d|d|d|d|d|d|	d|
d|d|d|d|d|d|d|d|d|d|d|d|d|}d}|durttjj||d }t||||S )"a  Builds custom WaveLM model :cite:`chen2022wavlm`. The architecture is compatible
    with Wav2Vec2 model :cite:`baevski2020wav2vec`, and so the output object is
    :class:`~torchaudio.models.Wav2Vec2Model`. Most of the arguments have the same meaning
    as in :py:func:`wav2vec2_model` so please refer there for documentation.

    Args:
        extractor_mode (str): Operation mode of feature extractor.
            See :py:func:`wav2vec2_model`.

        extractor_conv_layer_config (list of integer tuples or None):
            See :py:func:`wav2vec2_model`.

        extractor_conv_bias (bool):
            See :py:func:`wav2vec2_model`.

        encoder_embed_dim (int):
            See :py:func:`wav2vec2_model`.

        encoder_projection_dropout (float):
            See :py:func:`wav2vec2_model`.

        encoder_pos_conv_kernel (int):
            See :py:func:`wav2vec2_model`.

        encoder_pos_conv_groups (int):
            See :py:func:`wav2vec2_model`.

        encoder_num_layers (int):
            See :py:func:`wav2vec2_model`.

        encoder_num_heads (int):
            See :py:func:`wav2vec2_model`.

        encoder_num_buckets (int):
            Number of buckets for relative position embedding.
        encoder_max_distance (int):
            Maximum distance for relative position embedding.

        encoder_attention_dropout (float):
            See :py:func:`wav2vec2_model`.

        encoder_ff_interm_features (int):
            See :py:func:`wav2vec2_model`.

        encoder_ff_interm_dropout (float):
            See :py:func:`wav2vec2_model`.

        encoder_dropout (float):
            See :py:func:`wav2vec2_model`.

        encoder_layer_norm_first (bool):
            See :py:func:`wav2vec2_model`.

        encoder_layer_drop (float):
            See :py:func:`wav2vec2_model`.

        aux_num_out (int or None):
            See :py:func:`wav2vec2_model`.

    Returns:
        Wav2Vec2Model:
            The resulting model.
    Nrf   rj   rm   rn   rl   ro   rq   r&   r   rr   rs   rt   ru   r   r5   r6   total_num_headsr8   num_bucketsmax_distancerw   r9   rx   ry   rz   r{   r|   r}   r~   r   r   r   )r   r   _get_wavlm_encoderr(   r)   r   r	   )rN   rO   rP   rQ   rR   rS   rT   rU   rV   rW   r   rI   r   r   rZ   r[   r\   r]   r^   r_   r`   r
   ra   rb   rc   rd   re   r   r   r   r   r   r   rJ   k  sn   \
	
rJ   皙?c                 C   sv   t di ddddddddd	| d
dddddddddddd|ddd|d|ddd|d|S )a  Builds "base" WaveLM model :cite:`chen2022wavlm`. The architecture is compatible
    with Wav2Vec2 model :cite:`baevski2020wav2vec`, and so the output class is
    :class:`~torchaudio.models.Wav2Vec2Model`.

    Args:
        encoder_projection_dropout (float):
            See :py:func:`wav2vec2_model`.
        encoder_attention_dropout (float):
            See :py:func:`wav2vec2_model`.
        encoder_ff_interm_dropout (float):
            See :py:func:`wav2vec2_model`.
        encoder_dropout (float):
            See :py:func:`wav2vec2_model`.
        encoder_layer_drop (float):
            See :py:func:`wav2vec2_model`.
        aux_num_out (int, optional):
            See :py:func:`wav2vec2_model`.

    Returns:
        Wav2Vec2Model:
            The resulting model.
    rN   
group_normrO   NrP   FrQ   i   rR   rS      rT      rU      rX   r   i@  r   i   rZ   r[   i   r\   r]   r^   r_   r`   r   )rJ   )rR   rZ   r\   r]   r_   r`   r   r   r   
wavlm_base  sJ   	
r   )FFFFF)r   r   r   r   r   N)rC   mathtypingr   r   r   r(   torch.nn.functionalr)   
functionalr   r   torch.nnr    r   r	   rM   strrG   rD   floatrK   rJ   r   r   r   r   r   <module>   s4    	

 N	


 