
    2VhR                         d dl Z d dlmZ d dlmZ d dlmZ d dlmZ d dlmZ d dlm	Z	 d dl
mZ d d	lmZ d d
lmZ d dlmZ  ed       G d de             Zy)    N)constraints)initializers)ops)regularizers)keras_export)is_flash_attention_enabled)Softmax)EinsumDense)Layer)Dropoutz keras.layers.GroupQueryAttentionc                        e Zd ZdZ	 	 	 	 	 	 	 	 	 	 	 d fd	Z	 ddZd Z	 	 	 	 	 	 	 	 ddZ	 	 	 	 	 ddZddZ		 ddZ
dd	Z	 dd
Z fdZ xZS )GroupedQueryAttentiona7  Grouped Query Attention layer.

    This is an implementation of grouped-query attention introduced by
    [Ainslie et al., 2023](https://arxiv.org/abs/2305.13245). Here
    `num_key_value_heads` denotes number of groups, setting
    `num_key_value_heads` to 1 is equivalent to multi-query attention, and
    when `num_key_value_heads` is equal to `num_query_heads` it is equivalent
    to multi-head attention.

    This layer first projects `query`, `key`, and `value` tensors. Then, `key`
    and `value` are repeated to match the number of heads of `query`.

    Then, the `query` is scaled and dot-producted with `key` tensors. These are
    softmaxed to obtain attention probabilities. The value tensors are then
    interpolated by these probabilities and concatenated back to a single
    tensor.

    Args:
        head_dim: Size of each attention head.
        num_query_heads: Number of query attention heads.
        num_key_value_heads: Number of key and value attention heads.
        dropout: Dropout probability.
        use_bias: Boolean, whether the dense layers use bias vectors/matrices.
        flash_attention: If `None`, the layer attempts to use flash
            attention for faster and more memory-efficient attention
            computations when possible. This behavior can be configured using
            `keras.config.enable_flash_attention()` or
            `keras.config.disable_flash_attention()`.
        kernel_initializer: Initializer for dense layer kernels.
        bias_initializer: Initializer for dense layer biases.
        kernel_regularizer: Regularizer for dense layer kernels.
        bias_regularizer: Regularizer for dense layer biases.
        activity_regularizer: Regularizer for dense layer activity.
        kernel_constraint: Constraint for dense layer kernels.
        bias_constraint: Constraint for dense layer kernels.
        seed: Optional integer to seed the dropout layer.

    Call arguments:
        query: Query tensor of shape `(batch_dim, target_seq_len, feature_dim)`,
            where `batch_dim` is batch size, `target_seq_len` is the length of
            target sequence, and `feature_dim` is dimension of feature.
        value: Value tensor of shape `(batch_dim, source_seq_len, feature_dim)`,
            where `batch_dim` is batch size, `source_seq_len` is the length of
            source sequence, and `feature_dim` is dimension of feature.
        key: Optional key tensor of shape
            `(batch_dim, source_seq_len, feature_dim)`. If not given, will use
            `value` for both `key` and `value`, which is most common case.
        attention_mask: A boolean mask of shape
            `(batch_dim, target_seq_len, source_seq_len)`, that prevents
            attention to certain positions. The boolean mask specifies which
            query elements can attend to which key elements, where 1 indicates
            attention and 0 indicates no attention. Broadcasting can happen for
            the missing batch dimensions and the head dimension.
        return_attention_scores: A boolean to indicate whether the output
            should be `(attention_output, attention_scores)` if `True`, or
            `attention_output` if `False`. Defaults to `False`.
        training: Python boolean indicating whether the layer should behave in
            training mode (adding dropout) or in inference mode (no dropout).
            Will go with either using the training mode of the parent
            layer/model or `False` (inference) if there is no parent layer.
        use_causal_mask: A boolean to indicate whether to apply a causal mask to
            prevent tokens from attending to future tokens (e.g., used in a
            decoder Transformer).

    Returns:
        attention_output: Result of the computation, of shape
            `(batch_dim, target_seq_len, feature_dim)`, where `target_seq_len`
            is for target sequence length and `feature_dim` is the query input
            last dim.
        attention_scores: (Optional) attention coefficients of shape
            `(batch_dim, num_query_heads, target_seq_len, source_seq_len)`.
    c                    t        |   di | d| _        || _        || _        || _        ||z  dk7  rt        d      ||z  | _        || _        || _	        |xs
 t               | _        t        j                  |      | _        t        j                  |      | _        t!        j                  |	      | _        t!        j                  |
      | _        t!        j                  |      | _        t)        j                  |      | _        t)        j                  |      | _        || _        dt1        j2                  t5        | j                              z  | _        d| _        | j                  r| j                  dkD  rt        d      y y )	NTr   z=`num_query_heads` must be divisible by `num_key_value_heads`.g      ?F        zkDropout is not supported when flash attention is enabled. Please set dropout to 0.0 to use flash attention. )super__init__supports_maskinghead_dimnum_query_headsnum_key_value_heads
