
    h\*                     b    S r SSKrSSKJrJr  SSKrSSKJrJr   " S S\R                  5      r	g)a<  
The MIT License (MIT)

Copyright (c) Microsoft Corporation

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
    N)OptionalTuple)nnTensorc                      ^  \ rS rSrSr      SS\S\S\S\S\S\S	\S
\4U 4S jjjrS\S\S\	4S jr
SS\	S\4S jjr   SS\	S\\	   S\\	   S\\	   S\\	\\	   4   4
S jjrSrU =r$ )WavLMSelfAttention    an  Multi-headed self-attention for WavLM model :cite:`chen2022wavlm`.
Wraps around ``torch.nn.MultiheadAttention``, creating relaive position embeddings and passing them to multi-headed
attention as a mask.
Source: https://github.com/microsoft/unilm/blob/2d8302f09c99bca2b82e6e868d81d4281cceebc8/wavlm/modules.py#L303-L763

Args:
    embed_dim (int): Total dimension of the model.
    num_heads (int): The number of heads.
    dropout (float, optional): Dropout probability on attn_output_weights. (Default: to ``0.0``)
    bias (bool, optional): If ``True``, add bias to input / output projection layers. (Default: ``True``)
    has_relative_attention_bias (bool, optional): If ``True``, apply relative position embedding.
        Necessary in the first encoder layer, but not in the subsequent ones. (Default: ``False``)
    num_buckets (int, optional): Number of buckets for relative position embedding. (Default: ``32``)
    max_distance (int, optional): Naximum distance for relative position embedding. (Default: ``128``)
    gru_rel_pos (bool, optional): If ``True``, apply gated relative position embedding. (Default: ``False``)
	embed_dim	num_headsdropoutbiashas_relative_attention_biasnum_bucketsmax_distancegru_rel_posc	                 :  > [         T	U ]  5         Xl        X l        XPl        X`l        Xpl        U(       a  [        R                  " Xb5      U l	        OS U l	        X-  U l
        U R                  U-  U R                  :X  d   S5       eX0l        [        R                  " XX4SS9U l        Xl        U R                  (       aX  [        R                  " U R                  S5      U l        [        R"                  " [$        R&                  " SUSS5      5      U l        SU l        g )Nz(embed_dim must be divisible by num_headsT)r   r   batch_first      )super__init__r
   r   r   r   r   r   	Embeddingrel_attn_embedhead_dimr   MultiheadAttention	attentionr   Lineargru_rel_pos_linear	Parametertorchonesgru_rel_pos_consthas_position_bias)
selfr
   r   r   r   r   r   r   r   	__class__s
            b/var/www/auris/envauris/lib/python3.13/site-packages/torchaudio/models/wav2vec2/wavlm_attention.pyr   WavLMSelfAttention.__init__2   s     	""+F(&(&"$,,{"FD"&D!.}}y(DNN:f<ff:..yWmqr&&(iiq&AD#%'\\%**Q	1a2P%QD"!%    query_length
key_lengthreturnc                 |   [         R                  " U[         R                  S9SS2S4   n[         R                  " U[         R                  S9SSS24   nXC-
  nU R                  USS9nUR	                  U R
                  R                  R                  5      nU R                  U5      nUR                  / SQ5      nU$ )aP  Compute relative position embeddings for WavLM model.
Args:
    query_length (int): Query position can take values between 0 and ``query_length - 1``.
    key_length (int): Key position can take values between 0 and ``key_length - 1``.
Returns:
    Tensor of shape `(num_heads, query_length, key_length)`, relative positions embeddings
dtypeNT)bidirectional)   r   r   )	r    arangelong_relative_positions_buckettor   weightdevicepermute)r$   r)   r*   context_positionmemory_positionrelative_positionrelative_position_bucketvaluess           r&   compute_biasWavLMSelfAttention.compute_biasU   s     !<<EJJG4P,,zDT1WM+>#'#B#BCTdh#B#i #;#>#>t?R?R?Y?Y?`?`#a $$%=>	*r(   relative_positionsr/   c                    U R                   nU R                  n[        R                  " U[        R                  S9nU(       aC  US-  nXQS:  R                  [        R                  5      U-  -  n[        R                  " U5      nO,[        R                  " U[        R                  " U5      5      * nUS-  nX:  nU[        R                  " UR                  5       U-  5      [        R                  " XF-  5      -  X6-
  -  R                  [        R                  5      -   n[        R                  " U[        R                  " XS-
  5      5      nU[        R                  " XqU5      -  nU$ )a|  Compute relative position buckets for WavLM model. Computation similar to formula (5) in WavLM
   paper :cite:`chen2022wavlm`.
Args:
    relative_positions (Tensor): Relative offsets between query and key positions,
        of shape ``(query_length, key_length)``.
    bidirectional (bool): If ``True``, values will be filled both above and below the diagonal in the resulting
        matrix. If ``False``, the elements above the diagonal (i.e. with negative relative offsets) will be set
        to zero. (Default ``True``)
Returns:
    Tensor of shape ``(query_length, key_length)`` filled bucketed values of with relative positions.
r-   r0   r   r   )r   r   r    
zeros_liker2   r4   absminlogfloatmath	full_likewhere)	r$   r?   r/   r   r   relative_buckets	max_exactis_smallrelative_postion_if_larges	            r&   r3   -WavLMSelfAttention._relative_positions_bucketf   s=    &&(( ++,>ejjQ%*Ka!7 ; ;EJJ G+ UU!&+=!>"')),>@P@PQc@d"e!e1$	%1$-II(..09<=hh|/01&( "UZZ.	%!
 %*II%u7P`aRa'b%
