ó
    ‡Ž¡jSU  ã                   ót  • S r SSKrSSKJr  SSKJr  SSKrSSKJrJ	r	  Sr
\ " S S	5      5       r SS
\R                  S-  S\R                  \-  \-  S\R                  S\S\S-  4
S jjr SS
\R                  S-  S\R                  \-  \-  S\R                  S\S\S-  4
S jjrSS\R                  S\R&                  S\S-  4S jjrSS\R                  S\R&                  S\S-  4S jjr  SS\R                  \-  \-  S\R&                  S\R,                  S\S\S-  S\R                  S-  4S jjrg)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                   ó€  • \ rS rSr% Sr\\S'   \\S'   SS\S\S-  4S jjr S S\S\S	\S
\	R                  S\\	R                  S4   S\	R                  S-  4S jjr SS\	R                  S\S
\	R                  S	\S-  S\	R                  4
S jjr\  S!S\	R"                  S
\	R                  S\	R                  S\S\S-  4
S jj5       r\SS\	R                  S
\	R                  S\S-  4S jj5       r\S\	R(                  S\4S j5       r\  S"S\	R                  S-  S\	R                  S\S\S-  S\S\4S jj5       rSrg)#ÚAttentionMaskConverteré#   aÝ  
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                 óÈ   • [         R                  " [        [        5        Xl        X l        U R
                  b*  U R
                  S::  a  [        SU R
                   S35      eg g )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      Ú³C:\Users\johnn\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.13_qbz5n2kfra8p0\LocalCache\local-packages\Python313\site-packages\transformers/modeling_attn_mask_utils.pyÚ__init__ÚAttentionMaskConverter.__init__F   ss   € Ü�ŠÔ)¬=Ô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                 óÒ   • U R                   (       d  [        SU R                   S35      eX4nX2-
  nSnUS   S:”  d  U R                  b  U R	                  UUUUU R                  S9nU$ )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_4dÚ#AttentionMaskConverter.to_causal_4dQ   s‰   € ð �~�~ÜÐAÀ$Ç.Á.ÐAQÐQnÐoÓpÐpð "Ð0ˆØ!1Ñ!@Ðð ˆØ�r‰?˜QÓ $×"5Ñ"5Ñ"AØ!×3Ñ3ØØØØ'=Ø#×2Ñ2ð 4ð ˆNð Ðr   Úattention_mask_2dc                 óü  • UR                   S   U4nSnUS   S:”  d  U R                  bK  U R                  (       a:  Uc  [        S5      eXB-
  nU R	                  UUUR
                  UU R                  S9nOU R                  b  [        S5      eU R                  XUS   S9R                  UR
                  5      nUb>  UR                  UR                  5       [        R                  " U5      R                  5      nUn	U	$ )	z÷
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_4dÚ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           	      óH  • [         R                  " [        [        5        U u  pV[        R
                  " Xf4[        R                  " U5      R                  US9n[        R                  " UR                  S5      US9nUR                  XˆS-   R                  UR                  S5      S5      :  S5        UR                  U5      nUS:”  a*  [        R                  " [        R                  " XcXS9U/SS9nUbŒ  X4-
  S-
  n	[        R                  " [        R                   " U[        R"                  S9U	S	9n
[%        5       (       a  UR'                  5       nUR                  U
[        R                  " U5      R                  5        USSSS2SS24   R)                  USXfU-   5      $ )
z:
Make causal mask used for bi-directional self-attention.
)r   r!   r   r   ©r   r   )ÚdimN©r   )Údiagonal)r   r   r   r   r3   Úfullr4   r5   ÚarangeÚsizeÚmasked_fill_Úviewr0   ÚcatÚzerosÚtrilÚ	ones_liker2   r   ÚcloneÚexpand)r:   r   r   r#   r   Úbszr,   ÚmaskÚ	mask_condr?   Úcontext_masks              r   r%   Ú(AttentionMaskConverter._make_causal_mask¡   sM  € ô 	�ŠÔ)¬=Ô9à&‰ˆÜ�zŠz˜7Ð,¬e¯kªk¸%Ó.@×.DÑ.DÈVÑTˆÜ—L’L §¡¨2£°vÑ>ˆ	Ø×Ñ˜)°1¡}×&:Ñ&:¸4¿9¹9ÀR»=È!Ó&LÑLÈaÔPà�w‰w�u‹~ˆà! AÓ%Ü—9’9œeŸkšk¨'ÐQVÑ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ÐH^Ñ>^Ó_Ð_r   rL   r,   c                 ó–  • [         R                  " [        [        5        U R	                  5       u  p4Ub  UOUnU SS2SSSS24   R                  USX$5      R                  U5      n[        R                  " SUS9U-
  nUR                  UR                  [        R                  5      [        R                  " U5      R                  5      $ )zW
Expands attention_mask from `[bsz, seq_len]` to `[bsz, 1, tgt_seq_len, src_seq_len]`.
Nr   ç      ð?r>   )r   r   r   r   rB   rJ   r0   r3   Útensorr1   r2   r4   r5   )rL   r   r,   rK   Úsrc_lenÚexpanded_maskÚinverted_masks          r   r/   Ú#AttentionMaskConverter._expand_maskÅ   s¡   € ô
 	�ŠÔ)¬=Ô9à—y‘y“{‰ˆØ$Ñ0‘'°gˆàšQ  dªAÐ-Ñ.×5Ñ5°c¸1¸gÓO×RÑRÐSXÓYˆäŸš S°Ñ6¸ÑFˆà×(Ñ(¨×)9Ñ)9¼%¿*¹*Ó)EÄuÇ{Â{ÐSXÓGY×G]ÑG]Ó^Ð^r   rT   Ú	min_dtypec                 óâ   • [         R                  " [        [        5        U R                  [
        R                  :X  a  [        S5      eU R                  [
        R                  " X:H  SSS9) 5      $ )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)r=   Úkeepdim)
r   r   r   r   r   r3   r2   r   ÚmulÚall)rT   rW   s     r   Ú_unmask_unattendedÚ)AttentionMaskConverter._unmask_unattendedÕ   s_   € ôR 	�ŠÔ)¬=Ô9ð ×Ñ¤%§*¡*Ó,ÜØnóð ð × Ñ ¤%§)¢)¨MÑ,FÈBÐX\Ñ"]Ð!]Ó^Ð^r   Úattention_maskÚinputs_embedsÚis_trainingc                 ó˜  • [         R                  " [        [        5        UR                  S   UR                  S   peXb-   n[        U5      nSn	U c%  U(       d  U(       d  US:X  d  Xv:X  a
  Ub  Xs:  a  Sn	U	$ Ub  Xs:  aL  [        U R                  5      S:X  a  gU(       d+  [        R                  " U S:H  5      (       a  US:X  d  Xv:X  a  Sn	U	$ )a  
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   Úlenr3   r[   )
r^   r_   r#   r   r`   Ú_r   r   Úis_tracing_Úignore_causal_masks
             r   Ú_ignore_causal_mask_sdpaÚ/AttentionMaskConverter._ignore_causal_mask_sdpa  sÔ   € ô" 	�ŠÔ)¬=Ô9à'×-Ñ-¨aÑ0°-×2EÑ2EÀaÑ2Hˆ<Ø'Ñ@Ðä  Ó/ˆà"ÐàÑ!ö ¦KØ! QÓ&Ð*:Ó*JØ#Ñ+Ð/?Ó/Pà%)Ð"ð "Ð!ð Ñ#Ð'7Ó'HÜ�>×'Ñ'Ó(¨AÓ-ØÞ ¤U§Y¢Y¨~ÀÑ/B×%CÑ%CØ 1Ó$Ð(8Ó(Hà)-Ð&ð "Ð!r   ©r   r   ©N)Úcpu©r   N)NF)Ú__name__Ú
__module__Ú__qualname__Ú__firstlineno__Ú__doc__r2   Ú__annotations__Úintr   r3   r   r   r   ÚTensorr(   r8   ÚstaticmethodÚSizer%   r/   ÚFloatTensorÚfloatr\   rg   Ú__static_attributes__© 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	   r^   r&   r_   r#   r   c                 ó‚  • [        SUS9nUS   U-   nU b8  [        U R                  5      S:X  a  UR                  XS   XbR                  S9n U $ U bÂ  [        U R                  5      S:X  a©  US   SUS   U4n[        U R                  5      U:w  a%  [        S	[        U R                  5       S
U S35      eSU -
  nUR                  UR                  [        R                  5      [        R                  " UR                  5      R                  5      n  U $ UR                  US   US   XbR                  UR                  S9n U $ )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.
Tri   r!   é   )r   r   rb   r   r   z#Incorrect 4D attention_mask shape: z; expected: Ú.rQ   r<   )r	   rc   r-   r8   r   Útupler   r1   r0   r3   r2   r4   r5   r(   r   )	r^   r&   r_   r#   r   Úattn_mask_converterr   Úexpected_shaperU   s	            r   Ú!_prepare_4d_causal_attention_maskr�   D  sg  € ô. 1¸4ÐP^Ñ_Ðà" 2‘Ð)?Ñ?Ðð Ñ!¤c¨.×*>Ñ*>Ó&?À1Ó&DØ,×2Ñ2Ø¨™OÐ>N×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                 ó
  • [        SUS9nUS   U-   n[        U5      n[         R                  U UUUS9nU(       a  Sn	U	$ U c.  UR                  US   US   XbR                  UR
                  S9n	U	$ U R                  5       S:X  a  U n	OUR                  U US   UR                  US	9n	U(       dV  U	R
                  R                  S
;   a<  [         R                  U	[        R                  " UR                  5      R                  S9n	U	$ )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).
Tri   r!   )r^   r_   r#   r   Nr   r<   rb   )r   r   )ÚcudaÚxpu)rW   )r	   r   rg   r(   r   r   r=   r8   Útyper\   r3   r4   r5   )
r^   r&   r_   r#   r   r   r   re   rf   r7   s
             r   Ú*_prepare_4d_causal_attention_mask_for_sdpar†   y  s@  € ô 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   rL   r   r,   c                 ó*   • [         R                  XUS9$ )á¦  
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.
©rL   r   r,   )r	   r/   r‰   s      r   Ú_prepare_4d_attention_maskrŠ   ³  s   € ô "×.Ñ.°DÈwÐ.ÐWÐWr   c                 óð   • [         R                  " [        [        5        U R                  u  p4Ub  UOUn[        U 5      (       d  [        R                  " U S:H  5      (       a  g[        R                  XUS9$ )rˆ   Nr   r‰   )
r   r   r   r   r-   r   r3   r[   r	   r/   )rL   r   r,   rd   r   s        r   Ú#_prepare_4d_attention_mask_for_sdparŒ   Ã  se   € ô ‡M‚MÔ%¤}Ô5àŸ*™*Ñ€AØ Ñ,‰gÐ2B€Gô �d×Ñ¤§	¢	¨$°!©)× 4Ñ 4Øä%×2Ñ2¸ÐSZÐ2Ð[Ð[r   r   r   c                 óX   • [        SUS9nX0S   -   nUR                  U S   U S   XaUS9nU$ )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.
Tri   r!   r   r<   )r	   r(   )r&   r   r   r#   r   r   r   r^   s           r   Ú _create_4d_causal_attention_maskrŽ   Ü  sN   € ô( 1¸4ÐP^Ñ_Ðà-¸B±Ñ?ÐØ(×5Ñ5Ø�A‰˜ B™Ð)9Èvð 6ð €Nð Ðr   rj   rl   )rq   r   Údataclassesr   Útypingr   r3   Úutils.import_utilsr   r   r   r	   rt   rv   r~   Úlistrs   r�   r†   r   rŠ   rŒ   r   rŽ   rz   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   