o
    hI8                    @   s  d Z ddlZddlZddlZddlmZmZmZ ddlZ	ddl
Z
ddlm  mZ ddlZ
ddl
mZ ddlmZ ddlmZ ddlmZ dd	lmZmZ dd
lmZmZmZmZmZmZ ddl m!Z! ddl"m#Z#m$Z$m%Z%m&Z&m'Z'm(Z( ddl)m*Z* ddl+m,Z,m-Z- e% rddl.m/Z/m0Z0 ddl1m2Z2m3Z3m4Z4 e'5e6Z7dZ8dZ9dgZ:dd Z;dUde<de<de=de
j>fddZ?de
j>de<d e<fd!d"Z@		dVd#ee<e<f d$e=d%e<d&ee
jA d'e<de	jBfd(d)ZCd*e
j>d+e<de
j>fd,d-ZDd.e	jBfd/d0ZEG d1d2 d2ejFZGG d3d4 d4ejHZIG d5d6 d6eIZJG d7d8 d8eIZKeIeJeKd9ZLG d:d; d;ejHZMG d<d= d=ejHZNG d>d? d?e!ZOd@ZPdAZQdBZRG dCdD dDeOZSG dEdF dFeOZTe#dGePG dHdI dIeOZUe#dJePG dKdL dLeOZVG dMdN dNeOZWe#dOePG dPdQ dQeOZXe#dReRG dSdT dTeOZYdS )Wz PyTorch Whisper model.    N)OptionalTupleUnion)nn)CrossEntropyLoss   )ACT2FN)WhisperTimeStampLogitsProcessor)!_prepare_4d_causal_attention_mask*_prepare_4d_causal_attention_mask_for_sdpa)BaseModelOutput)BaseModelOutputWithPastAndCrossAttentions!CausalLMOutputWithCrossAttentionsSeq2SeqLMOutputSeq2SeqModelOutputSequenceClassifierOutput)PreTrainedModel)add_start_docstrings%add_start_docstrings_to_model_forwardis_flash_attn_2_available#is_flash_attn_greater_or_equal_2_10loggingreplace_return_docstrings   )WhisperConfig)TASK_IDSTO_LANGUAGE_CODE)flash_attn_funcflash_attn_varlen_func)index_first_axis	pad_inputunpad_inputr   zopenai/whisper-tinyzopenai/whisper-basec                 C   sX   | j dtjd}tj|  dd }|  }ttj	|dtjjdd}|||fS )N)dimdtypeF)as_tupler   r   r   )
sumtorchint32nonzeroflattenmaxitemFpadcumsum)attention_maskseqlens_in_batchindicesmax_seqlen_in_batch
cu_seqlens r6   b/var/www/html/ai/venv/lib/python3.10/site-packages/transformers/models/whisper/modeling_whisper.py_get_unpad_dataG   s   r8   '  lengthchannelsmax_timescalereturnc                 C   s   |d dkrt d| dt||d d  }t| t|d  }t| dd|dd }tj| |	 gddS )z*Returns sinusoids for positional embedding   r   zVNumber of channels has to be divisible by 2 for sinusoidal positional embeddings, got z
 channels.r   r"   r#   )

ValueErrormathlogr(   exparangeviewcatsincos)r:   r;   r<   log_timescale_incrementinv_timescalesscaled_timer6   r6   r7   	sinusoidsS   s   
rL   	input_idspad_token_iddecoder_start_token_idc                 C   sh   |  | j}| ddddf  |ddddf< ||dddf< |du r*td||dk| |S )z1
    Shift input ids one token to the right.
    Nr"   r   r   z1self.model.config.pad_token_id has to be defined.i)	new_zerosshapecloner@   masked_fill_)rM   rN   rO   shifted_input_idsr6   r6   r7   shift_tokens_right`   s   (rU   rQ   	mask_probmask_lengthr1   	min_masksc                    s  | \}dk rt dkrt d d dtjd   fdd}|dur:|d	  n
fd
dt|D }tj	|ft
d}g }	|}
|
dkrZ|S |D ];}||}tjjt|d  |dd}t|dkr}d }n|d }t|tj|
| tjd| g}|	| q\t|	}	t|	dddddf ||
f}	|	||
 }	tddddf }t|||
f||
 }|	| }	|	 d krd |	|	d k< t||	dd	 |S )af  
    Computes random mask spans for a given shape. Used to implement [SpecAugment: A Simple Data Augmentation Method for
    ASR](https://arxiv.org/abs/1904.08779). Note that this method is not optimized to run on TPU and should be run on
    CPU as part of the preprocessing during training.

    Args:
        shape: The shape for which to compute masks. This should be of a tuple of size 2 where
               the first element is the batch size and the second element is the length of the axis to span.
        mask_prob:  The percentage of the whole axis (between 0 and 1) which will be masked. The number of
                    independently generated mask spans of length `mask_length` is computed by
                    `mask_prob*shape[1]/mask_length`. Note that due to overlaps, `mask_prob` is an upper bound and the
                    actual percentage will be smaller.
        mask_length: size of the mask
        min_masks: minimum number of masked spans
        attention_mask: A (right-padded) attention mask which independently shortens the feature axis of
                        each batch dimension.
    r   z&`mask_length` has to be bigger than 0.zO`mask_length` has to be smaller than `sequence_length`, but got `mask_length`: z and `sequence_length`: `c                    sX   t |     }t|}| kr }| d  |k r*t| d  d}|S )z;Given input length, compute how many spans should be maskedr   r   )intr,   )input_lengthnum_masked_spanepsilonrW   rV   rX   sequence_lengthr6   r7   compute_num_masked_span   s   
z6_compute_mask_indices.<locals>.compute_num_masked_spanNr"   c                    s   g | ]} qS r6   r6   .0_)r_   r6   r7   
<listcomp>       z)_compute_mask_indices.<locals>.<listcomp>r$   r   F)replace)r@   nprandomrandr-   r'   detachtolistrangezerosboolchoicerD   lenconcatenateonesr)   appendarraybroadcast_toreshaper,   put_along_axis)rQ   rV   rW   r1   rX   
batch_sizer`   input_lengthsspec_aug_maskspec_aug_mask_idxsmax_num_masked_spanr[   r\   spec_aug_mask_idxdummy_mask_idxoffsetsr6   r]   r7   _compute_mask_indicesq   s\   

r   inputsfilter_widthc                 C   sr   |dks
|d dkrt d|d }| jd |kr| S tjj| ||ddfdd} | d|d d d|f }|S )	z
    Applies a median filter of width `filter_width` along the last dimension of the input.

    The `inputs` tensor is assumed to be 3- or 4-dimensional.
    r   r>   r   z&`filter_width` should be an odd numberr"   reflect)mode.)r@   rQ   r   
functionalr/   unfoldsort)r   r   	pad_widthresultr6   r6   r7   _median_filter   s   r   matrixc                 C   s:  | j \}}tj|d |d ftjdtj }tj|d |d ftjd }d|d< td|d D ]]}td|d D ]S}||d |d f }||d |f }|||d f }	||k rc||	k rc|d}
}n||k rq||	k rq|d}
}n|	d}
}| |d |d f |
 |||f< ||||f< q9q0|j d d }|j d d }d|dddf< d|dddf< g }g }|dks|dkr||d  ||d  |||f dkr|d8 }|d8 }n%|||f dkr|d8 }n|||f dkr|d8 }ntd| d| d	|dks|dkst|ddd
 }t|ddd
 }||fS )z
    Measures similarity between two temporal sequences: the input audio and the output tokens. Used to generate
    token-level timestamps.
    r   rf   r   )r   r   r>   Nz9Internal error in dynamic time warping. Unexpected trace[z, z]. Please file a bug report.r"   )	rQ   rh   rs   float32infrm   rt   RuntimeErrorru   )r   output_lengthr[   costtracejic0c1c2cttext_indicestime_indicesr6   r6   r7   _dynamic_time_warping   sP   
"
 


r   c                       s:   e Zd Zd
dededee f fddZddd	Z  ZS )WhisperPositionalEmbeddingNnum_positionsembedding_dimpadding_idxc                    s   t  || d S N)super__init__)selfr   r   r   	__class__r6   r7   r   4  s   z#WhisperPositionalEmbedding.__init__r   c                 C   s   | j |||jd   S Nr   )weightrQ   )r   rM   past_key_values_lengthr6   r6   r7   forward7  s   z"WhisperPositionalEmbedding.forwardr   )r   )__name__
__module____qualname__rZ   r   r   r   __classcell__r6   r6   r   r7   r   3  s     r   c                       s   e Zd ZdZ					ddededed	ed
ededee f fddZ	de
jdedefddZ					dde
jdee
j deee
j  dee
j dee
j dedee
jee
j eee
j  f fddZ  ZS )WhisperAttentionz=Multi-headed attention from 'Attention Is All You Need' paper        FTN	embed_dim	num_headsdropout
is_decoderbias	is_causalconfigc                    s   t    || _|| _|| _|| | _|| _| j| | jkr*td| j d| d| jd | _|| _	|| _
tj||dd| _tj|||d| _tj|||d| _tj|||d| _d S )Nz;embed_dim must be divisible by num_heads (got `embed_dim`: z and `num_heads`: z).g      Fr   )r   r   r   r   r   head_dimr   r@   scalingr   r   r   Lineark_projv_projq_projout_proj)r   r   r   r   r   r   r   r   r   r6   r7   r   >  s&   



zWhisperAttention.__init__tensorseq_lenbszc                 C   s    | ||| j| jdd S )Nr   r>   )rE   r   r   	transpose
contiguousr   r   r   r   r6   r6   r7   _shape^  s    zWhisperAttention._shapehidden_stateskey_value_statespast_key_valuer1   layer_head_maskoutput_attentionsr=   c                 C   sr  |du}|  \}}	}
| || j }|r.|dur.|d jd |jd kr.|d }|d }nZ|rE| | |d|}| | |d|}nC|durt| | |d|}| | |d|}tj|d |gdd}tj|d |gdd}n| | |d|}| | |d|}| j	r||f}|| j
 d| jf}| ||	|j| }|j| }|j| }| d}t||dd}|  || j
 |	|fkrtd|| j
 |	|f d|   |dur|  |d|	|fkrtd	|d|	|f d|   ||| j
