U
    4AfRS                     @   s  d dl mZ d dlmZmZmZmZ d dlZeG dd dZdeej	 eej
eef ej	eee dddZdeej	 eej
eef ej	eee dd	d
Zdej	ejee dddZdej	ejee dddZdeej
eef ejejeee eej	 dddZdS )    )	dataclass)ListOptionalTupleUnionNc                	   @   s  e Zd ZU dZeed< eed< deee dddZdeeee	j
ee	jd	f ee	j d
ddZd e	jee	j
ee e	jdddZed!e	je	j
e	jeee dddZed"e	je	j
ee dddZee	jedddZed#ee	j e	jeee eed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_windowNr   r	   c                 C   s6   || _ || _| jd k	r2| jdkr2td| j d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   I/tmp/pip-unpacked-wheel-zw5xktn0/transformers/modeling_attn_mask_utils.py__init__7   s    zAttentionMaskConverter.__init__cpustr)
batch_sizequery_lengthkey_value_lengthdtypedevicereturnc           	      C   s\   | j std| j d||f}|| }d}|d dksB| jdk	rX| 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.N   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_4d@   s    z#AttentionMaskConverter.to_causal_4d)attention_mask_2dr   r   r   r   c           
      C   s   |j d |f}d}|d dks(| jdk	r`| jr`|dkr>td|| }| j|||j|| jd}n| jdk	rrtd| j|||d d|j}|dk	r|	|
 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_4da   s0    
zAttentionMaskConverter.to_4dr   )input_ids_shaper   r   r   r	   c                 C   s   | \}}t j||ft |j|d}t j|d|d}|||d |ddk d ||}|dkrt j	t j
||||d|gdd}|dk	r|| d }	t jt j|t jd|	d	}
||
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'   catzerosZtrilZ	ones_liker)   expand)r/   r   r   r   r	   bszr#   maskZ	mask_condr2   Zcontext_maskr   r   r   r      s    "
 z(AttentionMaskConverter._make_causal_maskr:   r   r#   c                 C   sj   |   \}}|dk	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         ?)r4   r8   r'   r(   r*   r)   r+   r,   )r:   r   r#   r9   Zsrc_lenexpanded_maskinverted_maskr   r   r   r&      s
    *z#AttentionMaskConverter._expand_maskr=   	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)r1   Zkeepdim)r   r*   r)   r   mulallr?   r   r   r   _unmask_unattended   s
    *z)AttentionMaskConverter._unmask_unattendedF)attention_maskinputs_embedsr   r	   is_trainingr   c           
      C   s   |j d |j d  }}|| }tj pHt|tjjpHttdoHtj	 }d}	| dkr|s^|s|dksn||kr|dks~||k rd}	nL|dks||k rt
| j dkrdS |s|st| dkr|dks||krd}	|	S )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   _dynamoFNT   )r$   r*   jit
is_tracing
isinstancefxProxyhasattrrG   is_compilinglenrB   )
rD   rE   r   r	   rF   _r   r   rJ   ignore_causal_maskr   r   r   _ignore_causal_mask_sdpa   s:    
z/AttentionMaskConverter._ignore_causal_mask_sdpa)N)r   )N)r   N)N)NF)__name__
__module____qualname____doc__r)   __annotations__intr   r   r*   r   r   r   Tensorr!   r.   staticmethodSizer   r&   ZFloatTensorfloatrC   rS   r   r   r   r   r      s`   
 & /  0  r   )rD   r   rE   r   r	   c           	      C   s   t d|d}|d | }| dk	rHt| jdkrH|j| |d ||jd} n| dk	rt| jdkr|d d	|d	 |f}t| j|krtd
t| j d| dqd|  }||t	j
t	|jj} n |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.
    Tr
   r   N   )r   r   rH   r   r   z#Incorrect 4D attention_mask shape: z; expected: .r<   r0   )r   rP   r$   r.   r   tupler   r(   r'   r*   r)   r+   r,   r!   r   )	rD   r   rE   r   r	   attn_mask_converterr   Zexpected_shaper>   r   r   r   !_prepare_4d_causal_attention_mask$  s8       
     rb   c           
      C   s   t d|d}|d | }tj pBt|tjjpBttdoBtj	 }t j
| |||d}|r`d}	n| dkr|j|d |d ||j|jd}	nf|  d	kr|  dkrtd
| }	n|j| |d |j|d}	|s|	jjdkrt 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).
    Tr
   r   rG   )rD   rE   r   r	   Nr   r0   rH   zGCustom 4D attention mask should be passed in inverted form with max==0`)r   r   Zcuda)r@   )r   r*   rI   rJ   rK   rL   rM   rN   rG   rO   rS   r!   r   r   r1   maxr   r.   typerC   r+   r,   )
rD   r   rE   r   r	   ra   r   rJ   rR   r-   r   r   r   *_prepare_4d_causal_attention_mask_for_sdpaY  sN    
    
 re   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.
    r;   )r   r&   r;   r   r   r   _prepare_4d_attention_mask  s    rg   c                 C   sp   | j \}}|dk	r|n|}tj pDt| tjjpDttdoDtj	 }|s\t
| dkr\dS tj| ||dS dS )rf   NrG   r   r;   )r$   r*   rI   rJ   rK   rL   rM   rN   rG   rO   rB   r   r&   )r:   r   r#   rQ   r   rJ   r   r   r   #_prepare_4d_attention_mask_for_sdpa  s    

rh   )r   r   r   r   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.
    Tr
   r   r   r0   )r   r!   )r   r   r   r   r	   ra   r   rD   r   r   r    _create_4d_causal_attention_mask  s        ri   )N)N)N)N)r   N)Zdataclassesr   typingr   r   r   r   r*   r   rZ   r\   rY   rb   re   r   rg   rh   r   ri   r   r   r   r   <module>   sD      : A!  