Ë
    S^(håR  ã                   óP  — d dl mZ d dlmZmZ d dlZddlmZ e G d„ d«      «       Z	 ddeej                     d	eej                  eef   d
ej                  dedee   f
d„Z	 ddeej                     d	eej                  eef   d
ej                  dedee   f
d„Zddej                  dej                   dee   fd„Zddej                  dej                   dee   fd„Z	 	 dd	eej                  eef   dej                   dej&                  dedee   deej                     fd„Zy)é    )Ú	dataclass)ÚOptionalÚUnionNé   )Úis_torchdynamo_compilingc                   ó^  — e Zd ZU dZeed<   eed<   ddedee   fd„Z	 ddededed	e	j                  d
ee	j                  df   dee	j                     fd„Z	 dde	j                  ded	e	j                  dee   de	j                  f
d„Ze	 	 dde	j"                  d	e	j                  d
e	j                  dedee   f
d„«       Zedde	j                  d	e	j                  dee   fd„«       Zede	j(                  defd„«       Ze	 	 d dee	j                     de	j                  dedee   dedefd„«       Zy)!ÚAttentionMaskConvertera9  
    A utility attention mask class that allows one to:
        - Create a causal 4d mask
        - Create a causal 4d mask with slided window
        - Convert a 2d attention mask (batch_size, query_length) to a 4d attention mask (batch_size, 1, query_length,
          key_value_length) that can be multiplied with attention scores

    Examples:

    ```python
    >>> import torch
    >>> from transformers.modeling_attn_mask_utils import AttentionMaskConverter

    >>> converter = AttentionMaskConverter(True)
    >>> converter.to_4d(torch.tensor([[0, 0, 0, 1, 1]]), 5, key_value_length=5, dtype=torch.float32)
    tensor([[[[-3.4028e+38, -3.4028e+38, -3.4028e+38, -3.4028e+38, -3.4028e+38],
            [-3.4028e+38, -3.4028e+38, -3.4028e+38, -3.4028e+38, -3.4028e+38],
            [-3.4028e+38, -3.4028e+38, -3.4028e+38, -3.4028e+38, -3.4028e+38],
            [-3.4028e+38, -3.4028e+38, -3.4028e+38,  0.0000e+00, -3.4028e+38],
            [-3.4028e+38, -3.4028e+38, -3.4028e+38,  0.0000e+00,  0.0000e+00]]]])
    ```

    Parameters:
        is_causal (`bool`):
            Whether the attention mask should be a uni-directional (causal) or bi-directional mask.

        sliding_window (`int`, *optional*):
            Optionally, the sliding window masks can be created if `sliding_window` is defined to a positive integer.
    Ú	is_causalÚsliding_windowNc                 óŠ   — || _         || _        | j                  �)| j                  dk  rt        d| j                  › d�«      ‚y y )Nr   zaMake sure that when passing `sliding_window` that its value is a strictly positive integer, not `ú`)r
   r   Ú
ValueError)Úselfr
   r   s      úc/var/www/skyplay_api_hub/venv/lib/python3.12/site-packages/transformers/modeling_attn_mask_utils.pyÚ__init__zAttentionMaskConverter.__init__9   sh   € Ø"ˆŒØ,ˆÔà×ÑÐ*¨t×/BÑ/BÀaÒ/GÜØsÐtx÷  uHñ  uHð  tIð  IJð  Kóð ð 0HÐ*ó    Ú