|	|| }||| j
 |	|}tjj|dd}|durL|  | j
fkr1td
| j
f d|   |dddd||| j
|	| }||| j
 |	|}|rc||| j
|	|}||| j
 |	|}nd}tjj|| j| jd}t||}|  || j
 |	| jfkrtd|| j
 |	| jf d|   ||| j
|	| j}|dd}|||	| j}| |}|||fS )#Input shape: Batch x Time x ChannelNr   r>   r   r"   r?   z$Attention weights should be of size 	, but is z!Attention mask should be of size z/Head mask for a single layer should be of size ptraining `attn_output` should be of size )sizer   r   rQ   r   r   r   r(   rF   r   r   r   rE   rw   bmmr   r@   r   r   softmaxr   r   r   r   )r   r   r   r   r1   r   r   is_cross_attentionr   tgt_lenrc   query_states
key_statesvalue_states
proj_shapesrc_lenattn_weightsattn_weights_reshaped
attn_probsattn_outputr6   r6   r7   r   b  s   





"

zWhisperAttention.forward)r   FTFNNNNNF)r   r   r   __doc__rZ   floatro   r   r   r   r(   Tensorr   r   r   r   r6   r6   r   r7   r   ;  sV     r   c                       s   e Zd ZdZ fddZdejdedefddZ									
ddejde	ej de	e
ej  de	ej de	ej dede
eje	ej e	e
ej  f fddZ		dddZdd Z  ZS )WhisperFlashAttention2aJ  
    Whisper flash attention module. This module inherits from `WhisperAttention` as the weights of the module stays
    untouched. The only required change would be on the forward pass where it needs to correctly call the public API of
    flash attention and deal with padding tokens in case the input contains any of them.
    c                    s    t  j|i | t  | _d S r   )r   r   r   _flash_attn_uses_top_left_maskr   argskwargsr   r6   r7   r     s   zWhisperFlashAttention2.__init__r   r   r   c                 C   s   | ||| j| jS r   )rE   r   r   r   r6   r6   r7   _reshape  s   zWhisperFlashAttention2._reshapeNFr   r   r   r1   r   r   r=   c                 C   s&  |rt d|d u}| \}}	}
| | |d|}|r>|d ur>|d jd |jd kr>|d dd}|d dd}nb|rU| | |d|}| | |d|}nK|d ur| | |d|}| | |d|}tj	|d dd|gdd}tj	|d dd|gdd}n| | |d|}| | |d|}| j
r|dd|ddf}|jd }|d ur||d jd 7 }|j}|tjkrt| jdr| jj}n| jjj}td	| d
 ||}||}||}| j|||||	| jd}|||	d}| |}|sd }|||fS )NzCWhisperFlashAttention2 attention does not support output_attentionsr"   r   r>   r   r?   _pre_quantization_dtypezThe input hidden states seems to be silently casted in float32, this might be related to the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in .)r   )r@   r   r   r   rQ   r   r   r   r(   rF   r   r$   r   hasattrr   r   r   loggerwarning_onceto_flash_attention_forwardr   rw   r   )r   r   r   r   r1   r   r   r   r   q_lenrc   r   r   r   
kv_seq_leninput_dtypetarget_dtyper   r   r6   r6   r7   r     s^   
 








zWhisperFlashAttention2.forwardr   c                 C   s   | j s| j}n| jo|dk}|durE|jd }	| |||||\}}}}
}}|\}}|\}}t||||||||||d
}t||
|	|}|S t||||||d}|S )a  
        Calls the forward method of Flash Attention - if the input hidden states contain at least one padding token
        first unpad the input, then computes the attention scores and pad the final attention scores.

        Args:
            query_states (`torch.Tensor`):
                Input query states to be passed to Flash Attention API
            key_states (`torch.Tensor`):
                Input key states to be passed to Flash Attention API
            value_states (`torch.Tensor`):
                Input value states to be passed to Flash Attention API
            attention_mask (`torch.Tensor`):
                The padding mask - corresponds to a tensor of size `(batch_size, seq_len)` where 0 stands for the
                position of padding tokens and 1 for the position of non-padding tokens.
            dropout (`int`, *optional*):
                Attention dropout
            softmax_scale (`float`, *optional*):
                The scaling of QK^T before applying softmax. Default to 1 / sqrt(head_dim)
        r   Nr   )cu_seqlens_qcu_seqlens_kmax_seqlen_qmax_seqlen_k	dropout_psoftmax_scalecausal)r   r   )r   r   rQ   _upad_inputr   r    r   )r   r   r   r   r1   query_lengthr   r   r   ry   	indices_qcu_seq_lensmax_seq_lensr   r   max_seqlen_in_batch_qmax_seqlen_in_batch_kattn_output_unpadr   r6   r6   r7   r   R  s8   

z/WhisperFlashAttention2._flash_attention_forwardc                 C   s   t |\}}}|j\}	}
}}t||	|
 |||}t||	|
 |||}||
kr>t||	|
 | j||}|}|}|}n2|dkr\d}tj|	d tj|jd}|d d }|	d}n|d d | d f }t
||\}}}}||||||f||ffS )Nr   )r$   devicer"   )r8   rQ   r   rw   r   r(   rD   r)   r  squeezer!   )r   query_layer	key_layervalue_layerr1   r   	indices_kr   r  ry   r   num_key_value_headsr   r   r  r   r6   r6   r7   r     s>   z"WhisperFlashAttention2._upad_inputr   )r   N)r   r   r   r   r   r(   r   rZ   r   r   r   ro   r   r   r   r   r6   r6   r   r7   r     s6    
d
<r   c                       s   e Zd Z					ddejdeej deeej  deej deej ded	eejeej eeej  f f fd
dZ  Z	S )WhisperSdpaAttentionNFr   r   r   r1   r   r   r=   c                    s  |s|durt d t j||||||dS |du}| \}}	}
| |}|rB|durB|d jd |jd krB|d }|d }nZ|rY| | |d|}| | 	|d|}nC|dur| | |d|}| | 	|d|}t
j|d |gdd}t
j|d |gdd}n| | |d|}| | 	|d|}| jr||f}| ||	|}t
jjj||||| jr| jnd	| jo|du o|	dkd
}| || j|	| jfkrtd|| j|	| jf d|  |dd}|||	| j}| |}|d|fS )r   Na  WhisperModel is using WhisperSdpaAttention, but `torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True` or `layer_head_mask` not None. Falling back to the manual attention implementation, but specifying the manual implementation will be required from Transformers version v5.0.0 onwards. This warning can be removed using the argument `attn_implementation="eager"` when loading the model.)r   r   r1   r   r   r   r>   r   r"   r?   r   )	attn_maskr   r   r   r   )r   r   r   r   r   r   rQ   r   r   r   r(   rF   r   r   r   scaled_dot_product_attentionr   r   r   r   r   r@   r   rw   r   r   )r   r   r   r   r1   r   r   r   r   r   rc   r   r   r   r   r   r6   r7   r     sh   





zWhisperSdpaAttention.forwardr   )
r   r   r   r(   r   r   r   ro   r   r   r6   r6   r   r7   r    s*    r  )eagerflash_attention_2sdpac                       sL   e Zd Zdef fddZ	ddejdejdejded	ejf
d
dZ  Z	S )WhisperEncoderLayerr   c                    s   t    |j| _t|j | j|j|j|d| _t	
| j| _|j| _t|j | _|j| _t	| j|j| _t	|j| j| _t	
| j| _d S )N)r   r   r   r   )r   r   d_modelr   WHISPER_ATTENTION_CLASSES_attn_implementationencoder_attention_headsattention_dropout	self_attnr   	LayerNormself_attn_layer_normr   r   activation_functionactivation_fnactivation_dropoutr   encoder_ffn_dimfc1fc2final_layer_normr   r   r   r6   r7   r   #  s   
zWhisperEncoderLayer.__init__Fr   r1   r   r   r=   c           
      C   s  |}|  |}| j||||d\}}}tjj|| j| jd}|| }|}| |}| | |}tjj|| j	| jd}| 