ValueErrornum_repeatsdropoutuse_biasr   _flash_attentionr   getkernel_initializerbias_initializerr   kernel_regularizerbias_regularizeractivity_regularizerr   kernel_constraintbias_constraintseedmathsqrtfloat_inverse_sqrt_head_dim_return_attention_scores)selfr   r   r   r   r   flash_attentionr   r   r    r!   r"   r#   r$   r%   kwargs	__class__s                   b/home/dcms/DCMS/lib/python3.12/site-packages/keras/src/layers/attention/grouped_query_attention.pyr   zGroupedQueryAttention.__init__Z   sg   $ 	"6" $ .#6 00A5O  +.AA  / O3M3O"."2"23E"F , 0 01A B"."2"23E"F , 0 01A B$0$4$45I$J!!,1B!C*?	&)DIIeDMM6J,K&K#(-%   T\\C%7D  &8     c                    ||n|}|d   | _         t        	 dd | j                  | j                  f| j                  rdnd dd| j                         | _        | j                  j                  |       t        	 dd | j                  | j                  f| j                  rdnd dd| j                         | _	        | j                  j                  |       t        	 dd | j                  | j                  f| j                  rdnd dd| j                         | _
        | j                  j                  |       t        d| j                        | _        t        | j                  | j                  | j                   	      | _        d
| _        d| _        t        	 dd | j                   f| j                  rdnd dd| j                         | _        | j(                  j                  d d | j                  | j                  f       y )Nuhquery)output_shape	bias_axesnamevhkeyvalue)axisdtype)rater<   r%   zbquh,bkuh->buqkzbuqk,bkuh->bquhmattention_output)zbqm,muh->bquh)zbkm,mvh->bkvh)zbquh,uhm->bqm)feature_dimr
   r   r   r   _get_common_kwargs_for_sublayer_query_densebuildr   
_key_dense_value_denser	   dtype_policy_softmaxr   r   r%   _dropout_layer_dot_product_equation_combine_equation_output_denser+   query_shapevalue_shape	key_shapes       r/   rC   zGroupedQueryAttention.build   s    $-#4K)	&r?'
 4 4dmmD"mmd	

 224
 	,%
 8 8$--H"mmd	

 224
 	i('
 8 8$--H"mmd	

 224
 	,Rt/@/@A%T%6%6TYY
 &7"!2(
 0 01!]]c#	

 224
 	  4--t}}=	
r0   c                    t        | j                  | j                  | j                  | j                  | j
                  | j                        }| j                  j                  j                  | j                  j                               }| j                  j                  j                  | j                  j                               }||d<   ||d<   |S )N)r    r!   r"   r#   r$   r<   r   r   )dictr    r!   r"   r#   r$   rF   r   r.   from_config