batch_sizeÚquery_lengthÚkey_value_lengthÚdtypeÚdeviceÚstrÚreturnc                 óÎ   — | j                   st        d| j                  › d�«      ‚||f}||z
  }d}|d   dkD  s| j                  � | j	                  ||||| j                  ¬«      }|S )z¿
        Creates a causal 4D mask of (bsz, head_dim=1, query_length, key_value_length) shape and adds large negative
        bias to upper right hand triangular matrix (causal mask).
        z"Please use `to_causal_4d` only if z has `is_causal` set to True.Néÿÿÿÿr   ©r   Úpast_key_values_lengthr   )r
   r   Ú	__class__r   Ú_make_causal_mask)	r   r   r   r   r   r   Úinput_shaper   Úcausal_4d_masks	            r   Úto_causal_4dz#AttentionMaskConverter.to_causal_4dB   s�   € ð �~Š~ÜÐAÀ$Ç.Á.ÐAQÐQnÐoÓpÐpð " <Ð0ˆØ!1°LÑ!@Ðð ˆØ�r‰?˜QÒ $×"5Ñ"5Ð"AØ!×3Ñ3ØØØØ'=Ø#×2Ñ2ð 4ó ˆNð Ðr   Úattention_mask_2dc                 óö  — |j                   d   |f}d}|d   dkD  s| j                  �I| j                  r=|€t        d«      ‚||z
  }| j	                  |||j
                  || j                  ¬«      }n| j                  �t        d«      ‚| j                  |||d   ¬«      j                  |j
                  «      }|�=|j                  |j                  «       t        j                  |«      j                  «      }|}	|	S )	a  
        Converts 2D attention mask to 4D attention mask by expanding mask to (bsz, head_dim=1, query_length,
        key_value_length) shape and by adding a large negative bias to not-attended positions. If attention_mask is
        causal, a causal mask will be added.
        r   Nr   r   zpThis attention mask converter is causal. Make sure to pass `key_value_length` to correctly create a causal mask.r   z?Sliding window is currently only implemented for causal masking)Útgt_len)Úshaper   r
   r   r   r   ÚNotImplementedErrorÚ_expand_maskÚtoÚmasked_fillÚboolÚtorchÚfinfoÚmin)
r   r#   r   r   r   r    r!   r   Úexpanded_attn_maskÚexpanded_4d_masks
             r   Úto_4dzAttentionMaskConverter.to_4dc   s)  € ð )×.Ñ.¨qÑ1°<Ð@ˆð ˆØ˜‰O˜aÒ 4×#6Ñ#6Ð#BÈÏÊØÐ'Ü ð Góð ð &6¸Ñ%DÐ"Ø!×3Ñ3ØØØ(×/Ñ/Ø'=Ø#×2Ñ2ð 4ó ‰Nð × Ñ Ð,Ü%Ð&gÓhÐhð "×.Ñ.Ð/@À%ÐQ\Ð]_ÑQ`Ð.Óa×dÑdØ×$Ñ$ó
Ðð Ð%Ø!/×!;Ñ!;Ð<N×<SÑ<SÓ<UÔW\×WbÑWbÐchÓWi×WmÑWmÓ!nÐð .ÐàÐr   Úinput_ids_shaper   c                 ó  — | \  }}t        j                  ||ft        j                  |«      j                  |¬«      }t        j                  |j                  d«      |¬«      }|j                  ||dz   j                  |j                  d«      d«      k  d«       |j                  |«      }|dkD  r0t        j                  t        j                  ||||¬«      |gd¬«      }|�‹||z
  dz
  }	t        j                  t        j                  |t         j                  ¬«      |	¬	«      }