|}tjj|| j| jd}|| }|jtjkrvt| sdt| rvt|jjd }tj|| |d}|f}	|r|	|f7 }	|	S )a  
        Args:
            hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
            attention_mask (`torch.FloatTensor`): attention mask of size
                `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
            layer_head_mask (`torch.FloatTensor`): mask for attention heads in a given layer of size
                `(encoder_attention_heads,)`.
            output_attentions (`bool`, *optional*):
                Whether or not to return the attentions tensors of all attention layers. See `attentions` under
                returned tensors for more detail.
        )r   r1   r   r   r   i  )minr,   )r  r  r   r   r   r   r!  r  r  r  r   r$   r(   float16isinfanyisnanfinfor,   clamp)
r   r   r1   r   r   residualr   rc   clamp_valueoutputsr6   r6   r7   r   5  s8   



zWhisperEncoderLayer.forward)F)
r   r   r   r   r   r(   r   ro   r   r   r6   r6   r   r7   r  "  s    r  c                       s   e Zd Zdef fddZ								ddejdeej d	eej d
eej deej deej deeej  dee	 dee	 dejfddZ
  ZS )WhisperDecoderLayerr   c                    s   t    |j| _t|j | j|j|jdd|d| _|j	| _	t
|j | _|j| _t| j| _t|j | j|j|jd|d| _t| j| _t| j|j| _t|j| j| _t| j| _d S )NT)r   r   r   r   r   r   )r   r   r   )r   r   r  r   r  r  decoder_attention_headsr  r  r   r   r  r  r  r   r  r  encoder_attnencoder_attn_layer_normr   decoder_ffn_dimr  r   r!  r"  r   r6   r7   r   j  s2   
zWhisperDecoderLayer.__init__NFTr   r1   encoder_hidden_statesencoder_attention_maskr   cross_attn_layer_head_maskr   r   	use_cacher=   c
                 C   sZ  |}
|  |}|dur|dd nd}| j|||||d\}}}tjj|| j| jd}|
| }d}d}|durk|}
| |}|durH|dd nd}| j||||||d\}}}tjj|| j| jd}|
| }|| }|}
| |}| 	| 
|}tjj|| j| jd}| |}tjj|| j| jd}|
| }|f}|r|||f7 }|	r||f7 }|S )a  
        Args:
            hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
            attention_mask (`torch.FloatTensor`): attention mask of size
                `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
            encoder_hidden_states (`torch.FloatTensor`):
                cross attention input to the layer of shape `(batch, seq_len, embed_dim)`
            encoder_attention_mask (`torch.FloatTensor`): encoder attention mask of size
                `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
            layer_head_mask (`torch.FloatTensor`): mask for attention heads in a given layer of size
                `(encoder_attention_heads,)`.
            cross_attn_layer_head_mask (`torch.FloatTensor`): mask for cross-attention heads in a given layer of
                size `(decoder_attention_heads,)`.
            past_key_value (`Tuple(torch.FloatTensor)`): cached past key and value projection states
            output_attentions (`bool`, *optional*):
                Whether or not to return the attentions tensors of all attention layers. See `attentions` under
                returned tensors for more detail.
        Nr>   )r   r   r1   r   r   r   r   )r   r   r1   r   r   r   )r  r  r   r   r   r   r0  r/  r!  r  r  r  r   )r   r   r1   r2  r3  r   r4  r   r   r5  r*  self_attn_past_key_valueself_attn_weightspresent_key_valuecross_attn_present_key_valuecross_attn_weightscross_attn_past_key_valuer,  r6   r6   r7   r     sT   




zWhisperDecoderLayer.forward)NNNNNNFT)r   r   r   r   r   r(   r   r   r   ro   r   r   r6   r6   r   r7   r-  i  s>     	
r-  c                   @   sD   e Zd ZeZdZdZdZddgZdZ	dZ
dd Zdejfd	d
ZdS )WhisperPreTrainedModelmodelinput_featuresTr  r-  c                 C   s   | j j}t|tjtjfr%|jjjd|d |j	d ur#|j	j
  d S d S t|tjrF|jjjd|d |jd urD|jj|j 
  d S d S t|trnt  |jj}|t|j  W d    d S 1 sgw   Y  d S d S )Nr   )meanstd)r   init_std
isinstancer   r   Conv1dr   datanormal_r   zero_	Embeddingr   WhisperEncoderr(   no_gradembed_positionscopy_rL   rQ   )r   moduler@  rJ  r6   r6   r7   _init_weights  s"   



"z$WhisperPreTrainedModel._init_weightsrz   c                 C   s   |d d d }|S )zH
        Computes the output length of the convolutional layers
        r   r>   r6   )r   rz   r6   r6   r7    _get_feat_extract_output_lengths  s   z7WhisperPreTrainedModel._get_feat_extract_output_lengthsN)r   r   r   r   config_classbase_model_prefixmain_input_namesupports_gradient_checkpointing_no_split_modules_supports_flash_attn_2_supports_sdparM  r(   
LongTensorrN  r6   r6   r6   r7   r<    s    r<  aL  
    This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
    library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
    etc.)

    This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
    Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
    and behavior.

    Parameters:
        config ([`WhisperConfig`]):
            Model configuration class with all the parameters of the model. Initializing with a config file does not
            load the weights associated with the model, only the configuration. Check out the
            [`~PreTrainedModel.from_pretrained`] method to load the model weights.
aN  
    Args:
        input_features (`torch.FloatTensor` of shape `(batch_size, feature_size, sequence_length)`):
            Float values mel features extracted from the raw speech waveform. Raw speech waveform can be obtained by
            loading a `.flac` or `.wav` audio file into an array of type `List[float]` or a `numpy.ndarray`, *e.g.* via
            the soundfile library (`pip install soundfile`). To prepare the array into `input_features`, the
            [`AutoFeatureExtractor`] should be used for extracting the mel features, padding and conversion into a
            tensor of type `torch.FloatTensor`. See [`~WhisperFeatureExtractor.__call__`]
        attention_mask (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
            Mask to avoid performing *SpecAugment* data augmentation on padding token indices. Mask values selected in
            `[0, 1]`:

            - 1 for tokens that are **not masked**,
            - 0 for tokens that are **masked**.

            [What are attention masks?](../glossary#attention-mask)
        decoder_input_ids (`torch.LongTensor` of shape `(batch_size, target_sequence_length)`, *optional*):
            Indices of decoder input sequence tokens in the vocabulary.

            Indices can be obtained using [`WhisperTokenizer`]. See [`PreTrainedTokenizer.encode`] and
            [`PreTrainedTokenizer.__call__`] for details.

            [What are decoder input IDs?](../glossary#decoder-input-ids)

            Whisper uses the `decoder_start_token_id` as the starting token for `decoder_input_ids` generation. If
            `past_key_values` is used, optionally only the last `decoder_input_ids` have to be input (see
            `past_key_values`).
        decoder_attention_mask (`torch.LongTensor` of shape `(batch_size, target_sequence_length)`, *optional*):
            Default behavior: generate a tensor that ignores pad tokens in `decoder_input_ids`. Causal mask will also
            be used by default.

            If you want to change padding behavior, you should read
            [`modeling_whisper._prepare_decoder_attention_mask`] and modify to your needs. See diagram 1 in [the BART
            paper](https://arxiv.org/abs/1910.13461) for more information on the default strategy.
        head_mask (`torch.Tensor` of shape `(encoder_layers, encoder_attention_heads)`, *optional*):
            Mask to nullify selected heads of the attention modules in the encoder. Mask values selected in `[0, 1]`:

            - 1 indicates the head is **not masked**,
            - 0 indicates the head is **masked**.

        decoder_head_mask (`torch.Tensor` of shape `(decoder_layers, decoder_attention_heads)`, *optional*):
            Mask to nullify selected heads of the attention modules in the decoder. Mask values selected in `[0, 1]`:

            - 1 indicates the head is **not masked**,
            - 0 indicates the head is **masked**.

        cross_attn_head_mask (`torch.Tensor` of shape `(decoder_layers, decoder_attention_heads)`, *optional*):
            Mask to nullify selected heads of the cross-attention modules. Mask values selected in `[0, 1]`:

            - 1 indicates the head is **not masked**,
            - 0 indicates the head is **masked**.

        encoder_outputs (`tuple(tuple(torch.FloatTensor)`, *optional*):
            Tuple consists of (`last_hidden_state`, *optional*: `hidden_states`, *optional*: `attentions`)
            `last_hidden_state` of shape `(batch_size, sequence_length, hidden_size)`, *optional*) is a sequence of
            hidden-states at the output of the last layer of the encoder. Used in the cross-attention of the decoder.
        past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
            Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of shape
            `(batch_size, num_heads, sequence_length, embed_size_per_head)`) and 2 additional tensors of shape
            `(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)`.

            Contains pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
            blocks) that can be used (see `past_key_values` input) to speed up sequential decoding.

            If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that
            don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all
            `decoder_input_ids` of shape `(batch_size, sequence_length)`.
        decoder_inputs_embeds (`torch.FloatTensor` of shape `(batch_size, target_sequence_length, hidden_size)`, *optional*):
            Optionally, instead of passing `decoder_input_ids` you can choose to directly pass an embedded
            representation. If `past_key_values` is used, optionally only the last `decoder_inputs_embeds` have to be
            input (see `past_key_values`). This is useful if you want more control over how to convert
            `decoder_input_ids` indices into associated vectors than the model's internal embedding lookup matrix.
        use_cache (`bool`, *optional*):
            If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
            `past_key_values`).
        output_attentions (`bool`, *optional*):
            Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
            tensors for more detail.
        output_hidden_states (`bool`, *optional*):
            Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
            more detail.
        return_dict (`bool`, *optional*):
            Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
aY  
    Args:
        input_features (`torch.FloatTensor` of shape `(batch_size, feature_size, sequence_length)`):
            Float values mel features extracted from the raw speech waveform. Raw speech waveform can be obtained by
            loading a `.flac` or `.wav` audio file into an array of type `List[float]` or a `numpy.ndarray`, *e.g.* via
            the soundfile library (`pip install soundfile`). To prepare the array into `input_features`, the
            [`AutoFeatureExtractor`] should be used for extracting the mel features, padding and conversion into a
            tensor of type `torch.FloatTensor`. See [`~WhisperFeatureExtractor.__call__`]
        head_mask (`torch.Tensor` of shape `(encoder_layers, encoder_attention_heads)`, *optional*):
            Mask to nullify selected heads of the attention modules in the encoder. Mask values selected in `[0, 1]`:

            - 1 indicates the head is **not masked**,
            - 0 indicates the head is **masked**.
        encoder_outputs (`tuple(tuple(torch.FloatTensor)`, *optional*):
            Tuple consists of (`last_hidden_state`, *optional*: `hidden_states`, *optional*: `attentions`)
            `last_hidden_state` of shape `(batch_size, sequence_length, hidden_size)`, *optional*) is a sequence of
            hidden-states at the output of the last layer of the encoder.
        output_attentions (`bool`, *optional*):
            Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
            tensors for more detail.
        output_hidden_states (`bool`, *optional*):
            Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
            more detail.
        return_dict (`bool`, *optional*):
            Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
c                       sb   e Zd ZdZdef fddZdd Zdejfdd	Z	d
ejfddZ
					dddZ  ZS )rH  z
    Transformer encoder consisting of *config.encoder_layers* self attention layers. Each layer is a
    [`WhisperEncoderLayer`].

    Args:
        config: WhisperConfig
    r   c                    s   t     j| _ j| _ j} j| _ j| _ j	| _	 j
r%t|nd| _tj| j|ddd| _tj||dddd| _t| j	|| _| jd t fdd	t jD | _t j| _d| _|   d S )
N      ?r   r   )kernel_sizepaddingr>   )rX  striderY  Fc                       g | ]}t  qS r6   )r  ra   r   r6   r7   rd         z+WhisperEncoder.__init__.<locals>.<listcomp>)r   r   r   encoder_layerdrop	layerdropr  num_mel_binsrN   r   max_source_positionsscale_embeddingrA   sqrtembed_scaler   rC  conv1conv2rG  rJ  requires_grad_
ModuleListrm   encoder_layerslayersr  
layer_normgradient_checkpointing	post_init)r   r   r   r   r\  r7   r     s     zWhisperEncoder.__init__c                 C   s   |   D ]}d|_qd| _d S NF)
parametersrequires_grad_requires_grad)r   paramr6   r6   r7   _freeze_parameters  s   
z!WhisperEncoder._freeze_parametersr=   c                 C      | j S r   re  r   r6   r6   r7   get_input_embeddings     z#WhisperEncoder.get_input_embeddingsvaluec                 C   
   || _ d S r   ru  r   ry  r6   r6   r7   set_input_embeddings     
z#WhisperEncoder.set_input_embeddingsNc                 C   s>  | j j| jjd  | jjd  }|jd |kr(td| d|jd  d| d|dur.|n| j j}|dur8|n| j j}|durB|n| j j	}t
j| |}t
j| |}|ddd	}| jj}	||	 }
t
jj|
| j| jd
}
|rvdnd}|r|dnd}|dur| d t| jksJ dt| j d| d  dt| jD ]W\}}|r||
f }d}| jrtg }|| jk rd}|rd}n-| jr| jr| |j|
d|dur|| nd|}n||
d|dur|| nd|d}|d }
|r||d	 f }q| |
}
|r	||
f }|stdd |
||fD S t|
||dS )aK  
        Args:
            input_features (`torch.LongTensor` of shape `(batch_size, feature_size, sequence_length)`):
                Float values of mel features extracted from the raw speech waveform. Raw speech waveform can be
                obtained by loading a `.flac` or `.wav` audio file into an array of type `List[float]` or a
                `numpy.ndarray`, *e.g.* via the soundfile library (`pip install soundfile`). To prepare the array into
                `input_features`, the [`AutoFeatureExtractor`] should be used for extracting the mel features, padding
                and conversion into a tensor of type `torch.FloatTensor`. See [`~WhisperFeatureExtractor.__call__`]
            attention_mask (`torch.Tensor`)`, *optional*):
                Whisper does not support masking of the `input_features`, this argument is preserved for compatibility,
                but it is not used. By default the silence in the input log mel spectrogram are ignored.
            head_mask (`torch.Tensor` of shape `(encoder_layers, encoder_attention_heads)`, *optional*):
                Mask to nullify selected heads of the attention modules. Mask values selected in `[0, 1]`:

                - 1 indicates the head is **not masked**,
                - 0 indicates the head is **masked**.
            output_attentions (`bool`, *optional*):
                Whether or not to return the attentions tensors of all attention layers. See `attentions` under
                returned tensors for more detail.
            output_hidden_states (`bool`, *optional*):
                Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors
                for more detail.
            return_dict (`bool`, *optional*):
                Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
        r   r"   z7Whisper expects the mel input features to be of length z, but found z-. Make sure to pad the input mel features to r   Nr>   r   r   r6   z&The head_mask should be specified for  layers, but it is for FT)NN)r   r   c                 s       | ]	}|d ur|V  qd S r   r6   rb   vr6   r6   r7   	<genexpr>  s    z)WhisperEncoder.forward.<locals>.<genexpr>last_hidden_stater   
attentions)r   ra  re  rZ  rf  rQ   r@   r   output_hidden_statesuse_return_dictr   r   gelupermuterJ  r   r   r   r   rq   rj  	enumerater(   rj   r_  rl  _gradient_checkpointing_func__call__rk  tupler   )r   r>  r1   	head_maskr   r  return_dictexpected_seq_lengthinputs_embeds	embed_posr   encoder_statesall_attentionsidxencoder_layerto_dropdropout_probabilitylayer_outputsr6   r6   r7   r     sv    #





