Ë
    ÛÓ^jSU  ã                   ó`  — d Z ddlZddlmZ ddlmZ ddlZddlmZm	Z	 dZ
e G d„ d	«      «       Z	 dd
ej                  dz  dej                  ez  ez  dej                  dededz  f
d„Z	 dd
ej                  dz  dej                  ez  ez  dej                  dededz  f
d„Zddej                  dej&                  dedz  fd„Zddej                  dej&                  dedz  fd„Z	 	 ddej                  ez  ez  dej&                  dej,                  dededz  dej                  dz  fd„Zy)a  
IMPORTANT NOTICE: Every class and function in this file is deprecated in favor of using the much more general
`masking_utils.py` primitives. New code should not rely on it, it is only kept for backward compatibility for now,
and will be removed in the future.
é    N)Ú	dataclass)ÚUnioné   )Úis_torchdynamo_compilingÚ
is_tracingzÐThe attention mask API under `transformers.modeling_attn_mask_utils` (`AttentionMaskConverter`) is deprecated and will be removed in Transformers v5.10. Please use the new API in `transformers.masking_utils`.c                   ó^  — e Zd ZU dZeed<   eed<   ddededz  fd„Z	 ddededed	ej                  d
e
ej                  df   dej                  dz  fd„Z	 ddej                  ded	ej                  dedz  dej                  f
d„Ze	 	 ddej                   d	ej                  d
ej                  dededz  f
d„«       Zeddej                  d	ej                  dedz  fd„«       Zedej&                  defd„«       Ze	 	 d dej                  dz  dej                  dededz  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                 óÆ   — t        j                  t        t        «       || _        || _        | 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 `ú`)ÚwarningsÚwarnÚDEPRECATION_MESSAGEÚFutureWarningr
   r   Ú
ValueError)Úselfr
   r   s      úp/var/www/ramen.bs-engineer-server.com/venv/lib/python3.12/site-packages/transformers/modeling_attn_mask_utils.pyÚ__init__zAttentionMaskConverter.__init__F   sw   € Ü�‰Ô)¬=Ô9à"ˆŒØ,ˆÔà×ÑÐ*¨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_4dQ   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_4dr   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                 óZ  — t        j                  t        t        «       | \  }}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   r   r   r   r0   Úfullr1   r2   ÚarangeÚsizeÚmasked_fill_Úviewr-   ÚcatÚzerosÚtrilÚ	ones_liker/   r   ÚcloneÚexpand)r6   r   r   r!   r   Úbszr)   ÚmaskÚ	mask_condr;   Úcontext_masks              r   r#   z(AttentionMaskConverter._make_causal_mask¡   sZ  € ô 	�‰Ô)¬=Ô9à&‰ˆˆ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   rH   r)   c                 ó˜  — t        j                  t        t        «       | j	                  «       \  }}|�|n|}| dd…dddd…f   j                  |d||«      j                  |«      }t        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   ç      ð?r:   )r   r   r   r   r>   rF   r-   r0   Útensorr.   r/   r1   r2   )rH   r   r)   rG   Úsrc_lenÚexpanded_maskÚinverted_masks          r   r,   z#AttentionMaskConverter._expand_maskÅ   s¥   € ô
 	�‰Ô)¬=Ô9à—y‘y“{‰ˆˆWØ$Ð0‘'°gˆàšQ  dªAÐ-Ñ.×5Ñ5°c¸1¸gÀwÓO×RÑRÐSXÓYˆäŸ™ S°Ô6¸ÑFˆà×(Ñ(¨×)9Ñ)9¼%¿*¹*Ó)EÄuÇ{Á{ÐSXÓGY×G]ÑG]Ó^Ð^r   rO   Ú	min_dtypec                 óä   — t        j                  t        t        «       | 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)r9   Úkeepdim)
r   r   r   r   r   r0   r/   r   ÚmulÚall)rO   rQ   s     r   Ú_unmask_unattendedz)AttentionMaskConverter._unmask_unattendedÕ   sa   € ôR 	�‰Ô)¬=Ô9ð ×Ñ¤%§*¡*Ò,ÜØnóð ð × Ñ ¤%§)¡)¨M¸YÑ,FÈBÐX\Ô"]Ð!]Ó^Ð^r   Úattention_maskÚinputs_embedsÚis_trainingc                 ód  — t        j                  t        t        «       |j                  d   |j                  d   }}||z   }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   r   r   r*   r   Úlenr0   rU   )
rW   rX   r!   r   rY   Ú_r   r   Úis_tracing_Úignore_causal_masks
             r   Ú_ignore_causal_mask_sdpaz/AttentionMaskConverter._ignore_causal_mask_sdpa  sÞ   € ô" 	�‰Ô)¬=Ô9à'×-Ñ-¨aÑ0°-×2EÑ2EÀaÑ2Hˆ<ˆØ'Ð*@Ñ@Ðä  Ó/ˆà"ÐàÐ!ñ ¡KØ! QÒ&Ð*:¸lÒ*JØ#Ð+Ð/?À.Ò/Pà%)Ð"ð "Ð!ð Ð#Ð'7¸.Ò'HÜ�>×'Ñ'Ó(¨AÒ-ØÙ ¤U§Y¡Y¨~ÀÑ/BÔ%CØ 1Ò$Ð(8¸LÒ(Hà)-Ð&ð "Ð!r   ©N)Úcpu©r   N)NF)Ú__name__Ú
__module__Ú__qualname__Ú__doc__r/   Ú__annotations__Úintr   r0   r   r   r   ÚTensorr&   r5   ÚstaticmethodÚSizer#   r,   ÚFloatTensorÚfloatrV   r`   © r   r   r	   r	   #   s  … ñð< ƒOØÓñ	 $ð 	¸¸d¹
ó 	ð" .3ñàðð ðð ð	ð
 �{‰{ðð �e—l‘l EÐ)Ñ*ðð 
�‰˜Ñ	óðL (,ñ- à Ÿ<™<ð- ð ð- ð �{‰{ð	- ð
  ™*ð- ð 
�‰ó- ð^ ð
 '(Ø%)ñ!`ØŸ™ð!`à�{‰{ð!`ð —‘ð!`ð !$ð	!`ð
 ˜d™
ò!`ó ð!`ðF ñ_˜5Ÿ<™<ð _°·±ð _ÀcÈDÁjò _ó ð_ð ð0_Ø×(Ñ(ð0_àò0_ó ð0_ðd ð
 &*Ø!ñ8"ØŸ™ tÑ+ð8"à—|‘|ð8"ð !$ð8"ð ˜d™
ð	8"ð
 ð8"ð 
ò8"ó ñ8"r   r	   rW   r$   rX   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   r[   r   r   z#Incorrect 4D attention_mask shape: z; expected: ú.rL   r8   )r	   r\   r*   r5   r   Útupler   r.   r-   r0   r/   r1   r2   r&   r   )	rW   r$   rX   r!   r   Úattn_mask_converterr   Úexpected_shaperP   s	            r   Ú!_prepare_4d_causal_attention_maskrw   D  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        |«      }t         j                  | |||¬«      }|rd}	|	S | €2|j                  |d   |d   ||j                  |j
                  ¬«      }	|	S | j                  «       dk(  r| }	n"|j                  | |d   |j                  |¬	«      }	|sV|	j
                  j                  d
v 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).
    Trq   r   )rW   rX   r!   r   Nr   r8   r[   )r   r   )ÚcudaÚxpu)rQ   )r	   r   r`   r&   r   r   r9   r5   ÚtyperV   r0   r1   r2   )
rW   r$   rX   r!   r   ru   r   r^   r_   r4   s
             r   Ú*_prepare_4d_causal_attention_mask_for_sdpar|   y  sB  € ô 1¸4ÐP^Ô_Ðà" 2‘Ð)?Ñ?Ðô
 ˜]Ó+€Kä/×HÑHØ%Ø#Ø5Ø%ð	 Ió Ðñ ØÐð0 Ðð/ 
Ð	Ø.×;Ñ;Ø˜‰N˜K¨™OÐ-=À]×EXÑEXÐan×auÑauð <ó 
Ðð, Ðð% ×ÑÓ 1Ò$Ø-Ñà2×8Ñ8ØØ˜B‘Ø#×)Ñ)Ø!1ð	  9ó  Ðñ Ð/×6Ñ6×;Ñ;¸ÑNÜ5×HÑHØ ¬E¯K©K¸×8KÑ8KÓ,L×,PÑ,Pð  Ió  Ðð Ðr   rH   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.
    ©rH   r   r)   )r	   r,   r   s      r   Ú_prepare_4d_attention_maskr€   ³  s   € ô "×.Ñ.°DÀÈwÐ.ÓWÐWr   c                 óà   — t        j                  t        t        «       | j                  \  }}|�|n|}t        | «      st        j                  | dk(  «      ryt        j                  | ||¬«      S )r~   Nr   r   )
r   r   r   r   r*   r   r0   rU   r	   r,   )rH   r   r)   r]   r   s        r   Ú#_prepare_4d_attention_mask_for_sdpar‚   Ã  sd   € ô ‡M�MÔ%¤}Ô5àŸ*™*Ñ€AÐØ Ð,‰gÐ2B€Gô �dÔ¤§	¡	¨$°!©)Ô 4Øä%×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.
    Trq   r   r   r8   )r	   r&   )r$   r   r   r!   r   ru   r   rW   s           r   Ú _create_4d_causal_attention_maskr„   Ü  sR   € ô( 1¸4ÐP^Ô_Ðà-°¸B±Ñ?ÐØ(×5Ñ5Ø�A‰˜ B™Ð)9ÀÈvð 6ó €Nð Ðr   ra   rc   )rg   r   Údataclassesr   Útypingr   r0   Úutils.import_utilsr   r   r   r	   rj   rl   rt   Úlistri   rw   r|   r   r€   r‚   r   r„   ro   r   r   ú<module>r‰      sµ  ðñó Ý !Ý ã ç Dðwð ð ÷]"ð ]"ó ð]"ðJ	 "&ñ1Ø—L‘L 4Ñ'ð1à—‘˜eÑ# dÑ*ð1ð —<‘<ð1ð  ð	1ð
 ˜$‘Jó1ðt "&ñ7Ø—L‘L 4Ñ'ð7à—‘˜eÑ# dÑ*ð7ð —<‘<ð7ð  ð	7ð
 ˜$‘Jó7ñtX U§\¡\ð X¸%¿+¹+ð XÐPSÐVZÑPZó Xñ \¨e¯l©lð \À5Ç;Á;ð \ÐY\Ð_cÑYcó \ð: #$Ø!%ñØ—‘˜eÑ# dÑ*ðà�;‰;ðð �L‰Lðð  ð	ð
 ˜$‘Jðð ‡\�\�DÑôr   