get_configr   )r+   common_kwargsr   r   s       r/   rA   z5GroupedQueryAttention._get_common_kwargs_for_sublayer   s    #66!22!%!:!:"44 00##
 "44>>JJ##..0
  00::FF!!,,.
 /A*+,<()r0   c           	         || _         ||}| j                  |||||||
      }| j                  |      }| j                  |      }| j	                  |      }t        j                  || j                  d      }t        j                  || j                  d      }| j                  |||||	      \  }}| j                  |      }|r||fS |S )N)
query_mask
value_maskkey_maskattention_maskuse_causal_mask   r;   )rY   training)
r*   _compute_attention_maskrB   rD   rE   r   repeatr   _compute_attentionrK   )r+   r4   r:   r9   rV   rW   rX   rY   return_attention_scoresr]   rZ   outputscoress                r/   callzGroupedQueryAttention.call   s     )@%;C55!!)+ 6 
 !!%(ooc"!!%(jj!!
 

4##!
 00) 1 
 ##
 #6>!r0   c                    d}|,t        j                  |d      }t        j                  |d      }|5t        j                  |d      }t        j                  |d      }	||	n||	z  }|5t        j                  |d      }t        j                  |d      }	||	n||	z  }|r| j                  ||      }	||	n||	z  }|!||nt        j                  |t              |z  }|S )a  Computes the attention mask, using the Keras masks of the inputs.

        * The `query`'s mask is reshaped from [B, T] to [B, T, 1].
        * The `value`'s mask is reshaped from [B, S] to [B, 1, S].
        * The `key`'s mask is reshaped from [B, S] to [B, 1, S]. The `key`'s
          mask is ignored if `key` is `None` or if `key is value`.
        * If `use_causal_mask=True`, then the causal mask is computed. Its shape
          is [1, T, S].

        All defined masks are merged using a logical AND operation (`&`).

        In general, if the `query` and `value` are masked, then there is no need
        to define the `attention_mask`.

        Args:
            query: Projected query tensor of shape `(B, T, N, key_dim)`.
            key: Projected key tensor of shape `(B, T, N, key_dim)`.
            value: Projected value tensor of shape `(B, T, N, value_dim)`.
            attention_mask: a boolean mask of shape `(B, T, S)`, that prevents
                attention to certain positions.
            use_causal_mask: A boolean to indicate whether to apply a causal
                mask to prevent tokens from attending to future tokens (e.g.,
                used in a decoder Transformer).

        Returns:
            attention_mask: a boolean mask of shape `(B, T, S)`, that prevents
                attention to certain positions, based on the Keras masks of the
                `query`, `key`, `value`, and `attention_mask` tensors, and the
                causal mask if `use_causal_mask=True`.
        Nboolr2   )r   castexpand_dims_compute_causal_maskrf   )
r+   r4   r:   rV   rW   rX   rY   rZ   	auto_maskmasks
             r/   r^   z-GroupedQueryAttention._compute_attention_mask  s    P 	!*f5J
B7I!*f5J??:r2D ) 1y47GIxx&1H??8R0D ) 1y47GI,,UE:D ) 1y47GI  ") XXnd3i? 
 r0   c                 &   t        j                  |      d   }||nt        j                  |      d   }t        j                  d||fd      }t        j                  |d      }t        j                  |d      }t        j                  ||      S )a  Computes a causal mask (e.g., for masked self-attention layers).

        For example, if query and value both contain sequences of length 4,
        this function returns a boolean tensor equal to:

        ```
        [[[True,  False, False, False],
          [True,  True,  False, False],
          [True,  True,  True,  False],
          [True,  True,  True,  True]]]
        ```

        Args:
            query: query tensor of shape `(B, T, ...)`.
            value: value tensor of shape `(B, S, ...)` (optional, defaults to
                query).

        Returns:
            mask: a boolean tensor of shape `(1, T, S)` containing a lower
                triangular matrix of shape `(T, S)`.
           int32r<   rg   r\   r2   )r   shapeonescumsumgreater_equal)r+   r4   r:   q_seq_lengthv_seq_length	ones_mask	row_index	col_indexs           r/   rj   z*GroupedQueryAttention._compute_causal_maskZ  sz    , yy'*',}|#))E:J1:MHHa|<GL	JJyr2	JJyr2	  I66r0   c           
      R   | j                   r| j                  rt        d      | j                  dkD  xs& | j                  xs t	        |j
                        dk7   }|r|Xd}d}t        |t	        |j
                        z
        D ]  }	t        j                  ||      } t        j                  |d      }t        j                  |||d || j                  d| j                   	      }