zWhisperEncoder.forward)NNNNN)r   r   r   r   r   r   rs  r   Modulerw  r|  r   r   r6   r6   r   r7   rH    s    rH  c                       sZ   e Zd ZdZdZdef fddZdd Zdd	 Z	
	
	
	
	
	
	
	
	
	
	
dddZ	  Z
S )WhisperDecoderz
    Transformer decoder consisting of *config.decoder_layers* layers. Each layer is a [`WhisperDecoderLayer`]

    Args:
        config: WhisperConfig
    rM   r   c                    s   t     j| _ j| _ j| _ j| _ j| _ j	r#t
 jnd| _t j j| j| _t| j j| _t fddt jD | _ jdk| _ jdk| _t j| _d| _|   d S )NrW  c                    r[  r6   )r-  ra   r\  r6   r7   rd   2  r]  z+WhisperDecoder.__init__.<locals>.<listcomp>r  r  F)r   r   r   decoder_layerdropr_  rN   r   max_target_positionsra  rb  rA   rc  r  rd  r   rG  
vocab_sizeembed_tokensr   rJ  rh  rm   decoder_layersrj  r  _use_flash_attention_2	_use_sdpar  rk  rl  rm  r"  r   r\  r7   r   &  s    zWhisperDecoder.__init__c                 C   rt  r   r  rv  r6   r6   r7   rw  <  rx  z#WhisperDecoder.get_input_embeddingsc                 C   rz  r   r  r{  r6   r6   r7   r|  ?  r}  z#WhisperDecoder.set_input_embeddingsNc                 C   s  |	dur|	n| j j}	|
dur|
n| j j}
|dur|n| j j}|dur$|n| j j}|dur4|dur4td|durE| }|d|d }n|durR| dd }ntd|durc|d d jd nd}|du rn| 	|}| j
r~|dur{d|v r{|nd}n| jr|du r|	st||||}nt||||}|dur| j||d}n| j||d}|| }tjj|| j| jd}| jr| jr|rtd	 d
}|
rdnd}|	rdnd}|	r|durdnd}|rdnd}t||gddgD ]*\}}|dur| d t| jksJ d| dt| j d| d  dqt| jD ]\}}|
r(||f7 }| jr9tg }|| jk r9q|durB|| nd}| jrn| jrn| |j|||d|dur]|| nd|durg|| ndd|	|
}n|||||dur{|| nd|dur|| nd||	|d}|d }|r|||	rdnd f7 }|	r||d f7 }|dur||d f7 }q| |}|
r||f7 }|r|nd}|st dd |||||fD S t!|||||dS )aM  
        Args:
            input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
                Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you
                provide it.

                Indices can be obtained using [`WhisperTokenizer`]. See [`PreTrainedTokenizer.encode`] and
                [`PreTrainedTokenizer.__call__`] for details.

                [What are input IDs?](../glossary#input-ids)
            attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
                Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:

                - 1 for tokens that are **not masked**,
                - 0 for tokens that are **masked**.

                [What are attention masks?](../glossary#attention-mask)
            encoder_hidden_states (`torch.FloatTensor` of shape `(batch_size, encoder_sequence_length, hidden_size)`, *optional*):
                Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention
                of the decoder.
            head_mask (`torch.Tensor` of shape `(decoder_layers, decoder_attention_heads)`, *optional*):
                Mask to nullify selected heads of the attention modules. Mask values selected in `[0, 1]`:

                - 1 indicates the head is **not masked**,
                - 0 indicates the head is **masked**.

            cross_attn_head_mask (`torch.Tensor` of shape `(decoder_layers, decoder_attention_heads)`, *optional*):
                Mask to nullify selected heads of the attention modules in encoder to avoid performing cross-attention
                on hidden heads. Mask values selected in `[0, 1]`:

                - 1 indicates the head is **not masked**,
                - 0 indicates the head is **masked**.

            past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
                Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
                shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`) and 2 additional tensors of
                shape `(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)`.

                Contains pre-computed hidden-states (key and values in the self-attention blocks and in the
                cross-attention blocks) that can be used (see `past_key_values` input) to speed up sequential decoding.

                If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those
                that don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of
                all `decoder_input_ids` of shape `(batch_size, sequence_length)`.
            inputs_embeds (`torch.FloatTensor` of
                shape `(batch_size, sequence_length, hidden_size)`, *optional*): Optionally, instead of passing
                `input_ids` you can choose to directly pass an embedded representation. This is useful if you want more
                control over how to convert `input_ids` indices into associated vectors than the model's internal
                embedding lookup matrix.
            output_attentions (`bool`, *optional*):
                Whether or not to return the attentions tensors of all attention layers. See `attentions` under
                returned tensors for more detail.
            output_hidden_states (`bool`, *optional*):
                Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors
                for more detail.
            return_dict (`bool`, *optional*):
                Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
        NzTYou cannot specify both decoder_input_ids and decoder_inputs_embeds at the same timer"   zEYou have to specify either decoder_input_ids or decoder_inputs_embedsr   r>   )r   r   z^`use_cache = True` is incompatible with gradient checkpointing. Setting `use_cache = False`...Fr6   r  cross_attn_head_maskThe `z` should be specified for r~  r   )r1   r2  r   r4  r   r   r5  r   r   c                 s   r  r   r6   r  r6   r6   r7   r    s    z)WhisperDecoder.forward.<locals>.<genexpr>)r  past_key_valuesr   r  cross_attentions)"r   r   r  r5  r  r@   r   rE   rQ   r  r  r  r   r
   rJ  r   r   r   r   rl  r   r   ziprq   rj  r  r(   rj   r_  r  r  rk  r  r   )r   rM   r1   r2  r  r  r  r  r5  r   r  r  input_shaper   	positionsr   all_hidden_statesall_self_attnsall_cross_attentionsnext_decoder_cacher  	mask_namer  decoder_layerr  r   r  
next_cacher6   r6   r7   r   B  s   H







zWhisperDecoder.forward)NNNNNNNNNNN)r   r   r   r   rQ  r   r   rw  r|  r   r   r6   r6   r   r7   r    s$    r  zUThe bare Whisper Model outputting raw hidden-states without any specific head on top.c                #       sN  e Zd Zdef fddZdd Zdd Zdd	 Zd
d Zdd Z		d#de
jdee
j fddZeeeeed														d$dee
j dee
j dee
j dee
j dee
j dee
j dee
j deeee
j   deeee
j   deee
j  dee dee dee dee d eee
j ef fd!d"Z  ZS )%WhisperModelr   c                    s,   t  | t|| _t|| _|   d S r   )r   r   rH  encoderr  decoderrm  r"  r   r6   r7   r     s   

zWhisperModel.__init__c                 C      | j jS r   r  r  rv  r6   r6   r7   rw       z!WhisperModel.get_input_embeddingsc                 C      || j _d S r   r  r{  r6   r6   r7   r|  !     z!WhisperModel.set_input_embeddingsc                 C   rt  r   )r  rv  r6   r6   r7   get_encoder$  rx  zWhisperModel.get_encoderc                 C   rt  r   r  rv  r6   r6   r7   get_decoder'  rx  zWhisperModel.get_decoderc                 C      | j   dS z
        Calling this function will disable the gradient computation for the Whisper encoder so that its parameters will
        not be updated during training.
        Nr  rs  rv  r6   r6   r7   freeze_encoder*     zWhisperModel.freeze_encoderNr>  r1   c                 C   s   t | jdds	|S | \}}}| jjdkrE| jrEt||f| jj| jj|| jjd}tj	||j
tjd}|dddf d|d}d||< | jjdkrl| jrlt||f| jj| jj| jjd}tj	||j
tjd}d||< |S )	z
        Masks extracted features along time axis and/or along feature axis according to
        [SpecAugment](https://arxiv.org/abs/1904.08779).
        apply_spec_augmentTr   )rV   rW   r1   rX   )r  r$   Nr"   )rV   rW   rX   )getattrr   r   mask_time_probr   r   mask_time_lengthmask_time_min_masksr(   r   r  ro   expandmask_feature_probmask_feature_lengthmask_feature_min_masks)r   r>  r1   ry   hidden_sizer_   mask_time_indicesmask_feature_indicesr6   r6   r7   _mask_input_features1  s0   z!WhisperModel._mask_input_featuresoutput_typerO  decoder_input_idsdecoder_attention_maskr  decoder_head_maskr  encoder_outputsr  decoder_inputs_embedsr5  r   r  r  r=   c                 C   s  |dur|n| j j}|dur|n| j j}|dur|n| j j}|dur$|n| j j}|du r>| j||d}| j|||||d}n$|rbt|tsbt|d t	|dkrS|d ndt	|dkr^|d ndd}| j
|||d |||	|
||||d}|sz|| S t|j|j|j|j|j|j|j|jd	S )
a{  
        Returns:

        Example:
         ```python
         >>> import torch
         >>> from transformers import AutoFeatureExtractor, WhisperModel
         >>> from datasets import load_dataset

         >>> model = WhisperModel.from_pretrained("openai/whisper-base")
         >>> feature_extractor = AutoFeatureExtractor.from_pretrained("openai/whisper-base")
         >>> ds = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation")
         >>> inputs = feature_extractor(ds[0]["audio"]["array"], return_tensors="pt")
         >>> input_features = inputs.input_features
         >>> decoder_input_ids = torch.tensor([[1, 1]]) * model.config.decoder_start_token_id
         >>> last_hidden_state = model(input_features, decoder_input_ids=decoder_input_ids).last_hidden_state
         >>> list(last_hidden_state.shape)
         [1, 2, 512]
         ```N)r1   r  r   r  r  r   r   r>   r  rM   r1   r2  r  r  r  r  r5  r   r  r  )r  r  decoder_hidden_statesdecoder_attentionsr  encoder_last_hidden_stater2  encoder_attentions)r   r   r  r5  r  r  r  rB  r   rq   r  r   r  r  r   r  r  )r   r>  r1   r  r  r  r  r  r  r  r  r5  r   r  r  decoder_outputsr6   r6   r7   r   \  sZ   &zWhisperModel.forwardr   )NNNNNNNNNNNNNN)r   r   r   r   r   rw  r|  r  r  r  r(   FloatTensorr   rV  r  r   WHISPER_INPUTS_DOCSTRINGr   r   _CONFIG_FOR_DOCr   r   ro   r   r   r   r6   r6   r   r7   r    sx    

+
	
r  z^The Whisper Model with a language modeling head. Can be used for automatic speech recognition.c                %       s  e Zd ZdZdgZdef fddZdd Zdd	 Zd
d Z	dd Z
dejfddZdd Zeeeeed															d8deej deej deej deej deej deej deej deeeej   deeeej   deeej  deej d ee d!ee d"ee d#ee deeej ef f d$d%Z						&								&		'	d9deej d(eej d)ee d*ee d+edeej d,ed-ee f fd.d/Zed0d1 Z 				d:d2d3Z!ed4d5 Z"d;d6d7Z#  Z$S )<WhisperForConditionalGenerationr=  proj_out.weightr   c                    s8   t  | t|| _tj|j|jdd| _| 	  d S NFr   )
r   r   r  r=  r   r   r  r  proj_outrm  r"  r   r6   r7   r     s   
z(WhisperForConditionalGeneration.__init__c                 C   
   | j  S r   )r=  r  rv  r6   r6   r7   r    r}  z+WhisperForConditionalGeneration.get_encoderc                 C   r  r   )r=  r  rv  r6   r6   r7   r    r}  z+WhisperForConditionalGeneration.get_decoderc                 C   rt  r   r  rv  r6   r6   r7   get_output_embeddings  rx  z5WhisperForConditionalGeneration.get_output_embeddingsc                 C   rz  r   r  r   new_embeddingsr6   r6   r7   set_output_embeddings  r}  z5WhisperForConditionalGeneration.set_output_embeddingsr=   c                 C   r  r   r=  rw  rv  r6   r6   r7   rw    r}  z4WhisperForConditionalGeneration.get_input_embeddingsc                 C   s   | j j  dS r  )r=  r  rs  rv  r6   r6   r7   r    s   z.WhisperForConditionalGeneration.freeze_encoderr  Nr>  r1   r  r  r  r  r  r  r  r  labelsr5  r   r  r  c                 C   s  |dur|n| j j}|dur |du r |
du r t|| j j| j j}| j|||||||||	|
||||d}| |d }d}|durWt }||j	}||
d| j j|d}|sm|f|dd  }|durk|f| S |S t|||j|j|j|j|j|j|jd	S )a5  
        labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
            Labels for computing the language modeling loss. Indices should either be in `[0, ..., config.vocab_size]`
            or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored (masked), the loss is
            only computed for the tokens with labels in `[0, ..., config.vocab_size]`.

        Returns:

        Example:

        ```python
        >>> import torch
        >>> from transformers import AutoProcessor, WhisperForConditionalGeneration
        >>> from datasets import load_dataset

        >>> processor = AutoProcessor.from_pretrained("openai/whisper-tiny.en")
        >>> model = WhisperForConditionalGeneration.from_pretrained("openai/whisper-tiny.en")

        >>> ds = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation")

        >>> inputs = processor(ds[0]["audio"]["array"], return_tensors="pt")
        >>> input_features = inputs.input_features

        >>> generated_ids = model.generate(inputs=input_features)

        >>> transcription = processor.batch_decode(generated_ids, skip_special_tokens=True)[0]
        >>> transcription
        ' Mr. Quilter is the apostle of the middle classes, and we are glad to welcome his gospel.'
        ```N)r1   r  r  r  r  r  r  r  r  r5  r   r  r  r   r"   r   )	losslogitsr  r  r  r  r  r2  r  )r   r  rU   rN   rO   r=  r  r   r   r  rE   r  rw   r   r  r  r  r  r  r2  r  )r   r>  r1   r  r  r  r  r  r  r  r  r  r5  r   r  r  r,  	lm_logitsr  loss_fctoutputr6   r6   r7   r     sT   1z'WhisperForConditionalGeneration.forwardF{Gz?
prompt_idsnum_segment_framesreturn_token_timestampsreturn_segmentstime_precisionreturn_dict_in_generatec           ;         s6
  d|v r| d}tdt |dur|n| jj}|du r#t| j}| jj	j
jd | jj	jjd  }|du r=|| jj }|durG|jd }n"d|v ret|d trY|d d jn|d j}|d | }ntd||k}|d	u r~t|d
sztd||_n|s|du rtdt|d
stdtd d	|_nd|_|
durt|dstd|
|_t|dr|js|dus|	durtd|	durt|dstd|	 }	|	|_|durt|dstd||_d}t| jdr| jjdur| jj}nt| jdr| jjdur| jj}n|dd}|dus%|	dus%|du r|durg }t|dr|j|j v r:|j}nB|jt v rLdt|j  d}n0|jt  v r\d|j d}n t!|jdk}td|j d|rrt"t  nt"t  d|#d|j| f n|#d t|d r|jt$v r|#d|j%|j f ntd!|j d"t$ d#t|dr|#d|j%d$ f t|d
r|js|r|d d d nd}|#||j&f |dur||_|durv|d%durtd&|' }|^}}|| jj( d d d }|)d%|i |d'ddurR|d'  t!|7  < |d' | jj(krRtd(t!| d)|d' t!|  d*|d'  d+| jj( d,| jj( d| ddp[|j}g ||j*d-d. |D }d/d. t+|D }||_|rd	|d0< d	}t,|d dd1krt-d2 t|d3std4|d5dur| d5|_.|jd	u rt| jdr| jjr|jd d nd}|| jj&kr|jdd }t!|dkrdn||_t/|g}|du r|n|| }|rt0 j1||||||fd6|i|} |rt|d3rt,|d5d}!| j2| |j3|!d7| d8< | S |s$|r$td9| jj&d }"|jd }#|#dkr=|du r=td:|#dkrW|4d5 6t7j8}$t7j9|#ft7j8d;}%nt7j:d<t7j8d;| }$t7j9d<t7j8d;}%d=d. t;|#D }&t"t;|#}'|# }(})|%|$k < r|(})g }*t;|)D ]4}+|'|+ },|%|, |$|, kr|+|(|)  }-|(d8 }(t7j=|d|- ||-d d gdd>}q|*#|, q|*}'|%| | }.|$|% j>|d?}/g }0t;|(D ]9}+|'|+ },||+|+d dd|%|, |%|, |/|,  f }1|1jd |k r	t?j@|1d||1jd  fd@}1|0#|1 qt7j=|0dd>}0t0 j1|0|||||fd6|i| |rBt|d3rBt,|d5d}!| j2 |j3|!d7 d8< |r^ dA }2 fdBd.t;tAtB   CdD  n }2t+|2D ]^\}+}3|'|+ },|%|, | |$|, k }4|4r|3d | jjDkr|3dd }3|3d | jjEkr|3| jjEk4 }5|3d|5  }3| jF|3 |.|"|/|(|||,|+dC
\}6}7|&|,  |67  < |%|,  |77  < qd|%|$k < sg }8d}9|&D ]}:|8#t7j=dDd. |:D dd> tG|9t!|8d }9qt;|#D ]}+t?j@|8|+ d|9t!|8|+  f| jjEdE|8|+< qt7jH|8dd>}8|r|8|&dFS |8S )Ga+  
        Transcribes or translates passed mel input features to a sequence of token ids.

        <Tip warning={true}>

        Most generation-controlling parameters are set in `generation_config` which, if not passed, will be set to the
        model's default generation configuration. You can override any `generation_config` by passing the corresponding
        parameters to generate(), e.g. `.generate(inputs, num_beams=4, do_sample=True)`.

        For an overview of generation strategies and code examples, check out the [following
        guide](./generation_strategies).

        </Tip>

        Parameters:
            inputs (`torch.Tensor` of varying shape depending on the modality, *optional*):
                The sequence used as a prompt for the generation or as model inputs to the encoder. If `None` the
                method initializes it with `bos_token_id` and a batch size of 1. For decoder-only models `inputs`
                should of in the format of `input_ids`. For encoder-decoder models *inputs* can represent any of
                `input_ids`, `input_values`, `input_features`, or `pixel_values`.
            generation_config (`~generation.GenerationConfig`, *optional*):
                The generation configuration to be used as base parametrization for the generation call. `**kwargs`
                passed to generate matching the attributes of `generation_config` will override them. If
                `generation_config` is not provided, the default will be used, which had the following loading
                priority: 1) from the `generation_config.json` model file, if it exists; 2) from the model
                configuration. Please note that unspecified parameters will inherit [`~generation.GenerationConfig`]'s
                default values, whose documentation should be checked to parameterize generation.
            logits_processor (`LogitsProcessorList`, *optional*):
                Custom logits processors that complement the default logits processors built from arguments and
                generation config. If a logit processor is passed that is already created with the arguments or a
                generation config an error is thrown. This feature is intended for advanced users.
            stopping_criteria (`StoppingCriteriaList`, *optional*):
                Custom stopping criteria that complement the default stopping criteria built from arguments and a
                generation config. If a stopping criteria is passed that is already created with the arguments or a
                generation config an error is thrown. This feature is intended for advanced users.
            prefix_allowed_tokens_fn (`Callable[[int, torch.Tensor], List[int]]`, *optional*):
                If provided, this function constraints the beam search to allowed tokens only at each step. If not
                provided no constraint is applied. This function takes 2 arguments: the batch ID `batch_id` and
                `input_ids`. It has to return a list with the allowed tokens for the next generation step conditioned
                on the batch ID `batch_id` and the previously generated tokens `inputs_ids`. This argument is useful
                for constrained generation conditioned on the prefix, as described in [Autoregressive Entity
                Retrieval](https://arxiv.org/abs/2010.00904).
            synced_gpus (`bool`, *optional*, defaults to `False`):
                Whether to continue running the while loop until max_length (needed for ZeRO stage 3)
            return_timestamps (`bool`, *optional*):
                Whether to return the timestamps with the text. This enables the `WhisperTimestampsLogitsProcessor`.
            task (`str`, *optional*):
                Task to use for generation, either "translate" or "transcribe". The `model.config.forced_decoder_ids`
                will be updated accordingly.
            language (`str`, *optional*):
                Language token to use for generation, can be either in the form of `<|en|>`, `en` or `english`. You can
                find all the possible language tokens in the `model.generation_config.lang_to_id` dictionary.
            is_multilingual (`bool`, *optional*):
                Whether or not the model is multilingual.
            prompt_ids (`torch.Tensor`, *optional*):
                Rank-1 tensor of token IDs created by passing text to [`~WhisperProcessor.get_prompt_ids`] that is
                provided as a prompt to each chunk. This can be used to provide or "prompt-engineer" a context for
                transcription, e.g. custom vocabularies or proper nouns to make it more likely to predict those words
                correctly. It cannot be used in conjunction with `decoder_start_token_id` as it overwrites this value.
            return_token_timestamps (`bool`, *optional*):
                Whether to return token-level timestamps with the text. This can be used with or without the
                `return_timestamps` option. To get word-level timestamps, use the tokenizer to group the tokens into
                words.
            return_segments (`bool`, *optional*, defaults to `False`):
                Whether to additionally return a list of all segments. Note that this option can only be enabled
                when doing long-form transcription.
            attention_mask (`torch.Tensor`, *optional*):
                `attention_mask` needs to be passed when doing long-form transcription using a batch size > 1.
            time_precision (`int`, *optional*, defaults to 0.02):
                The duration of output token in seconds. *E.g.* 0.02 means that a generated token on average accounts
                for 20 ms.
            return_dict_in_generate (`bool`, *optional*, defaults to `False`):
                Whether or not to return a [`~utils.ModelOutput`] instead of just returning the generated tokens.
                Note that when doing long-form transcription, `return_dict_in_generate` can only be enabled when
                `return_segments` is set True. In this case the generation outputs of each segment is added to each
                segment.
            kwargs (`Dict[str, Any]`, *optional*):
                Ad hoc parametrization of `generate_config` and/or additional model-specific kwargs that will be
                forwarded to the `forward` function of the model. If the model is an encoder-decoder model, encoder
                specific kwargs should not be prefixed and decoder specific kwargs should be prefixed with *decoder_*.

        Return:
            [`~utils.ModelOutput`] or `torch.LongTensor` or `Dict[str, Any]`: A [`~utils.ModelOutput`] (if `return_dict_in_generate=True`
            or when `config.return_dict_in_generate=True`) or a `torch.FloatTensor` or a dict of segments when `return_segments=True`.

                If the passed input is > 30 seconds / > 3000 mel input features and `return_segments=True` then a dictionary of generated sequence ids, called `sequences` and a list of each generated segment is returned.

                else if the passed input is <= 30 seconds / >= 3000 mel input features, the possible [`~utils.ModelOutput`] types are:

                    - [`~generation.GreedySearchEncoderDecoderOutput`],
                    - [`~generation.SampleEncoderDecoderOutput`],
                    - [`~generation.BeamSearchEncoderDecoderOutput`],
                    - [`~generation.BeamSampleEncoderDecoderOutput`]

                else only the generated output sequence ids are returned.

        Example:

        - *Longform transcription*: To transcribe or translate audios longer than 30 seconds, process the audio files without truncation and pass all mel features at once to generate.

        ```python
        >>> import torch
        >>> from transformers import AutoProcessor, WhisperForConditionalGeneration
        >>> from datasets import load_dataset, Audio

        >>> processor = AutoProcessor.from_pretrained("openai/whisper-tiny.en")
        >>> model = WhisperForConditionalGeneration.from_pretrained("openai/whisper-tiny.en")
        >>> model.cuda()

        >>> # load audios > 30 seconds
        >>> ds = load_dataset("distil-whisper/meanwhile", "default")["test"]
        >>> # resample to 16kHz
        >>> ds = ds.cast_column("audio", Audio(sampling_rate=16000))
        >>> # take first 8 audios and retrieve array
        >>> audio = ds[:8]["audio"]
        >>> audio = [x["array"] for x in audio]

        >>> # make sure to NOT truncate the input audio, to return the `attention_mask` and to pad to the longest audio
        >>> inputs = processor(audio, return_tensors="pt", truncation=False, padding="longest", return_attention_mask=True, sampling_rate=16_000)
        >>> inputs = inputs.to("cuda", torch.float32)

        >>> # transcribe audio to ids
        >>> generated_ids = model.generate(**inputs)

        >>> transcription = processor.batch_decode(generated_ids, skip_special_tokens=True)
        >>> transcription[0]
        ' Folks, if you watch the show, you know, I spent a lot of time right over there. Patiently and astutely scrutinizing the boxwood and mahogany chest set of the day's biggest stories developing the central headline pawns, definitely maneuvering an oso topical night to F6, fainting a classic Sicilian, nade door variation on the news, all the while seeing eight moves deep and patiently marshalling the latest press releases into a fisher's shows in Lip Nitsky attack that culminates in the elegant lethal slow-played, all-passant checkmate that is my nightly monologue. But sometimes, sometimes, folks, I. CHEERING AND APPLAUSE Sometimes I startle away, cubside down in the monkey bars of a condemned playground on a super fun site. Get all hept up on goofballs. Rummage that were discarded tag bag of defective toys. Yank out a fist bowl of disembodied doll limbs, toss them on a stained kid's place mat from a defunct dennies. set up a table inside a rusty cargo container down by the Wharf and challenged toothless drifters to the godless bughouse blitz of tournament that is my segment. Meanwhile!'
        ```

        - *Shortform transcription*: If passed mel input features are < 30 seconds, the whole audio will be transcribed with a single call to generate.

        ```python
        >>> import torch
        >>> from transformers import AutoProcessor, WhisperForConditionalGeneration
        >>> from datasets import load_dataset

        >>> processor = AutoProcessor.from_pretrained("openai/whisper-tiny.en")
        >>> model = WhisperForConditionalGeneration.from_pretrained("openai/whisper-tiny.en")

        >>> ds = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation")

        >>> inputs = processor(ds[0]["audio"]["array"], return_tensors="pt")
        >>> input_features = inputs.input_features

        >>> generated_ids = model.generate(inputs=input_features)

        >>> transcription = processor.batch_decode(generated_ids, skip_special_tokens=True)[0]
        >>> transcription
        ' Mr. Quilter is the apostle of the middle classes, and we are glad to welcome his gospel.'
        ```

        r   zXThe input name `inputs` is deprecated. Please make sure to use `input_features` instead.Nr   r"   r  r   zPMake sure to provide either `input_features` or `encoder_outputs` to `generate`.Tno_timestamps_token_idad  You are trying to return timestamps, but the generation config is not properly set. Make sure to initialize the generation config with the correct attributes that are needed such as `no_timestamps_token_id`. For more details on how to generate the approtiate config, refer to https://github.com/huggingface/transformers/issues/21878#issuecomment-1451902363Fa  You have passed more than 3000 mel input features (> 30 seconds) which automatically enables long-form generation which requires the model to predict timestamp tokens. Please either pass `return_timestamps=True` or make sure to pass no more than 3000 mel input features.a  You have passed more than 3000 mel input features (> 30 seconds) which automatically enables long-form generation which requires the generation config to have `no_timestamps_token_id` correctly. Make sure to initialize the generation config with the correct attributes that are needed such as `no_timestamps_token_id`. For more details on how to generate the approtiate config, refer to https://github.com/huggingface/transformers/issues/21878#issuecomment-1451902363or make sure to pass no more than 3000 mel input features.z:Setting `return_timestamps=True` for long-form generation.is_multilingualzThe generation config is outdated and is thus not compatible with the `is_multilingual` argument to `generate`. Please update the generation config as per the instructions https://github.com/huggingface/transformers/issues/25084#issuecomment-1664398224zCannot specify `task` or `language` for an English-only model. If the model is intended to be multilingual, pass `is_multilingual=True` to generate, or update the generation config.
lang_to_ida=  The generation config is outdated and is thus not compatible with the `language` argument to `generate`. Either set the language using the `forced_decoder_ids` in the model config, or update the generation config as per the instructions https://github.com/huggingface/transformers/issues/25084#issuecomment-1664398224
task_to_ida5  The generation config is outdated and is thus not compatible with the `task` argument to `generate`. Either set the task using the `forced_decoder_ids` in the model config, or update the generation config as per the instructions https://github.com/huggingface/transformers/issues/25084#issuecomment-1664398224forced_decoder_idslanguagez<|z|>r>   zUnsupported language: z. Language should be one of: r   )r   Ntaskr  z3`task is not supported. The task should be one of `rY   
transcriberO   zfWhen specifying `prompt_ids`, you cannot also specify `decoder_start_token_id` as it gets overwritten.max_new_tokensz)The length of the sliced `prompt_ids` is z, and the `max_new_tokens` zP. Thus, the combined length of the sliced `prompt_ids` and `max_new_tokens` is: z@. This exceeds the `max_target_positions` of the Whisper model: z. You should either reduce the length of your prompt, or reduce the value of `max_new_tokens`, so that their combined length is less that c                 S   s   g | ]\}}|qS r6   r6   )rb   _ranktokenr6   r6   r7   rd     r]  z<WhisperForConditionalGeneration.generate.<locals>.<listcomp>c                 S   s   g | ]
\}}|d  |fqS r   r6   )rb   rankr  r6   r6   r7   rd     s    r   	translatez@Token-level timestamps may not be reliable for task 'translate'.alignment_headszModel generation config has no `alignment_heads`, token-level timestamps not available. See https://gist.github.com/hollance/42e32852f24243b748ae6bc1f985b13a on how to add this property to the generation config.
num_framesr  )r  token_timestampszeMake sure to set `return_segments=True` to return generation outputs as part of the `'segments' key.`zWhen doing long-form audio transcription, make sure to pass an `attention_mask`. You can retrieve the `attention_mask` by doing `processor(audio, ..., return_attention_mask=True)` rf   r  c                 S   s   g | ]}g qS r6   r6   ra   r6   r6   r7   rd     re   r?   )r,   )r/   	sequencesc                    s"   g | ]  fd d  D qS )c                    s   i | ]	\}}||  qS r6   r6   )rb   kr  r   r6   r7   
<dictcomp>;	  s    zGWhisperForConditionalGeneration.generate.<locals>.<listcomp>.<dictcomp>)items)rb   seek_outputsr  r7   rd   :	  s    )
seek_sequencer  time_offsettimestamp_beginseek_num_framescur_bszr  input_strideprev_idxr  c                 S   s   g | ]}|d  qS )tokensr6   )rb   dr6   r6   r7   rd   d	  r]  )r/   ry  )r	  segments)IpopwarningswarnFutureWarninggeneration_configr  copydeepcopyr=  r  re  rZ  rf  r   ra  rQ   rB  r   r@   r   return_timestampsr   infor  lowerr  r  r  getr  keysr   valuesrq   listrt   r   r  r  rl   r  updaterO   r  r  warningr  r	   r   generate_extract_token_timestampsr  r'   cpur   r(   longrn   rs   rm   r&  rF   r)  r.   r/   nextiterr   eos_token_idrN   _retrieve_segmentr,   stack);r   r>  r  logits_processorstopping_criteriaprefix_allowed_tokens_fnsynced_gpusr!  r  r  r  r  r  r  r  r1   r  r  r   r  total_input_framesencoder_outputs_shapeis_shortformr  language_tokenis_language_coder  rO   text_prompt_idsnon_prompt_forced_decoder_idslast_forced_decoder_idstimestamp_processorr,  r  r  ry   
max_framesseekcurrent_segmentscur_to_prev_index_mapr  prev_bsznew_cur_to_prev_index_mapr   prev_i	cut_indexr  r  segment_inputsegment_input_sliceseek_sequencesr  is_not_finalnum_paddingsr  segment_offsetr	  max_total_lengthcurrent_segment_listr   r  r7   r*  A  s:   /
 








(









*(


c
z(WhisperForConditionalGeneration.generatec
                 C   s  |  |}
|
dd   |ddgg k}t|
d d |
dd  @ d }t|dkr| }g }|r:|t|  d}|D ]6}| |d |d  }|d  | }|d  | }||| ||  || ||  |||	 d |}q>|r|| }||fS | |  | }|| }||fS | |
   }|| }|	 dkr|d  |kr|d  | }|| || ||  | ||	 dg}|| }||fS )Nr   FTr"   r   r   )startendr  r   )
gerl   r(   whererq   rt   r-   r*   r+   numel)r  r  r  r  r  r  r  r  r  r  timestamp_tokenssingle_timestamp_endingtimestamp_segment_indicesslicesr  
last_slicecurrent_slicesliced_tokensstart_timestamp_posend_timestamp_posrM  last_timestamp_pos
timestampsr6   r6   r7   r1  t	  sN   
"z1WhisperForConditionalGeneration._retrieve_segmentc           	      K   s`   |d ur(|d d j d }|j d |kr|}n|j d d }|d d |d f }||||d dS )Nr   r>   r   )r  r  r  r5  r  rQ   )	r   r  r  r5  r  r1   r   past_lengthremove_prefix_lengthr6   r6   r7   prepare_inputs_for_generation	     	z=WhisperForConditionalGeneration.prepare_inputs_for_generationc                    .   d}| D ]}|t  fdd|D f7 }q|S )Nr6   c                 3   $    | ]}| d  |jV  qdS r   Nindex_selectr   r  rb   
past_statebeam_idxr6   r7   r  	     " zAWhisperForConditionalGeneration._reorder_cache.<locals>.<genexpr>r  r  rm  reordered_past
layer_pastr6   rl  r7   _reorder_cache	     z.WhisperForConditionalGeneration._reorder_cachec                    s>  g  t | jjD ] tjfdd|jD dd qt fdd|D }|g d}|dur>|dd|d f }tj	|d	d
dd\}}|| | }t
|| jj}|jdd}tj|jtjd}	t |	jd D ]0}
t||
     \}}tjt|dddt}|| | }t||	|
