ó
    ‡Ž¡j: ã                   ó®  • % S SK Jr  S SKJr  S SKrS SKJs  Jr  SSK	J
r
  SSKJr  SSKJrJr  SSKJr  SS	KJrJr  SS
KJrJrJr  \" 5       (       a  S SKJr  S SKJrJr  O\R<                  r\" SSS9r\" 5       r \(       a  S SK!J"r"  \RF                  " \$5      r%S\S\4S jr&S\S\4S jr'S\(S\(S\(S\(S\)4
S jr*S\(S\(S\(S\(S\)4
S jr+S\(S\4S jr,S\(S\R<                  S\4S jr-S \R<                  S\4S! jr.S\(S\4S" jr/S\(S\4S# jr0S\(S\4S$ jr1S\(S\R<                  S\4S% jr2S&\R<                  S\4S' jr3S(\R<                  S\4S) jr4S*\S+\(S,\(S\4S- jr5S.\R<                  S-  S/\(S,\(S\R<                  S-  4S0 jr6S \R<                  S.\R<                  S-  S/\(S,\(S\R<                  4
S1 jr7S2\Rp                  S\Rp                  4S3 jr9 ShS&\R<                  S-  S4\(S/\(S+\(S,\(S5\(S-  S\)4S6 jjr:S&\R<                  S-  S/\(S5\(S-  S\)4S7 jr; ShS&\R<                  S-  S/\(S5\(S-  S\)4S8 jjr<S*\S\4S9 jr=S:\R<                  S;\R<                  S<\R<                  S=\R<                  4S> jr>\" S?S@SASB9S S \*SSSSCSSCSD4
SE\(S4\(S/\(S+\(S,\(S*\S.\R<                  S-  SF\(S-  SG\)SH\)S?\)SI\)SJ\R~                  \@-  S\R<                  S-  4SK jj5       rAS S \*S\R„                  SCSCSD4SE\(S4\(S/\(S+\(S,\(S*\S.\R<                  S-  SL\R†                  SH\)SI\)SJ\R~                  \@-  S\R<                  4SM jjrDS S \*S4SE\(S4\(S/\(S+\(S,\(S*\S.\R<                  S-  4SN jjrES S \*SSD4SE\(S4\(S/\(S+\(S,\(S*\S.\R<                  S-  SJ\R~                  \@-  S\4SO jjrF " SP SQ\5      rG\G" 5       rH\G\ISR'   SS\R<                  S\R<                  S-  4ST jrJ ShSU\SV\R<                  S.\R<                  \-  S-  SW\
S-  SS\R<                  S-  SX\(S-  SY\R<                  S-  S\K\)\R<                  \-  S-  \(\(4   4SZ jjrL      SiSU\SV\R<                  S.\R<                  S-  SW\
S-  SS\R<                  S-  S[\S-  S\\S-  S \R<                  S-  SX\(S-  SG\)S\R<                  \-  S-  4S] jjrM     SjSU\SV\R<                  S.\R<                  S-  SY\R<                  S-  SW\
S-  S[\S-  S\\S-  SH\)S\R<                  \-  S-  4S^ jjrN      SiSU\SV\R<                  S.\R<                  S-  SW\
S-  SS\R<                  S-  S[\S-  S\\S-  S \R<                  S-  SX\(S-  SG\)S\R<                  \-  S-  4S_ jjrO     SjSU\SV\R<                  S.\R<                  S-  SY\R<                  S-  SW\
S-  S[\S-  S\\S-  SH\)S\R<                  \-  S-  4S` jjrP     SjSU\SV\R<                  S.\R<                  S-  SW\
S-  SS\R<                  S-  S[\S-  S\\S-  SX\(S-  SG\)S\R<                  \-  S-  4Sa jjrQ ShSU\SV\R<                  S.\R<                  S-  SW\
S-  S\R<                  S-  4
Sb jjrR\M\O\Q\O\O\M\" \MSCSc9\" \MSCSc9\R\R\M\RSd.\M\RSe.Sf.rS    SkSU\SV\R<                  S.\R<                  S-  SW\
S-  SS\R<                  S-  S[\S-  S\\S-  S \R<                  S-  4Sg jjrTg)lé    )ÚCallable)ÚpartialNé   )ÚCache)ÚPreTrainedConfig)Úis_torch_xpu_availableÚlogging)Údeprecate_kwarg)ÚGeneralInterfaceÚis_flash_attention_requested)Úis_torch_flex_attn_availableÚis_torch_greater_or_equalÚ
is_tracing)Ú_DEFAULT_SPARSE_BLOCK_SIZE)Ú	BlockMaskÚcreate_block_maskz2.6T)Ú
accept_dev)ÚTransformGetItemToIndexÚmask_functionsÚreturnc                  ó^   ^ • [        S T  5       5      (       d  [        ST  35      eU 4S jnU$ )zKReturns a mask function that is the intersection of provided mask functionsc              3   ó8   #   • U  H  n[        U5      v •  M     g 7f©N©Úcallable©Ú.0Úargs     Ú¨C:\Users\johnn\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.13_qbz5n2kfra8p0\LocalCache\local-packages\Python313\site-packages\transformers/masking_utils.pyÚ	<genexpr>Úand_masks.<locals>.<genexpr>3   ó   é € Ð7ª Œx˜�}ˆ}ªùó   ‚ú.All inputs should be callable mask_functions: c                 óž   >• UR                  S[        R                  S9nT H'  nXE" XX#5      R                  UR                  5      -  nM)     U$ ©N© )Údtype)Únew_onesÚtorchÚboolÚtoÚdevice©Ú	batch_idxÚhead_idxÚq_idxÚkv_idxÚresultÚmaskr   s         €r   Úand_maskÚand_masks.<locals>.and_mask6   sH   ø€ Ø—‘ ¬%¯*©*�Ð5ˆÛ"ˆDØ˜d 9¸ÓF×IÑIÈ&Ï-É-ÓXÑXŠFñ #àˆó    ©ÚallÚRuntimeError)r   r5   s   ` r   Ú	and_masksr;   1   s4   ø€ äÑ7©Ó7×7Ñ7ÜÐKÈNÐK[Ð\Ó]Ð]õð €Or7   c                  ó^   ^ • [        S T  5       5      (       d  [        ST  35      eU 4S jnU$ )zDReturns a mask function that is the union of provided mask functionsc              3   ó8   #   • U  H  n[        U5      v •  M     g 7fr   r   r   s     r   r    Úor_masks.<locals>.<genexpr>A   r"   r#   r$   c                 óž   >• UR                  S[        R                  S9nT H'  nXE" XX#5      R                  UR                  5      -  nM)     U$ r&   )Ú	new_zerosr*   r+   r,   r-   r.   s         €r   Úor_maskÚor_masks.<locals>.or_maskD   sH   ø€ Ø—‘ ¬5¯:©:�Ð6ˆÛ"ˆDØ˜d 9¸ÓF×IÑIÈ&Ï-É-ÓXÑXŠFñ #àˆr7   r8   )r   rA   s   ` r   Úor_masksrC   ?   s4   ø€ äÑ7©Ó7×7Ñ7ÜÐKÈNÐK[Ð\Ó]Ð]õð €Nr7   r/   r0   r1   r2   c                 ó
   • X2:*  $ )z2
This creates a basic lower-diagonal causal mask.
r'   ©r/   r0   r1   r2   s       r   Úcausal_mask_functionrF   M   s   € ð ‰?Ðr7   c                 ó   • US:¬  $ )zw
This creates a full bidirectional mask.

NOTE: It is important to keep an index-based version for non-vmap expansion.
r   r'   rE   s       r   Úbidirectional_mask_functionrH   T   s   € ð �A‰:Ðr7   Úsliding_windowc           
      óT   ^ • S[         S[         S[         S[         S[        4
U 4S jjnU$ )zy
This is an overlay depicting a sliding window pattern. Add it on top of a causal mask for a proper sliding
window mask.
r/   r0   r1   r2   r   c                 ó   >• X2T-
  :„  $ r   r'   ©r/   r0   r1   r2   rI   s       €r   Ú
inner_maskÚ*sliding_window_overlay.<locals>.inner_maskc   s   ø€ Ø Ñ.Ñ.Ð.r7   ©Úintr+   ©rI   rM   s   ` r   Úsliding_window_overlayrR   ]   s3   ø€ ð/œcð /¬Sð /¼ð /Äcð /Ìd÷ /ð Ðr7   Ú
chunk_sizeÚleft_paddingc           
      óX   ^ ^• S[         S[         S[         S[         S[        4
U U4S jjnU$ )z
This is an overlay depicting a chunked attention pattern. Add it on top of a causal mask for a proper chunked
attention mask.
r/   r0   r1   r2   r   c                 ó2   >• UTU    -
  T-  UTU    -
  T-  :H  $ r   r'   )r/   r0   r1   r2   rS   rT   s       €€r   rM   Ú#chunked_overlay.<locals>.inner_masko   s.   ø€ Ø˜ iÑ0Ñ0°ZÑ?ÀEÈLÐYbÑLcÑDcÐhrÑCrÑrÐrr7   rO   )rS   rT   rM   s   `` r   Úchunked_overlayrX   i   s?   ù€ ðsœcð s¬Sð s¼ð sÄcð sÌd÷ sð sð Ðr7   Úblock_sequence_idsc           
      óT   ^ • S[         S[         S[         S[         S[        4
U 4S jjnU$ )aj  
This is an overlay depicting a blockwise masking pattern. Instead of a single
token, each block consists of arbitrary length tokens. In causal setup, each block
can attend to prev block causally and can't attend to future blocks. Within one block
the attention is always bidirectional.
Mostly used in MLLMs when non-text data attends bidirectionally to itself.
r/   r0   r1   r2   r   c                 ó0   >• TX4   nTX4   nXE:H  US:¬  -  $ )Nr   r'   )r/   r0   r1   r2   Úq_groupÚkv_grouprY   s         €r   rM   Ú%blockwise_overlay.<locals>.inner_mask~   s/   ø€ à$ YÐ%5Ñ6ˆØ% iÐ&7Ñ8ˆØÑ#¨°1©Ñ5Ð5r7   rO   )rY   rM   s   ` r   Úblockwise_overlayr_   u   s3   ø€ ð6œcð 6¬Sð 6¼ð 6Äcð 6Ìd÷ 6ð Ðr7   c                 ó4   • [        [        U 5      [        5      $ )zI
This return the mask_function function to create a sliding window mask.
)r;   rR   rF   ©rI   s    r   Ú#sliding_window_causal_mask_functionrb   ‡   s   € ô Ô+¨NÓ;Ô=QÓRÐRr7   c           
      óT   ^ • S[         S[         S[         S[         S[        4
U 4S jjnU$ )zF
This is an overlay depicting a bidirectional sliding window pattern.
r/   r0   r1   r2   r   c                 ó$   >• [        X#-
  5      T:*  $ )zŒA token can attend to any other token if their absolute distance is within
the (inclusive) sliding window size (distance <= sliding_window).)ÚabsrL   s       €r   rM   Ú8sliding_window_bidirectional_overlay.<locals>.inner_mask“   s   ø€ ô �5‘>Ó" nÑ4Ð4r7   rO   rQ   s   ` r   Ú$sliding_window_bidirectional_overlayrg   Ž   s3   ø€ ð
5œcð 5¬Sð 5¼ð 5Äcð 5Ìd÷ 5ð
 Ðr7   c                 ó4   • [        [        U 5      [        5      $ )zW
This return the mask_function function to create a bidirectional sliding window mask.
)r;   rg   rH   ra   s    r   Ú*sliding_window_bidirectional_mask_functionri   ›   s   € ô Ô9¸.ÓIÔKfÓgÐgr7   c                 ó4   • [        [        X5      [        5      $ )zL
This return the mask_function function to create a chunked attention mask.
)r;   rX   rF   )rS   rT   s     r   Úchunked_causal_mask_functionrk   ¢   s   € ô ”_ ZÓ>Ô@TÓUÐUr7   Úpadding_maskc           
      óT   ^ • S[         S[         S[         S[         S[        4
U 4S jjnU$ )zL
This return the mask_function function corresponding to a 2D padding mask.
r/   r0   r1   r2   r   c                 ó   >• TX4   $ r   r'   )r/   r0   r1   r2   rl   s       €r   rM   Ú)padding_mask_function.<locals>.inner_mask®   s   ø€ ð ˜IÐ-Ñ.Ð.r7   rO   )rl   rM   s   ` r   Úpadding_mask_functionrp   ©   s3   ø€ ð
/œcð /¬Sð /¼ð /Äcð /Ìd÷ /ð Ðr7   Úpacked_sequence_maskc           
      óT   ^ • S[         S[         S[         S[         S[        4
U 4S jjnU$ )zT
This return the mask_function function corresponding to a 2D packed sequence mask.
r/   r0   r1   r2   r   c                 ó   >• TX4   TX4   :H  $ r   r'   )r/   r0   r1   r2   rq   s       €r   rM   Ú1packed_sequence_mask_function.<locals>.inner_mask¼   s   ø€ Ø# IÐ$4Ñ5Ð9MÈiÐN_Ñ9`Ñ`Ð`r7   rO   )rq   rM   s   ` r   Úpacked_sequence_mask_functionru   ·   s9   ø€ ð
aœcð a¬Sð a¼ð aÄcð aÌd÷ að Ðr7   Úmask_functionÚq_offsetÚ	kv_offsetc           
      ó\   ^ ^^• S[         S[         S[         S[         S[        4
UU U4S jjnU$ )z‰
This function adds the correct offsets to the `q_idx` and `kv_idx` as the torch API can only accept lengths,
not start and end indices.
r/   r0   r1   r2   r   c                 ó$   >• T" XUT-   UT-   5      $ r   r'   )r/   r0   r1   r2   rx   rv   rw   s       €€€r   rM   Ú0add_offsets_to_mask_function.<locals>.inner_maskÈ   s   ø€ Ù˜Y°%¸(Ñ2BÀFÈYÑDVÓWÐWr7   rO   )rv   rw   rx   rM   s   ``` r   Úadd_offsets_to_mask_functionr|   Â   s?   ú€ ðXœcð X¬Sð X¼ð XÄcð XÌd÷ Xñ Xð Ðr7   Úattention_maskÚ	kv_lengthc                 óœ   • U nU bF  X-   U R                   S   -
  =nS:”  a,  [        R                  R                  R	                  U SU45      nU$ )z`
From the 2D attention mask, prepare the correct padding mask to use by potentially padding it.
éÿÿÿÿr   )Úshaper*   ÚnnÚ
functionalÚpad)r}   r~   rx   Úlocal_padding_maskÚpadding_lengths        r   Úprepare_padding_maskr‡   Î   sY   € ð (ÐØÑ!à'Ñ3°n×6JÑ6JÈ2Ñ6NÑNÐNˆNÐRSÓSÜ!&§¡×!4Ñ!4×!8Ñ!8¸È!È^ÐI\Ó!]ÐØÐr7   c                 ój   • X#-   U R                   S   -
  =nS:”  a  [        R                  " U SU4SS9n U $ )z¿
Pads the `block_sequence_ids` in case the total length is less than `kv_length`.
Usually that happens with `StaticCache` generation or generating without cache.
Pads to the right with `-1`.
r€   r   )r„   Úvalue)r�   ÚFr„   )rY   r}   r~   rx   r†   s        r   Úmaybe_pad_block_sequence_idsr‹   Ú   sF   € ð $Ñ/Ð2D×2JÑ2JÈ2Ñ2NÑNÐNˆÐRSÓSÜŸUšUÐ#5¸A¸~Ð;NÐVXÑYÐØÐr7   Útensorc                 óD   • U R                  5       U R                  5       :H  $ )ziSimilar to `tensor.all()`, but uses an implementation with `tensor.sum()`, which is actually much faster.)ÚsumÚnumel)rŒ   s    r   Úfast_allr�   ç   s   € à�:‰:‹<˜6Ÿ<™<›>Ñ)Ð)r7   Úq_lengthÚlocal_attention_sizec                 óp  • U b=  U R                   S   U:”  a*  [        R                  " X R                  S9U-   nU SS2U4   n [	        U 5      (       a  gUb  X%:¼  a  gUS:X  d  X!:X  a  U b  [        U 5      (       a  gUS:X  a7  U b3  [        U SS2SU24   5      (       a  [        U SS2US24   ) 5      (       a  gg)a¿  
Detects whether the 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 2D `padding_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).
Nr€   ©r-   Fr   Tr   )r�   r*   Úaranger-   r   r�   )rl   r‘   r~   rw   rx   r’   Úmask_indicess          r   Ú_ignore_causal_mask_sdpar—   ì   sË   € ð  Ñ L×$6Ñ$6°rÑ$:¸YÓ$FÜ—|’| I×6IÑ6IÑJÈYÑVˆØ#¢A | OÑ4ˆô �,×ÑØàÑ'¨IÓ,MØð
 	�A‹˜Ó.°\Ñ5IÌXÐVb×McÑMcØð �1ƒ}ØÑ¤¨,²q¸)¸8¸)°|Ñ*D×!EÑ!EÌ(ÐT`ÒabÐdlÑdmÐamÑTnÐSn×JoÑJoààr7   c                 ó^   • [        U 5      (       a  gUb  X:¼  a  gU c  gU R                  5       $ )z³
XPU-specific logic for determining if we can skip bidirectional mask creation.

For XPU devices, we have special handling:
- Skip if no padding and no local attention constraint
FT)r   r9   ©rl   r~   r’   s      r   Ú _can_skip_bidirectional_mask_xpurš     s<   € ô �,×ÑØð Ñ'¨IÓ,MØàÑàð ×ÑÓÐr7   c                 ó”   • [         (       a  [        XU5      $ [        U 5      (       d!  U b  U R                  5       (       a	  Ub  X:  a  gg)aš  
Detects whether the bidirectional mask can be ignored in case PyTorch's SDPA is used.

In case no token is masked in the 2D `padding_mask` argument and no local attention constraint applies
(i.e. `local_attention_size` is None or `kv_length < local_attention_size`), we skip mask creation,
allowing to dispatch to the flash attention kernel (that can otherwise not be used if a custom `attn_mask` is
passed).
TF)Ú_is_torch_xpu_availablerš   r   r9   r™   s      r   Ú_ignore_bidirectional_mask_sdpar�   5  sL   € ÷ Òô 0°ÐI]Ó^Ð^ô
 �|×$Ñ$ØÑ! \×%5Ñ%5×%7Ñ%7à!Ñ)¨YÓ-Mààr7   c                 óJ   • / SQnU H  n[         R                  " XSS9n M     U $ )a:  
Used to vmap our mask_functions over the all 4 dimensions (b_idx, h_idx, q_idx, kv_idx) of the inputs.
Using vmap here allows us to keep the performance of vectorized ops, while having a single set of primitive
functions between attention interfaces (i.e. between flex and sdpa/eager, FA2 being a bit different).
))NNNr   )NNr   N)Nr   NN)r   NNNr   )Úin_dimsÚout_dims)r*   Úvmap)rv   Ú
dimensionsÚdimss      r   Ú_vmap_expansion_sdpar¤   T  s*   € ò n€JÛˆÜŸ
š
 =ÈÑKŠñ àÐr7   Úbatch_indicesÚhead_indicesÚ	q_indicesÚ
kv_indicesc                 ób   • U SS2SSS4   n USSS2SS4   nUSSSS2S4   nUSSSSS24   nXX#4$ )a´  
Used to broadcast our mask_functions over the all 4 dimensions (b_idx, h_idx, q_idx, kv_idx) of the inputs.
Allows the usage of any index-based mask function without relying on vmap.

NOTE: This is limited to index based functions only and is not guaranteed to work otherwise.

Reference:
    - https://github.com/huggingface/optimum-onnx/blob/c123e8f4fab61b54a8e0e31ce74462bcacca576e/optimum/exporters/onnx/model_patcher.py#L362-L365
Nr'   )r¥   r¦   r§   r¨   s       r   Ú_non_vmap_expansion_sdparª   a  s[   € ð "¢! T¨4°Ð"5Ñ6€MØ ¢a¨¨tÐ 3Ñ4€LØ˜$ ¢a¨Ð-Ñ.€IØ˜D $¨ªaÐ/Ñ0€JØ¨	Ð=Ð=r7   Úallow_torch_fixz5.18.0zIt has no effect anymore.)ÚversionÚadditional_messageFÚcpuÚ
batch_sizeÚ
local_sizeÚallow_is_causal_skipÚallow_is_bidirectional_skipÚuse_vmapr-   c                 óZ  • [        XbU5      nU(       a  [        XáX#XG5      (       a  gU	(       a  [        XâU5      (       a  gUb  [        U[	        U5      5      n[
        R                  " XS9n[
        R                  " SUS9n[
        R                  " XS9U-   n[
        R                  " X,S9U-   nU(       d&  U" [        UUUU5      6 nUR                  U SX5      nU$ [        (       a)  [        5          [        U5      " UUUU5      nSSS5        U$ [        S5      e! , (       d  f       U$ = f)u®  
Create a 4D boolean mask of shape `(batch_size, 1, query_length, kv_length)` where a value of True indicates that
the element should take part in the attention computation, and False that it should not.
This function can only be used with torch>=2.5, as the context manager is otherwise not available.

Args:
    batch_size (`int`):
        The batch size of the input sequence.
    q_length (`int`):
        The size that the query states will have during the attention computation.
    kv_length (`int`):
        The size that the key and value states will have during the attention computation.
    kv_offset (`int`, optional):
        An optional offset to indicate at which first position the key and values states will refer to.
    q_offset (`int`, optional):
        An optional offset to indicate at which first position the query states will refer to.
    mask_function (`Callable`):
        The mask factory function describing the mask pattern.
    attention_mask (`torch.Tensor`, optional):
        The 2D attention mask corresponding to padded tokens of shape (batch_size, number_of_seen_tokens+q_length)
    local_size (`int`, optional):
        The size of the local attention, if we do not use full attention. This is used only if `allow_is_causal_skip=True`
        to try to skip mask creation if possible.
    allow_is_causal_skip (`bool`, optional):
        Whether to allow to return `None` for the mask under conditions where we can use the `is_causal` argument in
        `torch.sdpa` instead. Default to `True`.
    allow_is_bidirectional_skip (`bool`, optional):
        Whether to allow to return `None` for the mask under conditions where we do not have to add any bias,
        i.e. full attention without any padding. Default to `False`.
    allow_torch_fix (`bool`, optional):
        Deprecated and has no effect. Will be removed in version 5.18.0.
    use_vmap (`bool`, optional):
        Whether to use `vmap` during the mask construction or not. Allows powerful custom patterns that may not be
        index-based (for the cost of speed performance). By default `False`.
    device (`torch.device` or `str`, optional):
        An optional device to create the mask on.


## Creating a simple causal mask:

To create the following causal mask:

    0 â–  â¬š â¬š â¬š â¬š
    1 â–  â–  â¬š â¬š â¬š
    2 â–  â–  â–  â¬š â¬š
    3 â–  â–  â–  â–  â¬š
    4 â–  â–  â–  â–  â– 

You can do

```python
>>> sdpa_mask(batch_size=1, q_length=5, kv_length=5)
>>> tensor([[[[ True, False, False, False, False],
              [ True,  True, False, False, False],
              [ True,  True,  True, False, False],
              [ True,  True,  True,  True, False],
              [ True,  True,  True,  True,  True]]]])
```

## Creating a sliding window mask:

To create the following sliding window mask (`sliding_window=3`):

    0 â–  â¬š â¬š â¬š â¬š
    1 â–  â–  â¬š â¬š â¬š
    2 â–  â–  â–  â¬š â¬š
    3 â¬š â–  â–  â–  â¬š
    4 â¬š â¬š â–  â–  â– 

You can do

```python
>>> sdpa_mask(batch_size=1, q_length=5, kv_length=5, mask_function=sliding_window_causal_mask_function(3))
>>> tensor([[[[ True, False, False, False, False],
              [ True,  True, False, False, False],
              [ True,  True,  True, False, False],
              [False,  True,  True,  True, False],
              [False, False,  True,  True,  True]]]])
```

## Creating a chunked attention mask

To create the following chunked attention mask (`chunk_size=3`):

    0 â–  â¬š â¬š â¬š â¬š
    1 â–  â–  â¬š â¬š â¬š
    2 â–  â–  â–  â¬š â¬š
    3 â¬š â¬š â¬š â–  â¬š
    4 â¬š â¬š â¬š â–  â– 

You can do

```python
>>> sdpa_mask(batch_size=1, q_length=5, kv_length=5, mask_function=chunked_causal_mask_function(3, torch.zeros(1, dtype=int)))
>>> tensor([[[[ True, False, False, False, False],
            [ True,  True, False, False, False],
            [ True,  True,  True, False, False],
            [False, False, False,  True, False],
            [False, False, False,  True,  True]]]])
```

Nr”   r   r€   zœThe vmap functionality for mask creation is only supported from torch>=2.6. Please update your torch version or use `use_vmap=False` with index-based masks.)r‡   r—   r�   r;   rp   r*   r•   rª   ÚexpandÚ#_is_torch_greater_or_equal_than_2_6r   r¤   Ú
ValueError)r¯   r‘   r~   rw   rx   rv   r}   r°   r±   r²   r«   r³   r-   Úkwargsrl   Úbatch_arangeÚhead_arangeÚq_arangeÚ	kv_aranges                      r   Ú	sdpa_maskr½   t  s4  € ôp (¨À9ÓM€Lö
 Ô 8Ø 	°Y÷!ñ !ð Þ"Ô'FÀ|Ð`j×'kÑ'kØð ÑÜ! -Ô1FÀ|Ó1TÓUˆä—<’< 
Ñ:€LÜ—,’,˜q¨Ñ0€KÜ�|Š|˜HÑ4°xÑ?€HÜ—’˜YÑ6¸ÑB€Iö á&Ô(@ÀÈ{Ð\dÐfoÓ(pÐqˆà'×.Ñ.¨z¸2¸xÓSˆð" Ð÷ 
-Ò	,ô %Õ&Ü1°-Ô@ÀÈ{Ð\dÐfoÓpˆN÷ 'ð Ðô ð_ó
ð 	
÷ 'Ô&ð Ðús   Ã1DÄ
D*r(   c                 ó
  • UR                  SS5      n[        SU UUUUUUSUU	U
S.UD6nUbV  [        R                  " U5      R                  n[        R
                  " U[        R                  " SUR                  US9U5      nU$ )a°  
Create a 4D float mask of shape `(batch_size, 1, query_length, kv_length)` where a value of 0 indicates that
the element should take part in the attention computation, and -inf (minimum value for the given `dtype`) that
it should not.

Args:
    batch_size (`int`):
        The batch size of the input sequence.
    q_length (`int`):
        The size that the query states will have during the attention computation.
    kv_length (`int`):
        The size that the key and value states will have during the attention computation.
    q_offset (`int`, optional):
        An optional offset to indicate at which first position the query states will refer to.
    kv_offset (`int`, optional):
        An optional offset to indicate at which first position the key and values states will refer to.
    mask_function (`Callable`):
        The mask factory function describing the mask pattern.
    attention_mask (`torch.Tensor`, optional):
        The 2D attention mask corresponding to padded tokens of shape (batch_size, number_of_seen_tokens+q_length)
    dtype (`torch.dtype`, optional):
        The dtype to use for the mask. By default, `torch.float32`.
    allow_is_bidirectional_skip (`bool`, optional):
        Whether to allow to return `None` for the mask under conditions where we do not have to add any bias,
        i.e. full attention without any padding. Default to `False`.
    use_vmap (`bool`, optional):
        Whether to use `vmap` during the mask construction or not. Allows powerful custom patterns that may not be
        index-based (for the cost of speed performance). By default `False`.
    device (`torch.device` or `str`, optional):
        An optional device to create the mask on.
r±   NF)r¯   r‘   r~   rw   rx   rv   r}   r±   r²   r³   r-   g        ©r-   r(   r'   )Úpopr½   r*   ÚfinfoÚminÚwhererŒ   r-   )r¯   r‘   r~   rw   rx   rv   r}   r(   r²   r³   r-   r¸   Ú_r4   Ú	min_dtypes                  r   Ú
eager_maskrÆ     s•   € ð\ 	�
‰
Ð)¨4Ó0€AÜð ØØØØØØ#Ø%Ø"Ø$?ØØñð ñ€Dð ÑÜ—K’K Ó&×*Ñ*ˆ	ä�{Š{˜4¤§¢¨c¸$¿+¹+ÈUÑ!SÐU^Ó_ˆØ€Kr7   c                 óx   • Ub6  USS2U* S24   nUR                   S   U:X  a  UR                  5       (       a  SnU$ )a8  
Create the attention mask necessary to use FA2. Since FA2 is un-padded by definition, here we simply return
`None` if the mask is fully causal, or we return the 2D mask which will then be used to extract the seq_lens.
We just slice it in case of sliding window.

Args:
    batch_size (`int`):
        The batch size of the input sequence.
    q_length (`int`):
        The size that the query states will have during the attention computation.
    kv_length (`int`):
        The size that the key and value states will have during the attention computation.
    q_offset (`int`, optional):
        An optional offset to indicate at which first position the query states will refer to.
    kv_offset (`int`, optional):
        An optional offset to indicate at which first position the key and values states will refer to.
    mask_function (`Callable`):
        The mask factory function describing the mask pattern.
    attention_mask (`torch.Tensor`, optional):
        The 2D attention mask corresponding to padded tokens of shape (batch_size, number_of_seen_tokens+q_length)
Nr   )r�   r9   )r¯   r‘   r~   rw   rx   rv   r}   r¸   s           r   Úflash_attention_maskrÈ   `  sJ   € ð> Ñ!à'ª¨I¨:©;¨Ñ7ˆð ×Ñ Ñ" iÓ/°N×4FÑ4F×4HÑ4HØ!ˆNàÐr7   c           
      ó†  • Ubž  [        U5      (       dŽ  UR                  S   [        -  S-   [        -  n	X–R                  S   -
  n	[        (       d1  U	S:”  a+  [        R
                  R                  R                  USSU	4S9n[        XbU5      n
[        U[        U
5      5      n[        XSU5      n[        UU SUUU[        S9nU$ )ad  
Create a 4D block mask which is a compressed representation of the full 4D block causal mask. BlockMask is essential
for performant computation of flex attention. See: https://pytorch.org/blog/flexattention/

Args:
    batch_size (`int`):
        The batch size of the input sequence.
    q_length (`int`):
        The size that the query states will have during the attention computation.
    kv_length (`int`):
        The size that the key and value states will have during the attention computation.
    q_offset (`int`, optional):
        An optional offset to indicate at which first position the query states will refer to.
    kv_offset (`int`, optional):
        An optional offset to indicate at which first position the key and values states will refer to.
    mask_function (`Callable`):
        The mask factory function describing the mask pattern.
    attention_mask (`torch.Tensor`, optional):
        The 2D attention mask corresponding to padded tokens of shape (batch_size, number_of_seen_tokens+q_length)
    device (`torch.device` or `str`, optional):
        An optional device to create the mask on.
Nr   r   )r‰   r„   )Úmask_modÚBÚHÚQ_LENÚKV_LENr-   Ú_compile)r�   r�   Úflex_default_block_sizer¶   r*   r‚   rƒ   r„   r‡   r;   rp   r|   r   )r¯   r‘   r~   rw   rx   rv   r}   r-   r¸   Úpad_lenrl   Ú
block_masks               r   Úflex_attention_maskrÓ   ‹  sÔ   € ðD Ñ!¬(°>×*BÑ*Bð #×(Ñ(¨Ñ+Ô/FÑFÈ!ÑKÔOfÑfˆØ×0Ñ0°Ñ3Ñ3ˆß2Ò2°wÀ³{Ü"ŸX™X×0Ñ0×4Ñ4°^È1ÐSTÐV]ÐR^Ð4Ð_ˆNä+¨NÀyÓQˆÜ! -Ô1FÀ|Ó1TÓUˆô 1°È)ÓT€Mô #ØØ
Ø
ØØØÜ4ñ€Jð Ðr7   c                   ó&   • \ rS rSr\\\\\\S.rSr	g)ÚAttentionMaskInterfaceiÈ  )ÚsdpaÚeagerÚflash_attention_2Úflash_attention_3Úflash_attention_4Úflex_attentionr'   N)
Ú__name__Ú
__module__Ú__qualname__Ú__firstlineno__r½   rÆ   rÈ   rÓ   Ú_global_mappingÚ__static_attributes__r'   r7   r   rÕ   rÕ   È  s   † ð ØØ1Ø1Ø1Ø-ñƒOr7   rÕ   ÚALL_MASK_ATTENTION_FUNCTIONSÚposition_idsc                 óÔ   • U SS2SS24   S-
  n[         R                  " XSS9nUS:g  R                  S5      n[        U5      (       d   USS2S4   S:H  R	                  5       (       a  gU$ )a  
Find the indices of the sequence to which each new query token in the sequence belongs when using packed
tensor format (i.e. several sequences packed in the same batch dimension).

Args:
    position_ids (`torch.Tensor`)
        A 2D tensor of shape (batch_size, query_length) indicating the positions of each token in the sequences.

Returns:
    A 2D tensor where each similar integer indicates that the tokens belong to the same sequence. For example, if we
    pack 3 sequences of 2, 3 and 1 tokens respectively along a single batch dim, this will return [[0, 0, 1, 1, 1, 2]].

    If the there is only one sequence in each batch item (and we don't compile), then we return `None` indicating
    no packed sequences. This is the same as [[0, 0, 0, 0, 0, 0]] for the example above.
Nr   r€   )ÚprependÚdimr   )r*   ÚdiffÚcumsumr   r9   )rã   Úfirst_dummy_valueÚposition_diffrq   s       r   Úfind_packed_sequence_indicesrë   Ù  sw   € ð* %¢Q¨¨¨ UÑ+¨aÑ/ÐÜ—J’J˜|ÈBÑO€MØ)¨QÑ.×6Ñ6°rÓ:Ðô Ð*×+Ñ+Ð1EÂaÈÀeÑ1LÐPQÑ1Q×0VÑ0V×0XÑ0XØàÐr7   ÚconfigÚinputs_embedsÚpast_key_valuesÚ	layer_idxÚencoder_hidden_statesc                 ó   • [        U[        R                  [        45      (       a"  [	        UR
                  5      S:X  a	  SUSSSSS4$ U R                  [        R                  ;  a  gUb8  UR                  S:X  a(  UR                  UR                  [        R                  S9nUR
                  S   nUba  UR                  U5      n[        U[        R                  5      (       a  UR                  UR                  5      OUnUR                  Xu5      u  pšO,SnUc  Ub  UR
                  S   OUn	Sn
OUR
                  S	   Sp©SnUbD  UcA  Uc>  UR
                  S   nXÄR
                  S   :w  a  UR                  US	5      n[!        U5      nS
X+XyXŠ4$ )a	  
Perform some common pre-processing of the mask arguments we get from the modeling code. Mostly determine the
key-value length and offsets, and if we should early exit or not.

Args:
    config (`PreTrainedConfig`):
        The model config.
    inputs_embeds (`torch.Tensor`):
        The input embeddings of shape (batch_size, query_length, hidden_dim). This is used only to infer the
        batch size, query length and dtype.
    attention_mask (`torch.Tensor`, optional):
        The 2D attention mask corresponding to padded tokens of shape (batch_size, number_of_seen_tokens+q_length).
        It can also be an already prepared 4D mask, in which case it is returned as-is.
    past_key_values (`Cache`, optional):
        The past key values, if we use a cache.
    position_ids (`torch.Tensor`, optional)
        A 2D tensor of shape (batch_size, query_length) indicating the positions of each token in the sequences.
    layer_idx (`int`, optional):
        If `past_key_values` is not None, this is the layer index of the cache from which to get the key-value
        length and offset. Indeed, for hybrid caches, different layers may return different lengths.
    encoder_hidden_states (`torch.Tensor`, optional):
        The input embeddings of shape (batch_size, kv_length, hidden_dim). If provided, it is used instead of
        `inputs_embeds` to infer the kv length.

Returns:
    early_exit (`bool`):
        Whether we should early exit mask creation, and return the mask as-is.
    attention_mask (`torch.Tensor` or `BlockMask` or `None`):
        The attention mask to either return immediately, or to use in downstream mask creation.
    packed_sequence_mask (`torch.Tensor`, optional):
        In case we detected packed sequence format, this is a tensor where each similar integer indicates that
        the tokens belong to the same sequence.
    q_length (`int`):
        The size that the query states will have during the attention computation.
    kv_length (`int`):
        The size that the key and value states will have during the attention computation.
    q_offset (`int`, optional):
        An optional offset to indicate at which first position the query states will refer to.
    kv_offset (`int`):
        An offset to indicate at which first position the key and values states will refer to.
é   TN)TNNNNNNé   r¿   r   r   r€   F)Ú
isinstancer*   ÚTensorr   Úlenr�   Ú_attn_implementationrâ   rà   Úndimr,   r-   r+   Úget_query_offsetÚget_mask_sizesrµ   rë   )rì   rí   r}   rî   rã   rï   rð   r‘   rw   r~   rx   rq   r¯   s                r   Ú_preprocess_mask_argumentsrû   ù  sš  € ôf �.¤5§<¡<´Ð";×<Ñ<ÄÀ^×EYÑEYÓAZÐ^_ÓA_Ø�^ T¨4°°t¸TÐAÐAð ×"Ñ"Ô*F×*VÑ*VÓVØ7ð Ñ! n×&9Ñ&9¸QÓ&>Ø'×*Ñ*°-×2FÑ2FÌeÏjÉjÐ*ÐYˆà×"Ñ" 1Ñ%€HàÑ"Ø"×3Ñ3°IÓ>ˆô 9CÀ8ÌUÏ\É\×8ZÑ8Z�8—;‘;˜}×3Ñ3Ô4Ð`hˆØ.×=Ñ=¸hÓRÑˆ	�9ð ˆàÑ!à:OÑ:[Ð-×3Ñ3°AÒ6ÐaiˆIØ‰Ið $2×#7Ñ#7¸Ñ#;¸Q�yð  ÐØÑ NÑ$:¸Ñ?VØ"×(Ñ(¨Ñ+ˆ
à×+Ñ+¨AÑ.Ó.Ø'×.Ñ.¨z¸2Ó>ˆLÜ;¸LÓIÐà�.¸ÈXÐ`Ð`r7   Úor_mask_functionÚand_mask_functionc
                 ó  • [        U SS5      (       d  [        U UUUUUU	S9$ Uc?  [        US5      (       a,  SUR                  ;   a  UR                  R	                  S5      nOSn[        XX#XH5      u  p¢p¼pÞnU
(       a  U$ UR                  S   UR                  UR                  nnn[        n[        U R                     nSnU	=(       a    [        USS5      =(       a    US:H  (       + n	Ub&  [        (       d  [        S	5      e[        UU5      nSn	SnUb&  [        (       d  [        S	5      e[        UU5      nSn	SnUb  [        U[!        U5      5      nSn	Ub#  [#        XrXß5      n[        U[%        U5      5      nSn	U" UUUUUUUU	UU UUS
9nU$ )aD
  
Create a standard causal mask based on the attention implementation used (stored in the config). If `past_key_values`
has a hybrid cache structure, this function will return the mask corresponding to one of the "full_attention" layers (to align
to what is needed in the `modeling_xxx.py` files).

Args:
    config (`PreTrainedConfig`):
        The model config.
    inputs_embeds (`torch.Tensor`):
        The input embeddings of shape (batch_size, query_length, hidden_dim). This is used only to infer the
        batch size, query length and dtype.
    attention_mask (`torch.Tensor`, optional):
        The 2D attention mask corresponding to padded tokens of shape (batch_size, number_of_seen_tokens+q_length).
        It can also be an already prepared 4D mask, in which case it is returned as-is.
    past_key_values (`Cache`, optional):
        The past key values, if we use a cache.
    position_ids (`torch.Tensor`, optional)
        A 2D tensor of shape (batch_size, query_length) indicating the positions of each token in the sequences.
    or_mask_function (`Callable`, optional):
        An optional mask function to combine with the causal mask function (by doing the union of both). This is
        useful to easily overlay another mask on top of the causal one, for example for image tokens handling.
    and_mask_function (`Callable`, optional):
        An optional mask function to combine with the causal mask function (by doing the intersection of both). This is
        useful to easily overlay another mask on top of the causal one, for example for image tokens handling.
    block_sequence_ids (`torch.Tensor`, *optional*):
        A tensor of same shape as input IDs indicating to which block or group each token belongs to. Tokens from
        the same block will keep a bidirectional mask within the block, attending causally to the past. Index `-1`
        can be used for blocks that have to keep complete causality within itself.
    layer_idx (`int`, *optional*):
        The cache layer to size the mask against. By default, the first "full_attention" layer is used, which is
        correct whenever all layers of a given mask type have seen the same tokens. Pass it explicitly for caches
        where layers of the same type hold different lengths (e.g. per-depth MTP streams).
    allow_is_causal_skip (`bool`, optional):
        Whether to allow returning `None` (and relying on `sdpa`'s `is_causal` argument) when the mask would be a
        plain causal mask. Set to `False` to always materialize the mask, e.g. when it is later concatenated with
        another mask. Defaults to `True`.
Ú	is_causalT©rî   rü   rý   r²   Ú
is_slidingFr   Úis_compileabler   úLUsing `or_mask_function` or `and_mask_function` arguments require torch>=2.6)r¯   r‘   r~   rw   rx   rv   r}   r±   r(   rì   r³   r-   )ÚgetattrÚcreate_bidirectional_maskÚhasattrr  Úindexrû   r�   r(   r-   rF   râ   r÷   r¶   r·   rC   r;   ru   r‹   r_   )rì   rí   r}   rî   rã   rü   rý   rY   rï   r±   Ú
early_exitrq   r‘   r~   rw   rx   r¯   r(   r-   Úmask_factory_functionÚmask_interfacer³   Úcausal_masks                          r   Úcreate_causal_maskr  a  s÷  € ôf �6˜;¨×-Ñ-Ü(ØØØØ+Ø-Ø/Ø(<ñ
ð 	
ð ÑÜ�? L×1Ñ1°e¸×?YÑ?YÓ6YØ'×2Ñ2×8Ñ8¸Ó?‰IàˆIô 	# 6¸.Ð[gÓsñ _€JÐ 4À	ÐU^ö ØÐà -× 3Ñ 3°AÑ 6¸×8KÑ8KÈ]×MaÑMa�v�€JÜ0ÐÜ1°&×2MÑ2MÑN€Nð
 €Hð 0÷ Ü�Ð!1°5Ó9×K¸hÈ!¹mô5Ðð Ñ#ß2Ò2ÜÐkÓlÐlÜ (Ð)>Ð@PÓ QÐØ$ÐØˆØÑ$ß2Ò2ÜÐkÓlÐlÜ )Ð*?ÐARÓ SÐØ$ÐØˆð Ñ'Ü )Ð*?ÔA^Ð_sÓAtÓ uÐØ$ÐØÑ%Ü9Ð:LÐ^gÓsÐÜ (Ð)>Ô@QÐRdÓ@eÓ fÐØ$Ðñ !ØØØØØØ+Ø%Ø1ØØØØñ€Kð Ðr7   c                 ó  • [        US5      (       a,  SUR                  ;   a  UR                  R                  S5      n	OSn	[        XX$SX“5      u  p¢p¼pÞnU
(       a  U$ Ub  UOUnUR                  S   UR
                  nnUR                  n[        n[        U R                     nSnUb&  [        (       d  [        S5      e[        UU5      nSnSnUb&  [        (       d  [        S5      e[        UU5      nSnSnU" UUUUUUUSUUU UUS9nU$ )a  
Create a standard bidirectional mask based on the attention implementation used (stored in the config).

Args:
    config (`PreTrainedConfig`):
        The model config.
    inputs_embeds (`torch.Tensor`):
        The input embeddings of shape (batch_size, query_length, hidden_dim). This is only used to infer metadata
        such as the batch size, query length, dtype, and device.
    attention_mask (`torch.Tensor`, optional):
        The 2D attention mask corresponding to padded tokens of shape (batch_size, kv_length).
        It can also be an already prepared 4D mask of shape (batch_size, 1, query_length, kv_length),
        in which case it is returned as-is.
    encoder_hidden_states (`torch.Tensor`, optional):
        The input embeddings of shape (batch_size, kv_length, hidden_dim). If provided, it is used instead of
        `inputs_embeds` to infer the batch size, kv length and dtype.
    past_key_values (`Cache`, optional):
        The past key values, if we use a cache.
    or_mask_function (`Callable`, optional):
        An optional mask function to combine with the base mask function (by doing the union of both). This is
        useful to easily overlay another mask on top, for example for image tokens handling.
    and_mask_function (`Callable`, optional):
        An optional mask function to combine with the base mask function (by doing the intersection of both). This is
        useful to easily overlay another mask on top, for example for image tokens handling.
    allow_is_bidirectional_skip (`bool`, optional):
        Whether to allow returning `None` (no bias) when the mask is plain bidirectional with no padding. Set to
        `False` to always materialize the mask, e.g. when it is later concatenated with another mask. Defaults to
        `True`.
r  Fr   Nr  T)r¯   r‘   r~   rw   rx   rv   r}   r±   r²   r(   rì   r³   r-   )r  r  r  rû   r�   r(   r-   rH   râ   r÷   r¶   r·   rC   r;   )rì   rí   r}   rð   rî   rü   rý   r²   r¸   rï   r  rÄ   r‘   r~   rw   rx   Úembedsr¯   r(   r-   r	  r
  r³   s                          r   r  r  æ  sS  € ôR ˆ ×-Ñ-°%¸?×;UÑ;UÓ2UØ#×.Ñ.×4Ñ4°UÓ;‰	àˆ	ô OiØ˜~ÀÀióOÑK€J ¨YÀ)ö ØÐà&;Ñ&GÑ"È]€FØŸ™ Q™¨¯©�€Jð ×!Ñ!€FÜ7ÐÜ1°&×2MÑ2MÑN€Nð
 €Hð
 Ñ#ß2Ò2ÜÐkÓlÐlÜ (Ð)>Ð@PÓ QÐØ&+Ð#ØˆØÑ$ß2Ò2ÜÐkÓlÐlÜ )Ð*?ÐARÓ SÐØ&+Ð#Øˆñ $ØØØØØØ+Ø%à"Ø$?ØØØØñ€Nð  Ðr7   c
                 ó\  • [        U SS5      (       d  [        U UUUUUU	S9$ Uc?  [        US5      (       a,  SUR                  ;   a  UR                  R	                  S5      nOSn[        XX#XH5      u  p¢p¼pÞnU
(       a  U$ [        U SS5      nUc  [        S5      eUR                  S   UR                  UR                  nnn[        U5      n[        U R                     nS	nU	=(       a    [        US
S	5      =(       a    US:H  (       + n	Ub&  [        (       d  [        S5      e[        UU5      nS	n	SnUb&  [        (       d  [        S5      e[        UU5      nS	n	SnUb  [        U[!        U5      5      nS	n	Ub#  [#        XrXß5      n[        U[%        U5      5      nS	n	U" UUUUUUUU	UUU UUS9nU$ )a°
  
Create a sliding window causal mask based on the attention implementation used (stored in the config). This type
of attention pattern was mostly democratized by Mistral. If `past_key_values` has a hybrid cache structure, this
function will return the mask corresponding to one of the "sliding_attention" layers (to align to what is needed in the
`modeling_xxx.py` files).

Args:
    config (`PreTrainedConfig`):
        The model config.
    inputs_embeds (`torch.Tensor`):
        The input embeddings of shape (batch_size, query_length, hidden_dim). This is used only to infer the
        batch size, query length and dtype.
    attention_mask (`torch.Tensor`, optional):
        The 2D attention mask corresponding to padded tokens of shape (batch_size, number_of_seen_tokens+q_length).
        It can also be an already prepared 4D mask, in which case it is returned as-is.
    past_key_values (`Cache`, optional):
        The past key values, if we use a cache.
    position_ids (`torch.Tensor`, optional)
        A 2D tensor of shape (batch_size, query_length) indicating the positions of each token in the sequences.
    or_mask_function (`Callable`, optional):
        An optional mask function to combine with the sliding causal mask function (by doing the union of both). This is
        useful to easily overlay another mask on top of the sliding causal one, for example for image tokens handling.
    and_mask_function (`Callable`, optional):
        An optional mask function to combine with the sliding causal mask function (by doing the intersection of both). This is
        useful to easily overlay another mask on top of the sliding causal one, for example for image tokens handling.
    block_sequence_ids (`torch.Tensor`, *optional*):
        A tensor of same shape as input IDs indicating to which block or group each token belongs to. Tokens from
        the same block will keep a bidirectional mask within the block, attending causally to the past. Index `-1`
        can be used for blocks that have to keep complete causality within itself.
    layer_idx (`int`, *optional*):
        The cache layer to size the mask against. By default, the first "full_attention" layer is used, which is
        correct whenever all layers of a given mask type have seen the same tokens. Pass it explicitly for caches
        where layers of the same type hold different lengths (e.g. per-depth MTP streams).
    allow_is_causal_skip (`bool`, optional):
        Whether to allow returning `None` (and relying on `sdpa`'s `is_causal` argument) when the mask would be a
        plain causal mask. Set to `False` to always materialize the mask, e.g. when it is later concatenated with
        another mask. Defaults to `True`.
rÿ   Tr   Nr  r   rI   úJCould not find a `sliding_window` argument in the config, or it is not setFr  r   r  ©r¯   r‘   r~   rw   rx   rv   r}   r±   r°   r(   rì   r³   r-   )r  Ú(create_bidirectional_sliding_window_maskr  r  r  rû   r·   r�   r(   r-   rb   râ   r÷   r¶   rC   r;   ru   r‹   r_   )rì   rí   r}   rî   rã   rü   rý   rY   rï   r±   r  rq   r‘   r~   rw   rx   rI   r¯   r(   r-   r	  r
  r³   r  s                           r   Ú!create_sliding_window_causal_maskr  M  s   € ôh �6˜;¨×-Ñ-Ü7ØØØØ+Ø-Ø/Ø(<ñ
ð 	
ð ÑÜ�? L×1Ñ1°d¸o×>XÑ>XÓ6XØ'×2Ñ2×8Ñ8¸Ó>‰IàˆIô 	# 6¸.Ð[gÓsñ _€JÐ 4À	ÐU^ö ØÐä˜VÐ%5°tÓ<€NØÑÜÐeÓfÐfà -× 3Ñ 3°AÑ 6¸×8KÑ8KÈ]×MaÑMa�v�€JÜ?ÀÓOÐÜ1°&×2MÑ2MÑN€Nð
 €Hð 0÷ Ü�Ð!1°5Ó9×K¸hÈ!¹mô5Ðð Ñ#ß2Ò2ÜÐkÓlÐlÜ (Ð)>Ð@PÓ QÐØ$ÐØˆØÑ$ß2Ò2ÜÐkÓlÐlÜ )Ð*?ÐARÓ SÐØ$ÐØˆð Ñ'Ü )Ð*?ÔA^Ð_sÓAtÓ uÐØ$ÐØÑ%Ü9Ð:LÐ^gÓsÐÜ (Ð)>Ô@QÐRdÓ@eÓ fÐØ$Ðñ !ØØØØØØ+Ø%Ø1Ø!ØØØØñ€Kð Ðr7   c                 óX  • [        US5      (       a,  SUR                  ;   a  UR                  R                  S5      n	OSn	[        XX$SX“5      u  p¢p¼pÞnU
(       a  U$ [	        U SS5      nUc  [        S5      eUb  UOUnUR                  S   UR                  nnUR                  n[        U5      n[        U R                     nSnUb&  [        (       d  [        S5      e[        UU5      nSnSnUb&  [        (       d  [        S5      e[        UU5      nSnSnU" UUUUUUUSUUUU UUS	9nU$ )
a  
Create a standard bidirectional sliding window mask based on the attention implementation used (stored in the config).

Args:
    config (`PreTrainedConfig`):
        The model config.
    inputs_embeds (`torch.Tensor`):
        The input embeddings of shape (batch_size, query_length, hidden_dim). This is only used to infer metadata
        such as the batch size, query length, dtype, and device.
    attention_mask (`torch.Tensor`, optional):
        The 2D attention mask corresponding to padded tokens of shape (batch_size, kv_length).
        It can also be an already prepared 4D mask of shape (batch_size, 1, query_length, kv_length),
        in which case it is returned as-is.
    encoder_hidden_states (`torch.Tensor`, optional):
        The input embeddings of shape (batch_size, kv_length, hidden_dim). If provided, it is used instead of
        `inputs_embeds` to infer the batch size, kv length and dtype.
    past_key_values (`Cache`, optional):
        The past key values, if we use a cache.
    or_mask_function (`Callable`, optional):
        An optional mask function to combine with the base mask function (by doing the union of both). This is
        useful to easily overlay another mask on top, for example for image tokens handling.
    and_mask_function (`Callable`, optional):
        An optional mask function to combine with the base mask function (by doing the intersection of both). This is
        useful to easily overlay another mask on top, for example for image tokens handling.
    allow_is_bidirectional_skip (`bool`, optional):
        Whether to allow returning `None` (no bias) when the mask is plain bidirectional with no padding. Set to
        `False` to always materialize the mask, e.g. when it is later concatenated with another mask. Defaults to
        `True`.
r  Tr   NrI   r  Fr  )r¯   r‘   r~   rw   rx   rv   r}   r±   r²   r°   r(   rì   r³   r-   )r  r  r  rû   r  r·   r�   r(   r-   ri   râ   r÷   r¶   rC   r;   )rì   rí   r}   rð   rî   rü   rý   r²   r¸   rï   r  rÄ   r‘   r~   rw   rx   rI   r  r¯   r(   r-   r	  r
  r³   s                           r   r  r  ×  sv  € ôR ˆ ×-Ñ-°$¸/×:TÑ:TÓ2TØ#×.Ñ.×4Ñ4°TÓ:‰	àˆ	ô OiØ˜~ÀÀióOÑK€J ¨YÀ)ö ØÐä˜VÐ%5°tÓ<€NØÑÜÐeÓfÐfà&;Ñ&GÑ"È]€FØŸ™ Q™¨¯©�€Jð ×!Ñ!€FÜFÀ~ÓVÐÜ1°&×2MÑ2MÑN€Nà€HàÑ#ß2Ò2ÜÐkÓlÐlÜ (Ð)>Ð@PÓ QÐØ&+Ð#ØˆØÑ$ß2Ò2ÜÐkÓlÐlÜ )Ð*?ÐARÓ SÐØ&+Ð#Øˆá#ØØØØØØ+Ø%Ø"Ø$?Ø!ØØØØñ€Nð  Ðr7   c	                 ó¸  • Uc?  [        US5      (       a,  SUR                  ;   a  UR                  R                  S5      nOSn[        XX#XG5      u  p’p«pÍnU	(       a  U$ [	        U SS5      nUc  [        S5      e[        U 5      (       a  XÎ-   U:”  a  [        S5      eUR                  S   UR                  UR                  nnnUb4  UR                  SS	9[        R                  " U5      :H  R                  SS	9nO[        R                  " UU[        S
9n[!        UU5      n["        U R$                     nSnU=(       a    [	        USS5      =(       a    US:H  (       + nUb&  [&        (       d  [        S5      e[)        UU5      nSnSnUb&  [&        (       d  [        S5      e[+        UU5      nSnSnU
b  [+        U[-        U
5      5      nSnU" UUUUUUUUUUU UUS9nU$ )aE	  
Create a chunked attention causal mask based on the attention implementation used (stored in the config). This type
of attention pattern was mostly democratized by Llama4. If `past_key_values` has a hybrid cache structure, this
function will return the mask corresponding to one of the "chunked_attention" layers (to align to what is needed in the
`modeling_xxx.py` files).

Args:
    config (`PreTrainedConfig`):
        The model config.
    inputs_embeds (`torch.Tensor`):
        The input embeddings of shape (batch_size, query_length, hidden_dim). This is used only to infer the
        batch size, query length and dtype.
    attention_mask (`torch.Tensor`, optional):
        The 2D attention mask corresponding to padded tokens of shape (batch_size, number_of_seen_tokens+q_length).
        It can also be an already prepared 4D mask, in which case it is returned as-is.
    past_key_values (`Cache`, optional):
        The past key values, if we use a cache.
    position_ids (`torch.Tensor`, optional)
        A 2D tensor of shape (batch_size, query_length) indicating the positions of each token in the sequences.
    or_mask_function (`Callable`, optional):
        An optional mask function to combine with the chunked causal mask function (by doing the union of both). This is
        useful to easily overlay another mask on top of the chunked causal one, for example for image tokens handling.
    and_mask_function (`Callable`, optional):
        An optional mask function to combine with the chunked causal mask function (by doing the intersection of both). This is
        useful to easily overlay another mask on top of the chunked causal one, for example for image tokens handling.
    layer_idx (`int`, *optional*):
        The cache layer to size the mask against. By default, the first "full_attention" layer is used, which is
        correct whenever all layers of a given mask type have seen the same tokens. Pass it explicitly for caches
        where layers of the same type hold different lengths (e.g. per-depth MTP streams).
    allow_is_causal_skip (`bool`, optional):
        Whether to allow returning `None` (and relying on `sdpa`'s `is_causal` argument) when the mask would be a
        plain causal mask. Set to `False` to always materialize the mask, e.g. when it is later concatenated with
        another mask. Defaults to `True`.
Nr  Tr   Úattention_chunk_sizezQCould not find an `attention_chunk_size` argument in the config, or it is not setzÝFlash attention cannot handle chunked attention, and the key-value length is larger than the chunk size so the chunked pattern cannot be respected. You should use another `attn_implementation` when instantiating the modelr€   )ræ   r¿   Fr  r   r  r  )r  r  r  rû   r  r·   r   r�   r(   r-   rè   r*   Ú
zeros_likerŽ   ÚzerosrP   rk   râ   r÷   r¶   rC   r;   ru   )rì   rí   r}   rî   rã   rü   rý   rï   r±   r  rq   r‘   r~   rw   rx   rS   r¯   r(   r-   Úleft_padding_tokensr	  r
  r³   r  s                           r   Úcreate_chunked_causal_maskr  ;  s;  € ðZ Ñä�? L×1Ñ1°d¸o×>XÑ>XÓ6XØ'×2Ñ2×8Ñ8¸Ó>‰IàˆIô 	# 6¸.Ð[gÓsñ _€JÐ 4À	ÐU^ö ØÐä˜Ð!7¸Ó>€JØÑÜÐlÓmÐmô $ F×+Ñ+°	Ñ0EÈ
Ó0RÜð}ó
ð 	
ð
 !.× 3Ñ 3°AÑ 6¸×8KÑ8KÈ]×MaÑMa�v�€Jð Ñ!à-×4Ñ4¸Ð4Ð<Ä×@PÒ@PÐQ_Ó@`Ñ`×eÑeÐjlÐeÐmÑä#Ÿkšk¨*¸VÌ3ÑOÐÜ8¸ÐEXÓYÐÜ1°&×2MÑ2MÑN€Nð
 €Hð 0÷ Ü�Ð!1°5Ó9×K¸hÈ!¹mô5Ðð Ñ#ß2Ò2ÜÐkÓlÐlÜ (Ð)>Ð@PÓ QÐØ$ÐØˆØÑ$ß2Ò2ÜÐkÓlÐlÜ )Ð*?ÐARÓ SÐØ$ÐØˆð Ñ'Ü )Ð*?ÔA^Ð_sÓAtÓ uÐØ$Ðñ !ØØØØØØ+Ø%Ø1ØØØØØñ€Kð Ðr7   c                 óþ   • Ub  UR                   S:w  a  gUR                  S   S:X  a  g[        U5      (       d  [        R                  " US:H  5      (       a  gUSS2UR                  S   * S24   R                  5       $ )uá  Return the 2D padding mask for mamba / linear-attention layers, sized to the local sequence.

Returns ``None`` (so the consumer skips masking entirely) when any of:
- the input mask is missing or is already a custom 4D attention mask (no 2D padding signal);
- the current forward is a single-token decode step (a generated token is never padding; this
  also keeps the growing 2D mask out of the compiled decode graph);
- the mask is all-ones (un-padded batch â€” the masking multiply would be a no-op), skipped
  only outside trace/compile so the graph specialisation stays stable.

Otherwise we trim the mask to the trailing ``inputs_embeds.shape[1]`` positions so it aligns
with the current forward's local sequence and the consumer can multiply directly without
further slicing. Note that this includes multi-token forwards continuing from a cache (chunked
prefill, cache continuation): padding inside the new segment must still be zeroed out, otherwise
it leaks into the recurrent state.
Nró   r   )rø   r�   r   r*   r9   Ú
contiguous)rì   rí   r}   rî   r¸   s        r   Úcreate_recurrent_attention_maskr  ½  s{   € ð, Ñ ×!4Ñ!4¸Ó!9Øà×Ñ˜1Ñ Ó"ØÜ�n×%Ñ%¬%¯)ª)°NÀaÑ4G×*HÑ*HØàš!˜m×1Ñ1°!Ñ4Ð4Ñ6Ð6Ñ7×BÑBÓDÐDr7   )r±   )Úfull_attentionÚlinear_attention)Úsliding_attentionr  )r  r   Úchunked_attentionÚcompressed_sparse_attentionÚheavily_compressed_attentionÚminimax_m3_sparseÚdeepseek_sparse_attentionÚqwen_sparse_attentionr  ÚconvÚhybridÚhybrid_slidingc           	      óô  • U R                  5       n	U	UUUUUUUS.n
[        U	S5      (       a�  [        U	R                  5      n[	        S U 5       5      (       a  U$ 0 nU HX  n[
        U   n[        U[        5      (       a-  UR                  5        H  u  nnXü;  d  M  U" S0 U
D6XÏ'   M     MN  U" S0 U
D6XÍ'   MZ     U$ [        U	SS5      b  [        S0 U
D6$ [        U	SS5      b  [        S0 U
D6$ [        S0 U
D6$ )aR  
This function mimics how we create the masks in the `modeling_xxx.py` files, and is used in places like `generate`
in order to easily create the masks in advance, when we compile the forwards with Static caches.

Args:
    config (`PreTrainedConfig`):
        The model config.
    inputs_embeds (`torch.Tensor`):
        The input embeddings of shape (batch_size, query_length, hidden_dim). This is used only to infer the
        batch size, query length and dtype.
    attention_mask (`torch.Tensor`, optional):
        The 2D attention mask corresponding to padded tokens of shape (batch_size, number_of_seen_tokens+q_length).
        It can also be an already prepared 4D mask, in which case it is returned as-is.
    past_key_values (`Cache`, optional):
        The past key values, if we use a cache.
    position_ids (`torch.Tensor`, optional)
        A 2D tensor of shape (batch_size, query_length) indicating the positions of each token in the sequences.
    or_mask_function (`Callable`, optional):
        An optional mask function to combine with the other mask function (by doing the union of both). This is
        useful to easily overlay another mask on top of the causal one, for example for image tokens handling.
    and_mask_function (`Callable`, optional):
        An optional mask function to combine with the other mask function (by doing the intersection of both). This is
        useful to easily overlay another mask on top of the causal one, for example for image tokens handling.
    block_sequence_ids (`torch.Tensor`, *optional*):
        A tensor of same shape as input IDs indicating to which block or group each token belongs to. Tokens from
        the same block will keep a bidirectional mask within the block, attending causally to the past. Index `-1`
        can be used for blocks that have to keep complete causality within itself.
)rì   rí   r}   rî   rã   rü   rý   rY   Úlayer_typesc              3   ó2   #   • U  H  o[         ;  v •  M     g 7fr   )Ú&LAYER_PATTERN_TO_MASK_FUNCTION_MAPPING)r   Ú
layer_types     r   r    Ú,create_masks_for_generate.<locals>.<genexpr>)  s   é € ÐiÒZhÈJÔ!GÖGÒZhùs   ‚rI   Nr  r'   )Úget_text_configr  Úsetr+  Úanyr-  rô   ÚdictÚitemsr  r  r  r  )rì   rí   r}   rî   rã   rü   rý   rY   r¸   Úeffective_configÚmask_kwargsÚlayer_patternsÚcausal_masksÚlayer_patternrv   Úactual_patternÚactual_functions                    r   Úcreate_masks_for_generater<  ð  s)  € ðP ×-Ñ-Ó/Ðð #Ø&Ø(Ø*Ø$Ø,Ø.Ø0ñ	€Kô Ð ×/Ñ/ÜÐ-×9Ñ9Ó:ˆäÑiÑZhÓi×iÑiØ!Ð!ØˆÛ+ˆMÜBÀ=ÑQˆMä˜-¬×.Ñ.Ø7D×7JÑ7JÖ7LÑ3�N Oà%Õ9Ù7FÑ7UÈÑ7U˜Ó4ó 8Mñ
 /<Ñ.J¸kÑ.J�Ó+ñ ,ð Ðä	Ð!Ð#3°TÓ	:Ñ	FÜ0Ñ?°;Ñ?Ð?ä	Ð!Ð#9¸4Ó	@Ñ	LÜ)Ñ8¨KÑ8Ð8äÑ, Ñ,Ð,r7   r   )NNNNNT)NNNNT)NNNN)UÚcollections.abcr   Ú	functoolsr   r*   Útorch.nn.functionalr‚   rƒ   rŠ   Úcache_utilsr   Úconfiguration_utilsr   Úutilsr   r	   Úutils.deprecationr
   Úutils.genericr   r   Úutils.import_utilsr   r   r   Ú!torch.nn.attention.flex_attentionr   rÐ   r   r   rõ   r¶   rœ   Ú,torch._dynamo._trace_wrapped_higher_order_opr   Ú
get_loggerrÜ   Úloggerr;   rC   rP   r+   rF   rH   rR   rX   r_   rb   rg   ri   rk   rp   ru   r|   r‡   r‹   Ú
BoolTensorr�   r—   rš   r�   r¤   rª   r-   Ústrr½   Úfloat32r(   rÆ   rÈ   rÓ   rÕ   râ   Ú__annotations__rë   Útuplerû   r  r  r  r  r  r  r-  r<  r'   r7   r   Ú<module>rO     sö  ðö %Ý ã ß Ð å Ý 1ß 2Ý .ß I÷ñ ñ  ×!Ñ!ÝgßNÐNð —‘€Iá&?ÀÐRVÑ&WÐ #Ù0Ó2Ð æ&ÝTð 
×	Ò	˜HÓ	%€ð˜xð ¨Hô ð˜hð ¨8ô ð Cð °3ð ¸sð ÈCð ÐTXô ð¨3ð ¸#ð Àcð ÐSVð Ð[_ô ð	¨3ð 	°8ô 	ð	 ð 	°5·<±<ð 	ÀHô 	ð¨%¯,©,ð ¸8ô ð$S¸ð SÀô Sð
¸ð 
Àô 
ðh¸sð hÀxô hðV¨Sð VÀÇÁð VÐQYô Vð¨¯©ð ¸ô ð¸¿¹ð Èô ð	°ð 	ÀCð 	ÐTWð 	Ð\dô 	ð	¨¯©¸Ñ)<ð 	Èð 	ÐY\ð 	Ðaf×amÑamÐptÑatô 	ð
ØŸ™ð
Ø6;·l±lÀTÑ6Ið
ØVYð
Øfið
à
‡\�\ô
ð*�U×%Ñ%ð *¨%×*:Ñ*:ô *ð (,ñ+Ø—,‘, Ñ%ð+àð+ð ð+ð ð	+ð
 ð+ð  ™*ð+ð 
õ+ð\Ø—,‘, Ñ%ðàðð  ™*ðð 
ô	ð< (,ñØ—,‘, Ñ%ðàðð  ™*ðð 
õ	ð>
¨ð 
°Xô 
ð>Ø—<‘<ð>Ø/4¯|©|ð>ØHMÏÉð>Øbg×bnÑbnô>ñ& Ð"¨HÐIdÑeð
 ØØ2Ø*.Ø!Ø!%Ø(-Ø ØØ!&ñcØðcàðcð ðcð ð	cð
 ðcð ðcð —L‘L 4Ñ'ðcð �d‘
ðcð ðcð "&ðcð ðcð ðcð �L‰L˜3Ñðcð ‡\�\�DÑôcó fðcðT ØØ2Ø*.ØŸ™Ø(-ØØ!&ñBØðBàðBð ðBð ð	Bð
 ðBð ðBð —L‘L 4Ñ'ðBð �;‰;ðBð "&ðBð ðBð �L‰L˜3ÑðBð ‡\�\õBðR ØØ2Ø*.ñ(Øð(àð(ð ð(ð ð	(ð
 ð(ð ð(ð —L‘L 4Ñ'õ(ð^ ØØ2Ø*.Ø!&ñ:Øð:àð:ð ð:ð ð	:ð
 ð:ð ð:ð —L‘L 4Ñ'ð:ð �L‰L˜3Ñð:ð õ:ôz
Ð-ô 
ñ 8NÓ7OÐ Ð4Ó Oð ¨u¯|©|ð  ÀÇÁÈtÑ@Sô  ðN 26ñeaØðeaà—<‘<ðeað —L‘L 9Ñ,¨tÑ3ðeað ˜T‘\ð	eað
 —,‘, Ñ%ðeað �T‰zðeað !Ÿ<™<¨$Ñ.ðeað ˆ4�—‘ 	Ñ)¨DÑ0°#°sÐ:Ñ;õeaðZ )-Ø(,Ø)-Ø.2Ø Ø!%ñBØðBà—<‘<ðBð —L‘L 4Ñ'ðBð ˜T‘\ð	Bð
 —,‘, Ñ%ðBð  ‘oðBð   $‘ðBð Ÿ™ tÑ+ðBð �T‰zðBð ðBð ‡\�\�IÑ Ñ$õBðR 26Ø$(Ø(,Ø)-Ø(,ñdØðdà—<‘<ðdð —L‘L 4Ñ'ðdð !Ÿ<™<¨$Ñ.ð	dð
 ˜T‘\ðdð  ‘oðdð   $‘ðdð "&ðdð ‡\�\�IÑ Ñ$õdðX )-Ø(,Ø)-Ø.2Ø Ø!%ñGØðGà—<‘<ðGð —L‘L 4Ñ'ðGð ˜T‘\ð	Gð
 —,‘, Ñ%ðGð  ‘oðGð   $‘ðGð Ÿ™ tÑ+ðGð �T‰zðGð ðGð ‡\�\�IÑ Ñ$õGð\ 26Ø$(Ø(,Ø)-Ø(,ñaØðaà—<‘<ðað —L‘L 4Ñ'ðað !Ÿ<™<¨$Ñ.ð	að
 ˜T‘\ðað  ‘oðað   $‘ðað "&ðað ‡\�\�IÑ Ñ$õaðR )-Ø(,Ø)-Ø Ø!%ñØðà—<‘<ðð —L‘L 4Ñ'ðð ˜T‘\ð	ð
 —,‘, Ñ%ðð  ‘oðð   $‘ðð �T‰zðð ðð ‡\�\�IÑ Ñ$õðL %)ñ	EØðEà—<‘<ðEð —L‘L 4Ñ'ðEð ˜T‘\ð	Eð ‡\�\�DÑõEðD )Ø:Ø3Ø#DØ$EØ+á!(Ð);ÐRWÑ!Xá$Ð%7ÈeÑTØ7Ø+Ø!3ÐIhÑiØ,>ÐTsÑtñ*Ð &ð. )-Ø(,Ø)-Ø.2ñN-ØðN-à—<‘<ðN-ð —L‘L 4Ñ'ðN-ð ˜T‘\ð	N-ð
 —,‘, Ñ%ðN-ð  ‘oðN-ð   $‘ðN-ð Ÿ™ tÑ+öN-r7   