o
    ZhR                     @   s<  d dl mZ d dlmZmZ d dlZddlmZ eG dd dZ	ddeej	 d	eej
eef d
ej	dedee f
ddZ	ddeej	 d	eej
eef d
ej	dedee f
ddZddej	dejdee fddZddej	dejdee fddZ	 	dd	eej
eef dejdejdedee deej	 fddZdS )    )	dataclass)OptionalUnionN   )is_torchdynamo_compilingc                   @   sD  e Zd ZU dZeed< eed< d'dedee fddZ	d(ded	ed
ede	j
dee	jdf dee	j fddZ	d'de	jd	ede	j
d
ee de	jf
ddZe		d)de	jde	j
de	jdedee f
ddZed'de	jde	j
dee fddZede	jdefdd Ze		!d*d"ee	j d#e	jdedee d$edefd%d&ZdS )+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                 C   s:   || _ || _| jd ur| jdkrtd| j dd S d S )Nr   zaMake sure that when passing `sliding_window` that its value is a strictly positive integer, not ``)r   r	   
ValueError)selfr   r	    r   T/var/www/auris/lib/python3.10/site-packages/transformers/modeling_attn_mask_utils.py__init__9   s   zAttentionMaskConverter.__init__cpu
batch_sizequery_lengthkey_value_lengthdtypedevicestrreturnc           	      C   s\   | j std| j d||f}|| }d}|d dks!| jdur,| j||||| jd}|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.Nr   r   past_key_values_lengthr	   )r   r   	__class__r	   _make_causal_mask)	r   r   r   r   r   r   input_shaper   causal_4d_maskr   r   r   to_causal_4dB   s   z#AttentionMaskConverter.to_causal_4dattention_mask_2dc           
      C   s   |j d |f}d}|d dks| jdur0| jr0|du rtd|| }| j|||j|| jd}n	| jdur9td| j|||d d|j}|durW|	|
 t|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   Zexpanded_attn_maskexpanded_4d_maskr   r   r   to_4dc   s0   
zAttentionMaskConverter.to_4dr   input_ids_shaper   c                 C   s  | \}}t j||ft |j|d}t j|d|d}|||d |ddk d ||}|dkrFt j	t j
||||d|gdd}|durn|| d }	t jt j|t jd|	d	}
t rd| }||
t |j |ddddddf |d||| S )
zJ
        Make causal mask used for bi-directional self-attention.
        )r   r   r   r   r   r   )dimN)r   )diagonal)r(   fullr)   r*   ZarangesizeZmasked_fill_viewr%   catZzerosZtrilZ	ones_liker'   r   cloneexpand)r-   r   r   r   r	   bszr!   maskZ	mask_condr0   Zcontext_maskr   r   r   r      s   "
 (z(AttentionMaskConverter._make_causal_maskr8   r!   c                 C   sj   |   \}}|dur|n|}| ddddddf |d|||}d| }||tjt|jS )zg
        Expands attention_mask from `[bsz, seq_len]` to `[bsz, 1, tgt_seq_len, src_seq_len]`.
        Nr         ?)r2   r6   r%   r&   r(   r'   r)   r*   )r8   r   r!   r7   Zsrc_lenexpanded_maskinverted_maskr   r   r   r$      s
   *z#AttentionMaskConverter._expand_maskr:   	min_dtypec                 C   s0   | j tjkr
td| tj| |kd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)r/   Zkeepdim)r   r(   r'   r   mulall)r:   r<   r   r   r   _unmask_unattended   s
   *z)AttentionMaskConverter._unmask_unattendedFattention_maskinputs_embedsis_trainingc           
      C   s   |j d |j d }}|| }tj pt|tjjpt }d}	| du r<|s(|s:|dks0||kr:|du s8||k r:d}	|	S |du sD||k r`t| j dkrMdS |s`t	| 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   FNT   )
r"   r(   jit
is_tracing
isinstancefxProxyr   lenr>   )
r@   rA   r   r	   rB   _r   r   rE   ignore_causal_maskr   r   r   _ignore_causal_mask_sdpa   s(   z/AttentionMaskConverter._ignore_causal_mask_sdpaN)r   r   N)NF)__name__
__module____qualname____doc__r'   __annotations__intr   r   r(   r   r   r   Tensorr   r,   staticmethodSizer   r$   ZFloatTensorfloatr?   rL   r   r   r   r   r      s   
 
&
/!"0r   r@   r   rA   r   r	   c           	      C   s   t d|d}|d | }| dur%t| jdkr%|j| |d ||jd} | S | durdt| jdkrd|d d	|d	 |f}t| j|krOtd
t| j d| dd|  }||t	j
t	|jj} | S |j|d |d ||j|jd} | 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   N   )r   r   rC   r   r   z#Incorrect 4D attention_mask shape: z; expected: .r9   r.   )r   rI   r"   r,   r   tupler   r&   r%   r(   r'   r)   r*   r   r   )	r@   r   rA   r   r	   attn_mask_converterr   Zexpected_shaper;   r   r   r   !_prepare_4d_causal_attention_mask.  s,   r^   c           
      C   s   t d|d}|d | }tj pt|tjjpt }t j| |||d}|r*d}	|	S | du r@|j	|d |d ||j
|jd}	|	S |  dkrI| }	n|j| |d |j
|d	}	|si|	jjd
krit j|	t|j
jd}	|	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).
    TrY   r   )r@   rA   r   r	   Nr   r.   rC   )r   r   cuda)r<   )r   r(   rD   rE   rF   rG   rH   r   rL   r   r   r   r/   r,   typer?   r)   r*   )
r@   r   rA   r   r	   r]   r   rE   rK   r+   r   r   r   *_prepare_4d_causal_attention_mask_for_sdpac  s<   
ra   r8   r   r!   c                 C   s   t j| ||d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.
    r8   r   r!   )r   r$   rc   r   r   r   _prepare_4d_attention_mask  s   rd   c                 C   s^   | j \}}|dur|n|}tj pt| tjjpt }|s't| dkr'dS t	j
| ||dS )rb   Nr   rc   )r"   r(   rD   rE   rF   rG   rH   r   r>   r   r$   )r8   r   r!   rJ   r   rE   r   r   r   #_prepare_4d_attention_mask_for_sdpa  s   
re   r   r   c                 C   s8   t d|d}|| d  }|j| d | 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.
    TrY   r   r   r.   )r   r   )r   r   r   r   r	   r]   r   r@   r   r   r    _create_4d_causal_attention_mask  s   rf   rM   rN   )dataclassesr   typingr   r   r(   Zutils.import_utilsr   r   rU   rW   r\   listrT   r^   ra   r   rd   re   r   rf   r   r   r   r   <module>   sb     
:
 : 