a
    hT                     @   s  d Z 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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 )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.
    )	dataclass)OptionalUnionN   )is_torchdynamo_compilingc                	   @   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 u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   a/var/www/html/assistant/venv/lib/python3.9/site-packages/transformers/modeling_attn_mask_utils.py__init__?   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u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.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_4dH   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ur`| jr`|du r>td|| }| j|||j|| jd}n| jdurrtd| j|||d d|j}|du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_4di   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ur|| d }	t jt j|t jd|	d	}
t r| }||
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_condr2   Zcontext_maskr   r   r   r      s    "
 z(AttentionMaskConverter._make_causal_maskr:   r   r"   c                 C   st   |   \}}|dur|n|}| ddddddf |d|||}tj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         ?r1   )	r4   r8   r&   r)   Ztensorr'   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)r0   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 p:t|tjjp:t }d}	| du rv|sP|s|dks`||kr|du sp||k rd}	nH|du s||k rt| j dkrdS |st	| dkr|dks||krd}	|	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   lenrB   )
rD   rE   r   r	   rF   _r   r   rI   ignore_causal_maskr   r   r   _ignore_causal_mask_sdpa   s2    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   rP   r   r   r   r   r      s`   
 & /  !0  r   )rD   r   rE   r   r	   c           	      C   s   t d|d}|d | }| durHt| jdkrH|j| |d ||jd} n| du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   rG   r   r   z#Incorrect 4D attention_mask shape: z; expected: .r<   r/   )r   rM   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_mask4  s(    r_   c           
      C   s   t d|d}|d | }tj p4t|tjjp4t }t j| |||d}|rRd}	n|| du r||j	|d |d ||j
|jd}	nR|  dkr| }	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   )rD   rE   r   r	   Nr   r/   rG   )r   r   cuda)r@   )r   r)   rH   rI   rJ   rK   rL   r   rP   r    r   r   r0   r-   typerC   r*   r+   )
rD   r   rE   r   r	   r^   r   rI   rO   r,   r   r   r   *_prepare_4d_causal_attention_mask_for_sdpai  s8    
rb   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    rd   c                 C   sb   | j \}}|dur|n|}tj p6t| tjjp6t }|sNt| dkrNdS t	j
| ||dS dS )rc   Nr   r;   )r#   r)   rH   rI   rJ   rK   rL   r   rB   r   r%   )r:   r   r"   rN   r   rI   r   r   r   #_prepare_4d_attention_mask_for_sdpa  s    
re   )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   r/   )r   r    )r   r   r   r   r	   r^   r   rD   r   r   r    _create_4d_causal_attention_mask  s    rf   )N)N)N)N)r   N)rT   dataclassesr   typingr   r   r)   Zutils.import_utilsr   r   rW   rY   r]   listrV   r_   rb   r   rd   re   r   rf   r   r   r   r   <module>   sH      : :  