ddf< ql|	S )a  
        Calculates token-level timestamps using the encoder-decoder cross-attentions and dynamic time-warping (DTW) to
        map each output token to a position in the input audio. If `num_frames` is specified, the encoder-decoder
        cross-attentions will be cropped before applying DTW.

        Returns:
            tensor containing the timestamps in seconds for each predicted token
        c                    s   g | ]}|  qS r6   r6   )rb   xr  r6   r7   rd   	  r]  zMWhisperForConditionalGeneration._extract_token_timestamps.<locals>.<listcomp>r>   r?   c                    s$   g | ]\}} | d d |f qS r   r6   )rb   lh)r  r6   r7   rd   	  s   $ )r   r   r>   r   N.r   TF)r#   keepdimunbiasedr   rf   r   r&   )constant_values)rm   r   r  rt   r(   rF   r  r2  r  std_meanr   median_filter_widthr?  
zeros_liker	  r   rQ   r   doubler,  numpyrh   r/   diffastypero   r   )r   generate_outputsr  r  r  weightsr@  r?  r   r_  	batch_idxr   r   jumps
jump_timesr6   )r  r   r7   r+  	  s$   &z9WhisperForConditionalGeneration._extract_token_timestamps)NNNNNNNNNNNNNNN)NNNNNFNNNNNNNFNr  NNNNN)r  N)%r   r   r   rP  _tied_weights_keysr   r   r  r  r  r  r   r  rw  r  r   r  r   r   r  r   r(   r  rV  r   r   ro   r   r   rZ   r*  staticmethodr1  rc  rs  r+  r   r6   r6   r   r7   r    s    
	
b    7
L

r  c                       s8   e Zd ZdZ fddZdd Zdd Zdd	 Z  ZS )
WhisperDecoderWrapperz
    This wrapper class is a helper class to correctly load pretrained checkpoints when the causal language model is
    used in combination with the [`EncoderDecoderModel`] framework.
    c                    s    t  | d|_t|| _d S rn  )r   r   is_encoder_decoderr  r  r"  r   r6   r7   r   
  s   zWhisperDecoderWrapper.__init__c                 C   r  r   r  rv  r6   r6   r7   rw  
  r  z*WhisperDecoderWrapper.get_input_embeddingsc                 C   r  r   r  r{  r6   r6   r7   r|  
  r  z*WhisperDecoderWrapper.set_input_embeddingsc                 O   s   | j |i |S r   r  r   r6   r6   r7   r   
     zWhisperDecoderWrapper.forward)	r   r   r   r   r   rw  r|  r   r   r6   r6   r   r7   r  
  s    r  z}
    Whisper decoder with with a language modeling head on top (linear layer with weights tied to the input embeddings).
    c                       s0  e Zd ZdgZdZ fddZdd Zdd Zd	ej	fd