! 	EKKF_``r(   querykey_padding_maskattention_maskposition_biasc           	         UR                  5       u  pVnXpR                  :X  d   eUb   eU R                  b7  Uc4  U R                  Xf5      nUR	                  S5      R                  USSS5      nSnUb  UnU R                  (       a  UR                  XVU R                  S5      n	U	R                  SSSS5      n	[        R                  " U R                  U	5      R                  XPR                  USS5      R                  SSS	95      R                  SSS
9u  pXU R                  -  S-
  -  S-   nUR                  XPR                  SS5      U-  nUR                  XPR                  Xf45      nUb  Ub  UR                  USSU5      R!                  SU R                  SS5      n[        R"                  R$                  R'                  US[        R"                  R$                  R)                  U5      SUR*                  S9nUb  Ub  X-   n[        R"                  R$                  R-                  XR.                  R0                  U R.                  R2                  5      nUR                  SS5      u  pnXVU R                  U R4                  4nUR                  U5      R7                  SS5      nUR                  U5      R7                  SS5      nUR                  U5      R7                  SS5      nU R8                  (       a  U R:                  OSn[        R"                  R$                  R=                  UUUUUSS9nUR7                  SS5      R?                  USU R                  U R4                  -  5      nU R.                  RA                  U5      nUU4$ )a{  
Args:
    query (Tensor): Input of shape ``(batch_size, src_len, embed_dim)``.
    key_padding_mask (Tensor or None, optional): Mask to exclude keys that are pads, of shape
        `(batch, src_len)`, where padding elements are indicated by 1s. (Default: ``None``)
    attn_mask: Needs to be ``None``. The argument exists for compatibility with
        ``EncoderLayer``. (Default: ``None``)
    position_bias (Tensor or None, optional): Position bias of shape
        ``(batch_size * num_heads, src_len, src_len)``. When used inside WavLM model encoder, will be
        generated in the first layer and then passed from each encoder layer to the next one.
        (Default: ``None``)
Returns:
    attn_output (Tensor): Attention output of shape ``(batch_size, src_len, embed_dim)``.
    position_bias (Tensor or None): Position bias of shape ``(batch_size * num_heads, src_len, src_len)``.
Nr   r   r0         F)keepdim)dimg      ?g       @rO    )mask	mask_name
other_type
other_nametarget_type        )	attn_mask	dropout_p	is_causal)!sizer
   r   r=   	unsqueezerepeatr   viewr   r7   r    sigmoidr   sumchunkr"   expandr   
functional_canonical_mask_none_or_dtyper.   linearr   in_proj_weightin_proj_biasr   	transposetrainingr   scaled_dot_product_attentionreshapeout_proj)r$   rN   rO   rP   rQ   bszseq_lenr
   attn_mask_rel_posquery_layergate_agate_bgate_a_1query_projectedkeyvalueshaper   attn_outputs                      r&   forwardWavLMSelfAttention.forward   sJ   , #(**,iNN***%%%*}/D --g?M)33A6==c1aKM.2$ -#jjt~~rJ)11!Q1=!&++K8==c>>SZ\]_`aeefhrwex"%r%"  "d.D.D%Ds%JKcQ$,MM#~~r1$MP]$]! 1 6 6^^W7^ _(-=-I/44S!QHOOPRTXTbTbdfhjk$xx22BB%, 88..==>OP!KK  C   (-=-I 1 D((--44UNN<Y<Y[_[i[i[v[vw+11!R8Et~~t}}=

5!++Aq1hhuo''1-

5!++Aq1"&--$,,Shh))FF' G 
 "++Aq199#r4>>TXTaTaCabnn--k:M))r(   )r   r   r
   r   r"   r   r#   r   r   r   r   r   r   )r^   TFr	      T)T)NNN)__name__
__module____qualname____firstlineno____doc__intrE   boolr   r   r=   r3   r   r   r   __static_attributes____classcell__)r%   s   @r&   r   r       s   * ,1 !&!& !& 	!&
 !& &*!& !& !& !& !&F # & "% V % TX % T .2+/*.I*I* #6*I* !(	I*
  'I* 
vx''	(I* I*r(   r   )
r   rF   typingr   r   r    r   r   Moduler    r(   r&   <module>r      s*   0  "  v* v*r(   