t        «       r|j                  «       }|j                  |
t        j                  |«      j                  «       |dddd…dd…f   j!                  |d|||z   «      S )
zJ
        Make causal mask used for bi-directional self-attention.
        )r   r   r   r   ©r   r   )ÚdimN)r   )Údiagonal)r,   Úfullr-   r.   ÚarangeÚsizeÚmasked_fill_Úviewr)   ÚcatÚzerosÚtrilÚ	ones_liker+   r   ÚcloneÚexpand)r2   r   r   r   r   Úbszr%   ÚmaskÚ	mask_condr6   Úcontext_masks              r   r   z(AttentionMaskConverter._make_causal_mask’   sK  € ð '‰ˆˆWÜ�z‰z˜7 GÐ,¬e¯k©k¸%Ó.@×.DÑ.DÈVÔTˆÜ—L‘L §¡¨2£°vÔ>ˆ	Ø×Ñ˜) y°1¡}×&:Ñ&:¸4¿9¹9ÀR»=È!Ó&LÑLÈaÔPà�w‰w�u‹~ˆà! AÒ%Ü—9‘9œeŸk™k¨'Ð3IÐQVÐ_eÔfÐhlÐmÐsuÔvˆDð Ð%Ø-°Ñ>ÀÑBˆHä Ÿ:™:¤e§o¡o°dÄ%Ç*Á*Ô&MÐX`ÔaˆLô (Ô)Ø—z‘z“|�Ø×Ñ˜l¬E¯K©K¸Ó,>×,BÑ,BÔCà�D˜$¢¢1Ð$Ñ%×,Ñ,¨S°!°W¸gÐH^Ñ>^Ó_Ð_r   rC   r%   c                 ó2  — | j                  «       \  }}|�|n|}| dd…dddd…f   j                  |d||«      j                  |«      }d|z
  }|j                  |j                  t        j
                  «      t	        j                  |«      j                  «      S )zg
        Expands attention_mask from `[bsz, seq_len]` to `[bsz, 1, tgt_seq_len, src_seq_len]`.
        Nr   ç      ð?)r9   rA   r)   r*   r,   r+   r-   r.   )rC   r   r%   rB   Úsrc_lenÚexpanded_maskÚinverted_masks          r   r(   z#AttentionMaskConverter._expand_mask´   s‹   € ð
 —y‘y“{‰ˆˆWØ$Ð0‘'°gˆàšQ  dªAÐ-Ñ.×5Ñ5°c¸1¸gÀwÓO×RÑRÐSXÓYˆà˜mÑ+ˆà×(Ñ(¨×)9Ñ)9¼%¿*¹*Ó)EÄuÇ{Á{ÐSXÓGY×G]ÑG]Ó^Ð^r   rI   Ú	min_dtypec                 ó¨   — | j                   t        j                  k(  rt        d«      ‚| j	                  t        j
                  | |k(  dd¬«       «      S )aÏ  
        Attend to all tokens in masked rows from the expanded attention mask, for example the relevant first rows when
        using left padding. This is required by F.scaled_dot_product_attention memory-efficient attention path.
        Details: https://github.com/pytorch/pytorch/issues/110213

        `expanded_mask` is [bsz, num_masks, tgt_seq_len, src_seq_len] or [bsz, tgt_seq_len, src_seq_len].
        `attention_mask` is [bsz, src_seq_len].

        The dimension num_masks of `expanded_mask` is most often 1, but it can also be the number of heads in the case of alibi attention bias.

        For example, if `expanded_mask` is (e.g. here left-padding case)
        ```
        [[[[0, 0, 0],
           [0, 0, 0],
           [0, 0, 1]]],
         [[[1, 0, 0],
           [1, 1, 0],
           [1, 1, 1]]],
         [[[0, 0, 0],
           [0, 1, 0],
           [0, 1, 1]]]]
        ```
        then the modified `expanded_mask` will be
        ```
        [[[[1, 1, 1],   <-- modified
           [1, 1, 1],   <-- modified
           [0, 0, 1]]],
         [[[1, 0, 0],
           [1, 1, 0],
           [1, 1, 1]]],
         [[[1, 1, 1],   <-- modified
           [0, 1, 0],
           [0, 1, 1]]]]
        ```
        z\AttentionMaskConverter._unmask_unattended expects a float `expanded_mask`, got a BoolTensor.r   T)r5   Úkeepdim)r   r,   r+   r   ÚmulÚall)rI   rK   s     r   Ú_unmask_unattendedz)AttentionMaskConverter._unmask_unattendedÂ   sP   € ðT ×Ñ¤%§*¡*Ò,ÜØnóð ð × Ñ ¤%§)¡)¨M¸YÑ,FÈBÐX\Ô"]Ð!]Ó^Ð^r   Úattention_maskÚinputs_embedsÚis_trainingc                 ó²  — |j                   d   |j                   d   }}||z   }t        j                  j                  «       xs0 t	        |t        j
                  j                  «      xs
 t        «       }d}	| €|s|s|dk(  s||k(  r	|�||k  rd}	|	S |�||k  r?t        | j                   «      dk(  ry|s$t        j                  | dk(  «      r|dk(  s||k(  rd}	|	S )a9  
        Detects whether the optional user-specified attention_mask & the automatically created causal mask can be
        ignored in case PyTorch's SDPA is used, rather relying on SDPA's `is_causal` argument.

        In case no token is masked in the `attention_mask` argument, if `query_length == 1` or
        `key_value_length == query_length`, we rather rely on SDPA `is_causal` argument to use causal/non-causal masks,
        allowing to dispatch to the flash attention kernel (that can otherwise not be used if a custom `attn_mask` is
        passed).
        r   r   FTé   )
r&   r,   ÚjitÚ
is_tracingÚ
isinstanceÚfxÚProxyr   ÚlenrO   )
rQ   rR   r   r   rS   Ú_r   r   rW   Úignore_causal_masks
             r   Ú_ignore_causal_mask_sdpaz/AttentionMaskConverter._ignore_causal_mask_sdpaó   sô   € ð$ (×-Ñ-¨aÑ0°-×2EÑ2EÀaÑ2Hˆ<ˆØ'Ð*@Ñ@Ðä—Y‘Y×)Ñ)Ó+Òv¬z¸-ÌÏÉÏÉÓ/XÒvÔ\tÓ\vˆ
à"ÐàÐ!ñ ¡JØ! QÒ&Ð*:¸lÒ*JØ#Ð+Ð/?À.Ò/Pà%)Ð"ð "Ð!ð Ð#Ð'7¸.Ò'HÜ�>×'Ñ'Ó(¨AÒ-ØÙ¤E§I¡I¨nÀÑ.AÔ$BØ 1Ò$Ð(8¸LÒ(Hà)-Ð&ð "Ð!r   ©N)Úcpu©r   N)NF)Ú__name__Ú
__module__Ú__qualname__Ú__doc__r+   Ú__annotations__Úintr   r   r,   r   r   r   ÚTensorr"   r1   ÚstaticmethodÚSizer   r(   ÚFloatTensorÚfloatrP   r^   © r   r   r	   r	      s  … ñð< ƒOØÓñ $ð ¸À¹ó ð .3ñàðð ðð ð	ð
 �{‰{ðð �e—l‘l EÐ)Ñ*ðð 
�%—,‘,Ñ	óðL +/ñ- à Ÿ<™<ð- ð ð- ð �{‰{ð	- ð
 # 3™-ð- ð 
�‰ó- ð^ ð
 '(Ø(,ñ`ØŸ™ð`à�{‰{ð`ð —‘ð`ð !$ð	`ð
 ! ™ò`ó ð`ðB ñ_˜5Ÿ<™<ð _°·±ð _ÀhÈsÁmò _ó ð_ð ð._Ø×(Ñ(ð._àò._ó ð._ð` ð
 )-Ø!ñ7"Ø  §¡Ñ.ð7"à—|‘|ð7"ð !$ð7"ð ! ™ð	7"ð
 ð7"ð 
ò7"ó ñ7"r   r	   rQ   r    rR   r   r   c                 óŒ  — t        d|¬«      }|d   |z   }| �<t        | j                  «      dk(  r$|j                  | |d   ||j                  ¬«      } | S | �¾t        | j                  «      dk(  r¦|d   d|d   |f}t        | j                  «      |k7  r%t        d	t        | j                  «      › d
|› d�«      ‚d| z
  }|j                  |j                  t        j                  «      t        j                  |j                  «      j                  «      } | S |j                  |d   |d   ||j                  |j                  ¬«      } | S )añ  
    Creates a causal 4D mask of shape `(batch_size, 1, query_length, key_value_length)` from a 2D mask of shape
    `(batch_size, key_value_length)`

    Args:
        attention_mask (`torch.Tensor` or `None`):
            A 2D attention mask of shape `(batch_size, key_value_length)`
        input_shape (`tuple(int)` or `list(int)` or `torch.Size`):
            The input shape should be a tuple that defines `(batch_size, query_length)`.
        inputs_embeds (`torch.Tensor`):
            The embedded inputs as a torch Tensor.
        past_key_values_length (`int`):
            The length of the key value cache.
        sliding_window (`int`, *optional*):
            If the model uses windowed attention, a sliding window should be passed.
    T©r
   r   r   é   )r   r   rU   r   r   z#Incorrect 4D attention_mask shape: z; expected: ú.rG   r4   )r	   r[   r&   r1   r   Útupler   r*   r)   r,   r+   r-   r.   r"   r   )	rQ   r    rR   r   r   Úattn_mask_converterr   Úexpected_shaperJ   s	            r   Ú!_prepare_4d_causal_attention_maskru   .  sn  € ô. 1¸4ÐP^Ô_Ðà" 2‘Ð)?Ñ?Ðð Ð!¤c¨.×*>Ñ*>Ó&?À1Ò&DØ,×2Ñ2Ø˜K¨™OÐ>NÐVc×ViÑVið 3ó 
ˆð( Ðð# 
Ð	#¬¨N×,@Ñ,@Ó(AÀQÒ(FØ% a™.¨!¨[¸©^Ð=MÐNˆÜ�×%Ñ%Ó&¨.Ò8ÜØ5´e¸N×<PÑ<PÓ6QÐ5RÐR^Ð_mÐ^nÐnoÐpóð ð
   .Ñ0ˆMØ*×6Ñ6Ø× Ñ ¤§¡Ó,¬e¯k©k¸-×:MÑ:MÓ.N×.RÑ.RóˆNð Ðð	 -×9Ñ9Ø˜‰N˜K¨™OÐ-=À]×EXÑEXÐan×auÑauð :ó 
ˆð Ðr   c                 ó˜  — t        d|¬«      }|d   |z   }t        j                  j                  «       xs0 t	        |t        j
                  j                  «      xs
 t        «       }t         j                  | |||¬«      }|rd}	|	S | €2|j                  |d   |d   ||j                  |j                  ¬«      }	|	S | j                  «       dk(  r| }	n"|j                  | |d   |j                  |¬	«      }	|sW|	j                  j                  d
k(  r>t         j                  |	t        j                   |j                  «      j"                  ¬«      }	|	S )aé  
    Prepares the correct `attn_mask` argument to be used by `torch.nn.functional.scaled_dot_product_attention`.

    In case no token is masked in the `attention_mask` argument, we simply set it to `None` for the cases `query_length == 1` and
    `key_value_length == query_length`, and rely instead on SDPA `is_causal` argument to use causal/non-causal masks,
    allowing to dispatch to the flash attention kernel (that can otherwise not be used if a custom `attn_mask` is passed).
    Tro   r   )rQ   rR   r   r   Nr   r4   rU   )r   r   Úcuda)rK   )r	   r,   rV   rW   rX   rY   rZ   r   r^   r"   r   r   r5   r1   ÚtyperP   r-   r.   )
rQ   r    rR   r   r   rs   r   rW   r]   r0   s
             r   Ú*_prepare_4d_causal_attention_mask_for_sdpary   c  sg  € ô 1¸4ÐP^Ô_Ðà" 2‘Ð)?Ñ?Ðô
 —‘×%Ñ%Ó'Òr¬:°mÄUÇXÁXÇ^Á^Ó+TÒrÔXpÓXr€Jä/×HÑHØ%Ø#Ø5Ø%ð	 Ió Ðñ ØÐð0 Ðð/ 
Ð	Ø.×;Ñ;Ø˜‰N˜K¨™OÐ-=À]×EXÑEXÐan×auÑauð <ó 
Ðð, Ðð% ×ÑÓ 1Ò$Ø-Ñà2×8Ñ8ØØ˜B‘Ø#×)Ñ)Ø!1ð	  9ó  Ðñ Ð.×5Ñ5×:Ñ:¸fÒDÜ5×HÑHØ ¬E¯K©K¸×8KÑ8KÓ,L×,PÑ,Pð  Ió  Ðð Ðr   rC   r   r%   c                 ó2   — t         j                  | ||¬«      S )áÎ  
    Creates a non-causal 4D mask of shape `(batch_size, 1, query_length, key_value_length)` from a 2D mask of shape
    `(batch_size, key_value_length)`

    Args:
        mask (`torch.Tensor`):
            A 2D attention mask of shape `(batch_size, key_value_length)`
        dtype (`torch.dtype`):
            The torch dtype the created mask shall have.
        tgt_len (`int`):
            The target length or query length the created mask shall have.
    ©rC   r   r%   )r	   r(   r|   s      r   Ú_prepare_4d_attention_maskr}   �  s   € ô "×.Ñ.°DÀÈwÐ.ÓWÐWr   c                 ó2  — | j                   \  }}|�|n|}t        j                  j                  «       xs0 t	        | t        j
                  j                  «      xs
 t        «       }|st        j                  | dk(  «      ryt        j                  | ||¬«      S )r{   Nr   r|   )r&   r,   rV   rW   rX   rY   rZ   r   rO   r	   r(   )rC   r   r%   r\   r   rW   s         r   Ú#_prepare_4d_attention_mask_for_sdpar   ­  s   € ð Ÿ*™*Ñ€AÐØ Ð,‰gÐ2B€Gä—‘×%Ñ%Ó'Òi¬:°d¼E¿H¹H¿N¹NÓ+KÒiÔOgÓOi€Jñ œ%Ÿ)™) D¨A¡IÔ.Øä%×2Ñ2¸ÀEÐSZÐ2Ó[Ð[r   r   r   c                 óh   — t        d|¬«      }|| d   z   }|j                  | d   | d   |||¬«      }|S )a/  
    Creates a causal 4D mask of shape `(batch_size, 1, query_length, key_value_length)`

    Args:
        input_shape (`tuple(int)` or `list(int)` or `torch.Size`):
            The input shape should be a tuple that defines `(batch_size, query_length)`.
        dtype (`torch.dtype`):
            The torch dtype the created mask shall have.
        device (`int`):
            The torch device the created mask shall have.
        sliding_window (`int`, *optional*):
            If the model uses windowed attention, a sliding window should be passed.
    Tro   r   r   r4   )r	   r"   )r    r   r   r   r   rs   r   rQ   s           r   Ú _create_4d_causal_attention_maskr�   Æ  sR   € ô( 1¸4ÐP^Ô_Ðà-°¸B±Ñ?ÐØ(×5Ñ5Ø�A‰˜ B™Ð)9ÀÈvð 6ó €Nð Ðr   r_   ra   )Údataclassesr   Útypingr   r   r,   Úutils.import_utilsr   r	   rh   rj   rr   Úlistrg   ru   ry   r   r}   r   r   r�   rm   r   r   ú<module>r†      s¨  ðõ "ß "ã å 8ð ÷T"ð T"ó ðT"ðx %)ñ1Ø˜UŸ\™\Ñ*ð1à�u—z‘z 5¨$Ð.Ñ/ð1ð —<‘<ð1ð  ð	1ð
 ˜S‘Mó1ðt %)ñ7Ø˜UŸ\™\Ñ*ð7à�u—z‘z 5¨$Ð.Ñ/ð7ð —<‘<ð7ð  ð	7ð
 ˜S‘Mó7ñtX U§\¡\ð X¸%¿+¹+ð XÐPXÐY\ÑP]ó Xñ \¨e¯l©lð \À5Ç;Á;ð \ÐYaÐbeÑYfó \ð: #$Ø$(ñØ�u—z‘z 5¨$Ð.Ñ/ðà�;‰;ðð �L‰Lðð  ð	ð
 ˜S‘Mðð ˆe�l‰lÑôr   