dZ
dd Zdd Zdd Zeeed												d%dejdeej deeej  deej deej deeeej   deej deej dee dee dee dee d	eeef fdd Z				d&d!d"Zed#d$ Z  ZS )'WhisperForCausalLMr  rM   c                    s>   t  | d|_t|| _tj|j|jdd| _	| 
  d S r  )r   r   r  r  r=  r   r   r  r  r  rm  r"  r   r6   r7   r   -
  s
   
zWhisperForCausalLM.__init__c                 C   rt  r   r  rv  r6   r6   r7   r  7
  rx  z(WhisperForCausalLM.get_output_embeddingsc                 C   rz  r   r  r  r6   r6   r7   r  :
  r}  z(WhisperForCausalLM.set_output_embeddingsr=   c                 C   r  r   r  rv  r6   r6   r7   rw  =
  r}  z'WhisperForCausalLM.get_input_embeddingsc                 C      | j | d S r   )r=  r|  r{  r6   r6   r7   r|  @
  r  z'WhisperForCausalLM.set_input_embeddingsc                 C   r  r   r=  r  )r   r  r6   r6   r7   set_decoderC
  r  zWhisperForCausalLM.set_decoderc                 C   r  r   r  rv  r6   r6   r7   r  F
  r  zWhisperForCausalLM.get_decoderr  Nr1   r  r  r  r  r  r  r5  r   r  r  c                 C   s  |