|
d fS t        j                  |t        j                  | j                  |j                              }t        j                  | j                  ||      }| j!                  ||
      }| j                  dkD  r| j#                  ||      }n|}t        j                  | j$                  ||      }||fS )NzReturning attention scores is not supported when flash attention is enabled. Please disable flash attention to access attention scores.r      r\   rf   rp   F)r4   r9   r:   biasrl   scale	is_causalr,   )rY   )r]   )r   r*   r   r   lenrq   ranger   ri   rh   dot_product_attentionr)   multiplyr<   einsumrI   _masked_softmaxrH   rJ   )r+   r4   r9   r:   rY   r]   use_dot_product_attentionmask_expansion_axislen_attention_scores_shape_r?   rc   scores_dropoutrb   s                 r/   r`   z(GroupedQueryAttention._compute_attentionw  s      T%B%B%  LL3 ',,'EKK A%%
! %) '1#-.*.^5I5I1JJ A &)__&-@&N "%.!G"88#11 $ 5 5	  $T)) 388D77E

 &&s
 %%f^%L <<#!00(0KN#ND22NEJv~r0   c                     |Rd}t        t        |j                        t        |j                        z
        D ]  }t        j                  ||      } | j                  ||      S )Nr|   r\   )rl   )r   r   rq   r   ri   rG   )r+   rc   rY   r   r   s        r/   r   z%GroupedQueryAttention._masked_softmax  sh     % #-3v||,s>3G3G/HHI !$")<" }}V.}99r0   c           
          ||}|d   |d   k7  rt        d|d    d|d    d| d|       |dd |dd k7  rt        d| d|       |S )	Nr2   zMThe last dimension of `query_shape` and `value_shape` must be equal, but are z, z. Received: query_shape=z, value_shape=rn   z_All dimensions of `value` and `key`, except the last one, must be equal. Received: value_shape=z and key_shape=)r   rL   s       r/   compute_output_shapez*GroupedQueryAttention.compute_output_shape  s     #Ir?k"o-**5b/):"[_<M N))4 6*m-  q	!B/88C} E&K)  r0   c                 Z   | j                   | j                  | j                  | j                  | j                  t        j                  | j                        t        j                  | j                        t        j                  | j                        t        j                  | j                        t        j                  | j                        t        j                  | j                        t        j                  | j                        | j                   d}t"        | I         }i ||S )N)r   r   r   r   r   r   r   r    r!   r"   r#   r$   r%   )r   r   r   r   r   r   	serializer   r   r   r    r!   r"   r   r#   r$   r%   r   rS   )r+   configbase_configr.   s      r/   rS   z GroupedQueryAttention.get_config  s    #33#'#;#;||"."8"8''# !- 6 6t7L7L M"."8"8''# !- 6 6t7L7L M$0$:$:))% "-!6!6t7M7M!N*44T5I5IJII'
* g(*(+(((r0   )r   TNglorot_uniformzerosNNNNNN)N)NNNNNFNF)NNNNF)NN)__name__
__module____qualname____doc__r   rC   rA   rd   r^   rj   r`   r   r   rS   __classcell__)r.   s   @r/   r   r      s    G\ + !0l 	<
|4  %4t BH7< @D?B:$ 	4) )r0   r   )r&   	keras.srcr   r   r   r   keras.src.api_exportr   keras.src.backend.configr   $keras.src.layers.activations.softmaxr	   "keras.src.layers.core.einsum_denser
   keras.src.layers.layerr   'keras.src.layers.regularization.dropoutr   r   r   r0   r/   <module>r      sJ     ! "  " - ? 8 : ( ; 01g)E g) 2g)r0   