dur|
n| j j}
|dur|n| j j}|dur|n| j j}t|tttfr*|d }| jj	||||||||	|
||d}| 
|d }d}|dur_||j}t }||d| j j|d}|su|f|dd  }|durs|f| S |S t|||j|j|j|jdS )a  
        Args:
            input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
                Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you
                provide it. Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
                [`PreTrainedTokenizer.__call__`] for details. [What are input IDs?](../glossary#input-ids)
            attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
                Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
                - 1 for tokens that are **not masked**,
                - 0 for tokens that are **masked**.
                [What are attention masks?](../glossary#attention-mask)
            encoder_outputs  (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
                Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention
                if the model is configured as a decoder.
            head_mask (`torch.Tensor` of shape `(decoder_layers, decoder_attention_heads)`, *optional*):
                Mask to nullify selected heads of the attention modules. Mask values selected in `[0, 1]`:
                - 1 indicates the head is **not masked**,
                - 0 indicates the head is **masked**.
            cross_attn_head_mask (`torch.Tensor` of shape `(decoder_layers, decoder_attention_heads)`, *optional*):
                Mask to nullify selected heads of the cross-attention modules. Mask values selected in `[0, 1]`:
                - 1 indicates the head is **not masked**,
                - 0 indicates the head is **masked**.
            past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
                Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
                shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`) and 2 additional tensors of
                shape `(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)`. The two additional
                tensors are only required when the model is used as a decoder in a Sequence to Sequence model. Contains
                pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
                blocks) that can be used (see `past_key_values` input) to speed up sequential decoding. If
                `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that
                don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all
                `decoder_input_ids` of shape `(batch_size, sequence_length)`.
            inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
                Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation.
                This is useful if you want more control over how to convert `input_ids` indices into associated vectors
                than the model's internal embedding lookup matrix.
            labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
                Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
                config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
                (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
            use_cache (`bool`, *optional*):
                If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
                (see `past_key_values`).
                - 1 for tokens that are **not masked**,
                - 0 for tokens that are **masked**.
            output_attentions (`bool`, *optional*):
                Whether or not to return the attentions tensors of all attention layers. See `attentions` under
                returned tensors for more detail.
            output_hidden_states (`bool`, *optional*):
                Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors
                for more detail.
            return_dict (`bool`, *optional*):
                Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.

        Returns:

        Example:

        ```python
        >>> from transformers import WhisperForCausalLM, WhisperForConditionalGeneration, WhisperProcessor
        >>> import torch
        >>> from datasets import load_dataset

        >>> processor = WhisperProcessor.from_pretrained("openai/whisper-large-v2")
        >>> model = WhisperForConditionalGeneration.from_pretrained("openai/whisper-large-v2")

        >>> assistant_model = WhisperForCausalLM.from_pretrained("distil-whisper/distil-large-v2")

        >>> ds = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation")
        >>> sample = ds[0]["audio"]
        >>> input_features = processor(
        ...     sample["array"], sampling_rate=sample["sampling_rate"], return_tensors="pt"
        ... ).input_features

        >>> predicted_ids = model.generate(input_features, assistant_model=assistant_model)

        >>> # decode token ids to text
        >>> transcription = processor.batch_decode(predicted_ids, skip_special_tokens=True)[0]
        >>> transcription
        ' Mr. Quilter is the apostle of the middle classes and we are glad to welcome his gospel.'
        ```Nr   r  r"   r   )r  r  r  r   r  r  )r   r   r  r  rB  r   r  r'  r=  r  r  r   r  r   rE   r  r   r  r   r  r  )r   rM   r1   r  r  r  r  r  r  r5  r   r  r  r,  r  r  r  r  r6   r6   r7   r   I
  sH   azWhisperForCausalLM.forwardc           	      K   s`   |d ur(|d d j d }|j d |kr|}n|j d d }|d d |d f }|||||dS )Nr   r>   r   )r  r  rM   r5  r1   r`  )	r   rM   r  r5  r  r1   r   ra  rb  r6   r6   r7   rc  
  rd  z0WhisperForCausalLM.prepare_inputs_for_generationc                    re  )Nr6   c                 3   rf  rg  rh  rj  rl  r6   r7   r  
  rn  z4WhisperForCausalLM._reorder_cache.<locals>.<genexpr>ro  rp  r6   rl  r7   rs  
  rt  z!WhisperForCausalLM._reorder_cache)NNNNNNNNNNNNr  )r   r   r   r  rQ  r   r  r  r   r  rw  r|  r  r  r   r   r  r(   rV  r   r   r   r  ro   r   r   rc  r  rs  r   r6   r6   r   r7   r  #
  st    

	

 
r  z
    Whisper Encoder Model with a sequence classification head on top (a linear layer over the pooled output) for tasks
    like SUPERB Keyword Spotting.
    c                       s   e Zd Z fddZdd ZdejfddZdejfd	d
Ze	e
eeed							ddeej deej deeeej   deej dee dee dee deeej ef fddZ  ZS )WhisperForAudioClassificationc                    sl   t  | t|| _|jd }|jrtt	|| | _
t|j|j| _t|j|j| _|   d S r   )r   r   rH  r  num_hidden_layersuse_weighted_layer_sumr   	Parameterr(   rs   layer_weightsr   r  classifier_proj_size	projector
num_labels
classifierrm  )r   r   
num_layersr   r6   r7   r     s   

z&WhisperForAudioClassification.__init__c                 C   r  )z
        Calling this function will disable the gradient computation for the Whisper encoder so that its parameters will
        not be updated during training. Only the projection layers and classification head will be updated.
        Nr  rv  r6   r6   r7   r    r  z,WhisperForAudioClassification.freeze_encoderr=   c                 C   r  r   )r  rw  rv  r6   r6   r7   rw    r}  z2WhisperForAudioClassification.get_input_embeddingsry  c                 C   r  r   )r  r|  r{  r6   r6   r7   r|    r  z2WhisperForAudioClassification.set_input_embeddingsr  Nr>  r  r  r  r   r  r  c                 C   s>  |dur|n| j j}|dur|n| j j}|dur|n| j j}|du r,| j|||||d}| j jrNtj|dd}tj	j
| jdd}	||	ddd jdd}n|d }| |}|jdd}
| |
}d}|durt }||j}||d| j j|d}|s|f|dd  }|dur|f| S |S t|||j|jdS )a  
        labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
            Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
            config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
            `config.num_labels > 1` a classification loss is computed (Cross-Entropy).

        Returns:

        Example:

        ```python
        >>> import torch
        >>> from transformers import AutoFeatureExtractor, WhisperForAudioClassification
        >>> from datasets import load_dataset

        >>> feature_extractor = AutoFeatureExtractor.from_pretrained("sanchit-gandhi/whisper-medium-fleurs-lang-id")
        >>> model = WhisperForAudioClassification.from_pretrained("sanchit-gandhi/whisper-medium-fleurs-lang-id")

        >>> ds = load_dataset("google/fleurs", "all", split="validation", streaming=True)
        >>> sample = next(iter(ds))

        >>> inputs = feature_extractor(
        ...     sample["audio"]["array"], sampling_rate=sample["audio"]["sampling_rate"], return_tensors="pt"
        ... )
        >>> input_features = inputs.input_features

        >>> with torch.no_grad():
        ...     logits = model(input_features).logits

        >>> predicted_class_ids = torch.argmax(logits).item()
        >>> predicted_label = model.config.id2label[predicted_class_ids]
        >>> predicted_label
        'Afrikaans'
        ```Nr  r   r?   r"   r   )r  r  r   r  )r   r   r  r  r  r  r(   r2  r   r   r   r  rE   r'   r  r?  r  r   r   r  r  r   r   r  )r   r>  r  r  r  r   r  r  r   norm_weightspooled_outputr  r  r  r  r6   r6   r7   r   !  sD   /

z%WhisperForAudioClassification.forward)NNNNNNN)r   r   r   r   r  r   r  rw  r|  r    WHISPER_ENCODER_INPUTS_DOCSTRINGr   r   r  r   r(   rV  r   r   r  ro   r   r   r   r6   r6   r   r7   r  
  s>    
	r  )r9   )Nr   )Zr   r  rA   r  typingr   r   r   r  rh   r(   torch.nn.functionalr   r   r.   torch.utils.checkpointtorch.nnr   activationsr   generation.logits_processr	   modeling_attn_mask_utilsr
   r   modeling_outputsr   r   r   r   r   r   modeling_utilsr   utilsr   r   r   r   r   r   configuration_whisperr   tokenization_whisperr   r   
flash_attnr   r   flash_attn.bert_paddingr   r    r!   
get_loggerr   r   r  _CHECKPOINT_FOR_DOC%WHISPER_PRETRAINED_MODEL_ARCHIVE_LISTr8   rZ   r   r   rL   rU   rV  ndarrayr   r   r   rG  r   r  r   r   r  r  r  r-  r<  WHISPER_START_DOCSTRINGr  r  rH  r  r  r  r  r  r  r6   r6   r6   r7   <module>   s     


w6 " ZfGx!U  v %      W W