o
    Zh`                    @  s  d Z ddlmZ ddlZddlZddlmZ ddlm	Z	m
Z
mZmZ ddlZddlZddlmZ ddlmZmZ dd	lmZmZmZmZmZmZ dd
lmZmZm Z  ddl!m"Z"m#Z#m$Z$m%Z%m&Z&m'Z' ddl(m)Z)m*Z*m+Z+ e&,e-Z.e% rzddl/Z0e0j1j2dddZ3W n& e4y   e.5d Y nw zddl/Z0e0j1j2dddZ3W n	 e4y   Y nw dZ6dZ7dkdlddZ8dmddZ9dndd Z:dod#d$Z;dpdqd+d,Z<drdsd1d2Z=dtd6d7Z>eG d8d9 d9e"Z?G d:d; d;ej@jAZBG d<d= d=ej@jAZCG d>d? d?ej@jAZDG d@dA dAej@jAZEG dBdC dCej@jAZFG dDdE dEej@jAZGG dFdG dGej@jAZHG dHdI dIej@jAZIG dJdK dKeIZJG dLdM dMej@jAZKG dNdO dOej@jAZLG dPdQ dQej@jAZMG dRdS dSej@jAZNG dTdU dUej@jAZOG dVdW dWej@jAZPeG dXdY dYej@jAZQeG dZd[ d[ej@jAZReG d\d] d]ej@jAZSG d^d_ d_eZTd`ZUdaZVdbZWdcZXG ddde deeTZYG dfdg dgeTZZe#eUG dhdi dieTZ[g djZ\dS )uzTF 2.0 GroupViT model.    )annotationsN)	dataclass)AnyOptionalTupleUnion   )get_tf_activation)TFBaseModelOutputTFBaseModelOutputWithPooling)TFModelInputTypeTFPreTrainedModelget_initializerkeraskeras_serializableunpack_inputs)check_embeddings_within_bounds
shape_liststable_softmax)ModelOutputadd_start_docstrings%add_start_docstrings_to_model_forward#is_tensorflow_probability_availableloggingreplace_return_docstrings   )GroupViTConfigGroupViTTextConfigGroupViTVisionConfig              ?)locscalea  GroupViT models are not usable since `tensorflow_probability` can't be loaded. It seems you have `tensorflow_probability` installed with the wrong tensorflow version.Please try to reinstall it following the instructions here: https://github.com/tensorflow/probability.znvidia/groupvit-gcc-yfccg    חmask	tf.Tensortgt_lenOptional[int]c                 C  sj   t | d }|dur|n|}td}tj| |jd} t| ddddddf dd|df}|| t S )z_
    Expands attention_mask from `[bsz, seq_len]` to `[bsz, 1, tgt_seq_len, src_seq_len]`.
    r   Nr    dtype)r   tfZconstantcastr(   tileLARGE_NEGATIVE)r#   r%   Zsrc_lenZone_cstZexpanded_mask r-   `/var/www/auris/lib/python3.10/site-packages/transformers/models/groupvit/modeling_tf_groupvit.py_expand_maskR   s   
(r/   logitsreturnc                 C  s(   t jtjjt t| d | ddS )Nr   T)Zy_trueZy_predZfrom_logits)r)   mathreduce_meanr   ZmetricsZsparse_categorical_crossentropyranger   )r0   r-   r-   r.   contrastive_lossa   s
   r5   
similarityc                 C  s"   t | }t t| }|| d S )Ng       @)r5   r)   	transpose)r6   Zcaption_lossZ
image_lossr-   r-   r.   groupvit_lossj   s   r8   dimintc                 C  sX   t | |}t||}tj|t| | ttt| | |jd}|t| | }|S )Ndepthaxisr(   )	r   r)   argmaxone_hotr   r4   lenr(   stop_gradient)r0   r9   y_softindexy_hardretr-   r-   r.   hard_softmaxp   s   

rF   Ftaufloathardboolc           
      C  s   t jdd}|jt| | jd}| | | }t||}|rFt||}tj	|t
| | ttt
| | |jd}|t| | }	|	S |}	|	S )Nr   r    r'   r;   )tfpdistributionsZGumbelsampler)   shaper(   r   r>   r?   r   r4   r@   rA   )
r0   rH   rJ   r9   Zgumbel_distZgumbelsrB   rC   rD   rE   r-   r-   r.   gumbel_softmax   s    

rP   
attentionsheightwidthalign_cornersc           	      C  s   || | j d  d }||kr!tt|| }t| d | }ntt|| }t| d | }t| d }t| d }t| ||||f} tj| dd} |r`tjj	j
j| ||fd|d} ntj
j| ||fdd	} tj| d
d} | S )a  
    Args:
        attentions (`tf.Tensor`): attention map of shape [batch_size, groups, feat_height*feat_width]
        height (`int`): height of the output attention map
        width (`int`): width of the output attention map
        align_corners (`bool`, *optional*): the `align_corner` argument for `nn.functional.interpolate`.

    Returns:
        `tf.Tensor`: resized attention map of shape [batch_size, groups, height, width]
       g      ?r   r   r   rU   r   r   permZbilinear)sizemethodrT   )rY   rZ   )r   r   r   rU   )rO   r:   nproundr   r)   reshaper7   compatv1imageresize)	rQ   rR   rS   rT   r"   Z
feat_widthZfeat_height
batch_sizegroupsr-   r-   r.   resize_attention_map   s(   
rd   Tuple[tf.Tensor]hw_shape
Tuple[int]c                 C  sp   g }d}| D ](}t j|dd}|du r|}nt ||}tt j|ddg|R  }|| q|d }t |S )a(  
    Args:
        attentions (`tuple(tf.Tensor)`: tuple of attention maps returned by `TFGroupViTVisionTransformer`
        hw_shape (`tuple(int)`): height and width of the output attention map
    Returns:
        `tf.Tensor`: the attention map of shape [batch_size, groups, height, width]
    Nr   rU   r   rW   rG   )r)   r7   matmulrd   appendrA   )rQ   rf   Z	attn_mapsZprev_attn_masksZ
attn_masksZcur_attn_mapZfinal_groupingr-   r-   r.   get_grouping_from_attentions   s   	
rk   c                   @  s|   e Zd ZU dZdZded< dZded< dZded< dZded< dZ	ded	< dZ
ded
< dZded< dZded< dddZdS )TFGroupViTModelOutputa8  
    Args:
        loss (`tf.Tensor` of shape `(1,)`, *optional*, returned when `return_loss` is `True`):
            Contrastive loss for image-text similarity.
        logits_per_image (`tf.Tensor` of shape `(image_batch_size, text_batch_size)`):
            The scaled dot product scores between `image_embeds` and `text_embeds`. This represents the image-text
            similarity scores.
        logits_per_text (`tf.Tensor` of shape `(text_batch_size, image_batch_size)`):
            The scaled dot product scores between `text_embeds` and `image_embeds`. This represents the text-image
            similarity scores.
        segmentation_logits (`tf.Tensor` of shape `(batch_size, config.num_labels, logits_height, logits_width)`):
            Classification scores for each pixel.

            <Tip warning={true}>

            The logits returned do not necessarily have the same size as the `pixel_values` passed as inputs. This is
            to avoid doing two interpolations and lose some quality when a user needs to resize the logits to the
            original image size as post-processing. You should always check your logits shape and resize as needed.

            </Tip>

        text_embeds (`tf.Tensor` of shape `(batch_size, output_dim`):
            The text embeddings obtained by applying the projection layer to the pooled output of
            [`TFGroupViTTextModel`].
        image_embeds (`tf.Tensor` of shape `(batch_size, output_dim`):
            The image embeddings obtained by applying the projection layer to the pooled output of
            [`TFGroupViTVisionModel`].
        text_model_output (`TFBaseModelOutputWithPooling`):
            The output of the [`TFGroupViTTextModel`].
        vision_model_output (`TFBaseModelOutputWithPooling`):
            The output of the [`TFGroupViTVisionModel`].
    Ntf.Tensor | NonelossOptional[tf.Tensor]logits_per_imagelogits_per_textsegmentation_logitstext_embedsimage_embedsr   text_model_outputvision_model_outputr1   
Tuple[Any]c                   s   t  fdd  D S )Nc                 3  s.    | ]}|d vr | nt  | V  qdS ))ru   rv   N)getattrto_tuple).0kselfr-   r.   	<genexpr>	  s
    
z1TFGroupViTModelOutput.to_tuple.<locals>.<genexpr>)tuplekeysr|   r-   r|   r.   ry     s   zTFGroupViTModelOutput.to_tuple)r1   rw   )__name__
__module____qualname____doc__rn   __annotations__rp   rq   rr   rs   rt   ru   rv   ry   r-   r-   r-   r.   rl      s   
 !rl   c                      s4   e Zd Zd fddZddddZdddZ  ZS )TFGroupViTCrossAttentionLayerconfigr   c                   s`   t  jdi | t|dd| _tjj|jdd| _t	|dd| _
tjj|jdd| _|| _d S )Nattnnamenorm2epsilonr   mlp	norm_postr-   )super__init__TFGroupViTAttentionr   r   layersLayerNormalizationlayer_norm_epsr   TFGroupViTMLPr   r   r   r}   r   kwargs	__class__r-   r.   r     s   
z&TFGroupViTCrossAttentionLayer.__init__Fqueryr$   keytrainingrK   r1   c                 C  s<   |}|| j ||dd  }|| | | }| |}|S )N)encoder_hidden_statesr   )r   r   r   r   )r}   r   r   r   xr-   r-   r.   call  s
   
z"TFGroupViTCrossAttentionLayer.callNc                 C  sV  | j rd S d| _ t| dd d ur-t| jj | jd  W d    n1 s(w   Y  t| dd d urWt| jj | jd d | jj	g W d    n1 sRw   Y  t| dd d ur|t| j
j | j
d  W d    n1 sww   Y  t| dd d urt| jj | jd d | jj	g W d    d S 1 sw   Y  d S d S )NTr   r   r   r   )builtrx   r)   
name_scoper   r   buildr   r   hidden_sizer   r   r}   input_shaper-   r-   r.   r     s(   "z#TFGroupViTCrossAttentionLayer.buildr   r   F)r   r$   r   r$   r   rK   r1   r$   Nr   r   r   r   r   r   __classcell__r-   r-   r   r.   r     s    r   c                      s@   e Zd Zd fddZddddZddddZdddZ  ZS )TFGroupViTAssignAttentionr   r   c                   s   t  jdi | |jd | _tjj|jdd| _tjj|jdd| _tjj|jdd| _	tjj|jdd| _
|j| _|| _d S )N      q_projr   k_projv_projprojr-   )r   r   r   r"   r   r   Denser   r   r   r   
assign_epsr   r   r   r-   r.   r   2  s   
z"TFGroupViTAssignAttention.__init__TFr   r$   gumbelrK   rJ   r   r1   c                 C  s>   |r|rt |d|d}|S |rt|dd}|S t|dd}|S )N)r9   rJ   )r9   r=   )rP   rF   r   )r}   r   r   rJ   r   r-   r-   r.   get_attn=  s   z"TFGroupViTAssignAttention.get_attnr   r   c           	      C  s   |}|  |}| |}| |}tj||dd| j }| j||d}| j||ddd}|tjj|ddd| j	  }t||}| 
|}||fS )NTZtranspose_b)r   F)r   r   rJ   rG   r=   keepdims)r   r   r   r)   ri   r"   r   r2   Z
reduce_sumr   r   )	r}   r   r   r   valueZraw_attnr   Z	soft_attnoutr-   r-   r.   r   H  s   



zTFGroupViTAssignAttention.callNc                 C  sj  | j rd S d| _ t| dd d ur2t| jj | jd d | jjg W d    n1 s-w   Y  t| dd d ur\t| j	j | j	d d | jjg W d    n1 sWw   Y  t| dd d urt| j
j | j
d d | jjg W d    n1 sw   Y  t| dd d urt| jj | jd d | jjg W d    d S 1 sw   Y  d S d S )NTr   r   r   r   )r   rx   r)   r   r   r   r   r   r   r   r   r   r   r-   r-   r.   r   a  s(   "zTFGroupViTAssignAttention.buildr   )TTF)
r   r$   r   rK   rJ   rK   r   rK   r1   r$   r   )r   r$   r   r$   r   rK   r   )r   r   r   r   r   r   r   r   r-   r-   r   r.   r   1  s
    r   c                      s>   e Zd Zd fddZdddZddddZdddZ  ZS )TFGroupViTTokenAssignr   r   num_group_tokenr:   num_output_groupc                   s   t  jdi | || _tjj jdd| _t j	t
jjr! j	n j	 j	f} fdd|D \}}t |||dd| _tjj jdd| _tjj jdd| _t d	d| _t d
d| _tjj jdd| _t  j| jdd| _ | _d S )Nnorm_tokensr   c                   s   g | ]	}t | j qS r-   )r:   r   )rz   r   r   r-   r.   
<listcomp>~  s    z2TFGroupViTTokenAssign.__init__.<locals>.<listcomp>	mlp_interr   norm_post_tokensnorm_xpre_assign_attnassign
norm_new_xmlp_channelsr-   )r   r   r   r   r   r   r   r   
isinstanceassign_mlp_ratiocollectionsabcIterableTFGroupViTMixerMLPr   r   r   r   r   r   r   r   r   r   r   r   )r}   r   r   r   r   r   Z
tokens_dimZchannels_dimr   r   r.   r   t  s$   

zTFGroupViTTokenAssign.__init__group_tokensr$   r1   c                 C  s   |  |}| |}|S )z
        Args:
            group_tokens (tf.Tensor): group tokens, [batch_size, num_group_tokens, channels]

        Returns:
            projected_group_tokens (tf.Tensor): [batch_size, num_output_groups, channels]
        )r   r   )r}   r   projected_group_tokensr-   r-   r.   project_group_token  s   
	
z)TFGroupViTTokenAssign.project_group_tokenFimage_tokensr   rK   c                 C  s^   |  |}| |}| |}| ||}| ||\}}||7 }|| | | }||fS )z
        Args:
            image_tokens (`tf.Tensor`): image tokens, of shape [batch_size, input_length, channels]
            group_tokens (`tf.Tensor`): group tokens, [batch_size, num_group_tokens, channels]
        )r   r   r   r   r   r   r   )r}   r   r   r   r   Znew_image_tokens	attentionr-   r-   r.   r     s   


zTFGroupViTTokenAssign.callNc                 C  s  | j rd S d| _ t| dd d ur2t| jj | jd d | jjg W d    n1 s-w   Y  t| dd d urWt| j	j | j	d  W d    n1 sRw   Y  t| dd d urt| j
j | j
d d | jjg W d    n1 s|w   Y  t| dd d urt| jj | jd d | jjg W d    n1 sw   Y  t| dd d urt| jj | jd  W d    n1 sw   Y  t| dd d urt| jj | jd  W d    n1 sw   Y  t| dd d ur!t| jj | jd d | jjg W d    n	1 sw   Y  t| d	d d urKt| jj | jd  W d    d S 1 sDw   Y  d S d S )
NTr   r   r   r   r   r   r   r   )r   rx   r)   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r-   r-   r.   r     sH   $zTFGroupViTTokenAssign.build)r   r   r   r:   r   r:   )r   r$   r1   r$   r   )r   r$   r   r$   r   rK   r   )r   r   r   r   r   r   r   r   r-   r-   r   r.   r   s  s
    
r   c                      s:   e Zd ZdZd fddZ	ddddZdddZ  ZS )TFGroupViTPatchEmbeddingsz
    This class turns `pixel_values` of shape `(batch_size, num_channels, height, width)` into the initial
    `hidden_states` (patch embeddings) of shape `(batch_size, seq_length, hidden_size)` to be consumed by a
    Transformer.
    r   r   c                   s   t  jd	i | |j|j}}|j}|j| _t|tjj	r |n||f}t|tjj	r-|n||f}|d |d  |d |d   }|| _|| _|| _
|| _|| _tjj| j||dddt| jjddd	| _d S )
Nr   r   ZvalidZchannels_lastTzeros
projection)	filtersZkernel_sizestridespaddingZdata_formatZuse_biaskernel_initializerZbias_initializerr   r-   )r   r   
image_size
patch_sizenum_channelsr   r   r   r   r   num_patchesr   r   r   ZConv2Dr   initializer_ranger   )r}   r   r   r   r   r   r   r   r-   r.   r     s.    
z"TFGroupViTPatchEmbeddings.__init__Fpixel_valuesr$   interpolate_pos_encodingrK   r   r1   c              
   C  s   t |\}}}}t r|| jkrtd|s@t r@|| jd ks)|| jd kr@td| d| d| jd  d| jd  d	tj|dd	}| |}|| jd  || jd   }	tj	|||	| j
fd
}
|
S )NzeMake sure that the channel dimension of the pixel values match with the one set in the configuration.r   r   zInput image size (*z) doesn't match model ().rV   rW   tensorrO   )r   r)   Zexecuting_eagerlyr   
ValueErrorr   r7   r   r   r]   r   )r}   r   r   r   rb   r   rR   rS   r   r   
embeddingsr-   r-   r.   r     s$   (
zTFGroupViTPatchEmbeddings.callNc                 C  sn   | j rd S d| _ t| dd d ur5t| jj | jd d d | jg W d    d S 1 s.w   Y  d S d S )NTr   )r   rx   r)   r   r   r   r   r   r   r-   r-   r.   r     s   "zTFGroupViTPatchEmbeddings.buildr   r   FFr   r$   r   rK   r   rK   r1   r$   r   )r   r   r   r   r   r   r   r   r-   r-   r   r.   r     s    "r   c                      sD   e Zd ZdZd fddZdddZdddZ	ddddZ  ZS )TFGroupViTVisionEmbeddingsz7
    Construct the position and patch embeddings.

    r   r   c                   sR   t  jdi | t|dd| _tjj|jdd| _tjj|j	dd| _
|| _d S )Npatch_embeddingsr   dropout)rater   	layernormr   r-   )r   r   r   r   r   r   Dropoutr   r   r   r   r   r   r   r-   r.   r      s
   
z#TFGroupViTVisionEmbeddings.__init__Nc                 C  s(  | j j}| jd|| jjfdddd| _| jrd S d| _t| dd d ur@t	| j j
 | j d  W d    n1 s;w   Y  t| dd d uret	| jj
 | jd  W d    n1 s`w   Y  t| dd d urt	| jj
 | jd d | jjg W d    d S 1 sw   Y  d S d S )	Nr   r   Tposition_embeddingsrO   ZinitializerZ	trainabler   r   r   r   )r   r   
add_weightr   r   r   r   rx   r)   r   r   r   r   r   )r}   r   r   r-   r-   r.   r   (  s.   "z TFGroupViTVisionEmbeddings.buildr1   r$   c              	   C  s   t |\}}}t | jd }||kr||kr| jS | j}|| jj }	|| jj }
tjjtj|dtt	
|tt	
||fd|	|
fdd}tj|dd|fd}|S )a#  
        This method allows to interpolate the pre-trained position encodings, to be able to use the model on higher
        resolution images.

        Source:
        https://github.com/facebookresearch/dino/blob/de9ee3df6cf39fac952ab558447af1fa1365362a/vision_transformer.py#L174
        r   rO   Zbicubic)ZimagesrY   rZ   rG   r   )r   r   r   r   r)   r`   ra   r]   r:   r2   sqrt)r}   r   rR   rS   rb   r   r9   Znum_positionsZpatch_pos_embedZh0Zw0r-   r-   r.   r   >  s    	 z3TFGroupViTVisionEmbeddings.interpolate_pos_encodingFr   r   rK   r   c                 C  sX   t |\}}}}| j||d}| |}|r || ||| }n|| j }| |}|S )N)r   )r   r   r   r   r   r   )r}   r   r   r   _rR   rS   r   r-   r-   r.   r   Y  s   


zTFGroupViTVisionEmbeddings.callr   r   )r1   r$   r   r   )	r   r   r   r   r   r   r   r   r   r-   r-   r   r.   r     s    

r   c                      s@   e Zd Zd fddZdd fdd	Z			ddddZ  ZS )TFGroupViTTextEmbeddingsr   r   c                   s$   t  jdi | |j| _|| _d S )Nr-   )r   r   r   	embed_dimr   r   r   r-   r.   r   m  s   
z!TFGroupViTTextEmbeddings.__init__Nr   tf.TensorShapec                   s   t d | j| jj| jft| jj| jj ddd| _	W d    n1 s'w   Y  t d | j| jj
| jft| jj| jj ddd| _W d    n1 sSw   Y  t | d S )NZtoken_embeddingTweightr   position_embeddingr   )r)   r   r   r   
vocab_sizer   r   initializer_factorr   r   Zmax_position_embeddingsr   r   r   r   r   r-   r.   r   t  s"   

zTFGroupViTTextEmbeddings.build	input_idsro   position_idsinputs_embedsr1   r$   c                 C  s   |du r|du rt d|du rt|| jj tj| j|d}t|dd }|du r9tjtj	d|d ddd}tj| j
|d}tj||d ddfd	}|| }|S )
z
        Applies embedding based on inputs tensor.

        Returns:
            final_embeddings (`tf.Tensor`): output embedding tensor.
        Nz5You have to specify either input_ids or inputs_embedsparamsindicesrG   r   )startlimitr   r   )input	multiples)r   r   r   r   r)   gatherr   r   Zexpand_dimsr4   r   r+   )r}   r   r   r  r   Zposition_embedsZfinal_embeddingsr-   r-   r.   r     s   zTFGroupViTTextEmbeddings.callr   r   r   )r   r   NNN)r   ro   r   ro   r  ro   r1   r$   )r   r   r   r   r   r   r   r-   r-   r   r.   r   l  s    r   c                      s`   e Zd ZdZd" fd	d
Zd#ddZedd Zd$ddZd#d%ddZ				d&d'd d!Z
  ZS )(TFGroupViTStagezMThis corresponds to the `GroupingLayer` class in the GroupViT implementation.r   r   r<   r:   num_prev_group_tokenr   r   c                   s   t  jdi |  | _|| _|| _ fddt|D | _|dkr,t ||dd| _nd | _|dkrO|dkrOt	jj
 jddt | jd |d	d
g| _d S d | _d S )Nc                      g | ]}t  d | dqS z	layers_._r   TFGroupViTEncoderLayerrz   ir   r-   r.   r         z,TFGroupViTStage.__init__.<locals>.<listcomp>r   
downsample)r   r   r   r   zgroup_projector.0r   rU   zgroup_projector.1r   r-   )r   r   r   r<   r   r4   r   r   r  r   r   r   r   r   group_projector)r}   r   r<   r  r   r   r   r   r   r.   r     s(   	


zTFGroupViTStage.__init__Nc              	   C  s  | j dkr| jd| j | jjfdddd| _nd | _| jrd S d| _t| dd d urFt| j	j
 | j	d  W d    n1 sAw   Y  t| dd d uro| jD ]}t|j
 |d  W d    n1 siw   Y  qQt| d	d d urt| jd j
 | jd d d | jjg W d    n1 sw   Y  t| jd j
 | jd d  W d    d S 1 sw   Y  d S d S )
Nr   r   r   Tgroup_tokenr   r  r   r  )r   r   r   r   r  r   rx   r)   r   r  r   r   r   r  r}   r   layerr-   r-   r.   r     s:   


"zTFGroupViTStage.buildc                 C  s
   | j d uS r   )r  r|   r-   r-   r.   with_group_token  s   
z TFGroupViTStage.with_group_tokenr   r$   r1   c                 C  s>   | j r|d d d | j f |d d | j d f fS |d fS r   )r  r   )r}   r   r-   r-   r.   split_x  s   0zTFGroupViTStage.split_xr  rm   c                 C  s   |d u r|S t j||gddS )Nr   r   )r)   concat)r}   r   r  r-   r-   r.   concat_x  s   zTFGroupViTStage.concat_xFhidden_statesprev_group_tokenoutput_attentionsrK   r   re   c                 C  s   | j r&tj| jt|d ddfd}| jdur%| jD ]}||}q|| }nd}|}| ||}| jD ]}||dddd}	|	d }q3| |\}}d}
| j	durX| 	||\}}
||f}|rc||
f }|S )a  
        Args:
            hidden_states (`tf.Tensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
            attention_mask (`tf.Tensor`): attention mask of size
                `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
                `(config.encoder_attention_heads,)`.
            output_attentions (`bool`, *optional*):
                Whether or not to return the grouping tensors of Grouping block.
        r   r   )r  N)attention_maskcausal_attention_maskr   )
r  r)   r+   r  r   r  r  r   r  r  )r}   r  r  r   r   r  r  r   Zcat_xZ	layer_outr   outputsr-   r-   r.   r     s4   






zTFGroupViTStage.call)
r   r   r<   r:   r  r:   r   r:   r   r:   r   )r   r$   r1   r$   )r   r$   r  rm   r1   r$   )NFF)
r  r$   r  rm   r   rK   r   rK   r1   re   )r   r   r   r   r   r   propertyr  r  r  r   r   r-   r-   r   r.   r    s    
#

r  c                      s<   e Zd Z			dd fdd	ZddddZdddZ  ZS )r   Nr   r   r   r&   intermediate_sizeoutput_sizec                   s   t  jdi | || _t|j| _|d ur|n|j}|d ur!|n|j}|d ur*|n|}tj	j
|dd| _tj	j
|dd| _|| _|| _d S )Nfc1r   fc2r-   )r   r   r   r	   Z
hidden_actactivation_fnr   r%  r   r   r   r'  r(  )r}   r   r   r%  r&  r   r   r-   r.   r   )  s   
zTFGroupViTMLP.__init__Fr  r$   r   rK   r1   c                 C  s"   |  |}| |}| |}|S r   )r'  r)  r(  )r}   r  r   r-   r-   r.   r   <  s   


zTFGroupViTMLP.callc                 C  s   | j rd S d| _ t| dd d ur1t| jj | jd d | jg W d    n1 s,w   Y  t| dd d ur]t| jj | jd d | j	g W d    d S 1 sVw   Y  d S d S )NTr'  r(  )
r   rx   r)   r   r'  r   r   r   r(  r%  r   r-   r-   r.   r   B  s   "zTFGroupViTMLP.buildr  )r   r   r   r&   r%  r&   r&  r&   r   )r  r$   r   rK   r1   r$   r   r   r-   r-   r   r.   r   (  s    r   c                      s    e Zd Zdd fddZ  ZS )r   Fr   rK   c                   s&   t  jtj|ddd}tj|ddS )Nrh   rW   r  )r   r   r)   r7   )r}   r   r   r   r-   r.   r   O  s   zTFGroupViTMixerMLP.callr   )r   rK   )r   r   r   r   r   r-   r-   r   r.   r   N  s    r   c                      sL   e Zd ZdZd fddZdddZ					dd ddZd!ddZ  ZS )"r   z=Multi-headed attention from 'Attention Is All You Need' paperr   r   c                   s  t  jdi | |j| _|j| _| j| j | _| j| j | jkr.td| j d| j d|j}| jd d|j d  | }| jd | }t	
| j| _tjj| jt|dd| _tjj| jt|dd| _tjj| jt|d	d| _tjj|jd
| _tjj| jt|dd| _d S )Nz;embed_dim must be divisible by num_heads (got `embed_dim`: z and `num_heads`: r   r   rU   r   )Zunitsr   r   r   r   )r   out_projr-   )r   r   r   r   num_attention_headsattention_head_sizer   r   num_hidden_layersr2   r   sqrt_att_head_sizer   r   r   r   r   r   r   r   Zattention_dropoutr   r+  )r}   r   r   factorZin_proj_stdZout_proj_stdr   r-   r.   r   X  s6   
zTFGroupViTAttention.__init__r   r$   rb   r:   r1   c                 C  s,   t j||d| j| jfd}t j|g ddS )NrG   r   r   rU   r   r   rW   )r)   r]   r,  r-  r7   )r}   r   rb   r-   r-   r.   transpose_for_scores{  s   z(TFGroupViTAttention.transpose_for_scoresNFr  r!  ro   r"  r   Optional[bool]r   r   rK   re   c                 C  s@  t |d }|du}| j|d}	|r| j|d}
| j|d}n| j|d}
| j|d}| |	|}| |
|}| ||}tj||dd}tj| j|j	d}t
||}|dur^t||}|durht||}t|dd}| j|d}t||}tj|g d	d
}tj||d| jfd}| |}|r||f}|S |f}|S )z#Input shape: Batch x Time x Channelr   NinputsTr   r'   rG   )r0   r=   r1  rW   r   )r   r   r   r   r2  r)   ri   r*   r/  r(   divideaddr   r   r7   r]   r   r+  )r}   r  r!  r"  r   r   r   rb   Zis_cross_attentionZmixed_query_layerZmixed_key_layerZmixed_value_layerZquery_layerZ	key_layerZvalue_layerZattention_scoresZdkZ_attention_probsZattention_probsZattention_outputr#  r-   r-   r.   r     s8   
zTFGroupViTAttention.callc                 C  sb  | j rd S d| _ t| dd d ur1t| jj | jd d | jg W d    n1 s,w   Y  t| dd d urZt| jj | jd d | jg W d    n1 sUw   Y  t| dd d urt| j	j | j	d d | jg W d    n1 s~w   Y  t| dd d urt| j
j | j
d d | jg W d    d S 1 sw   Y  d S d S )NTr   r   r   r+  )r   rx   r)   r   r   r   r   r   r   r   r+  r   r-   r-   r.   r     s(   "zTFGroupViTAttention.buildr   )r   r$   rb   r:   r1   r$   NNNNF)r  r$   r!  ro   r"  ro   r   r3  r   ro   r   rK   r1   re   r   )	r   r   r   r   r   r2  r   r   r   r-   r-   r   r.   r   U  s    
#
=r   c                      6   e Zd Zd fddZ	ddddZdddZ  ZS )r  r   r   c                   sb   t  jdi | |j| _t|dd| _tjj|j	dd| _
t|dd| _tjj|j	dd| _d S )N	self_attnr   layer_norm1r   r   layer_norm2r-   )r   r   r   r   r   r:  r   r   r   r   r;  r   r   r<  r   r   r-   r.   r     s   zTFGroupViTEncoderLayer.__init__Fr  r$   r!  r"  r   rK   r   r1   re   c           	      C  sn   |}| j |d}| j|||||d}|d }|| }|}| j|d}| j|d}|| }|f|dd  }|S )a  
        Args:
            hidden_states (`tf.Tensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
            attention_mask (`tf.Tensor`): attention mask of size
                `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
            causal_attention_mask (`tf.Tensor`): causal attention mask of size
                `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
            output_attentions (`bool`):
                Whether or not to return the attentions tensors of all attention layers. See `outputs` under returned
                tensors for more detail.
        r4  )r  r!  r"  r   r   r   r*  r   N)r;  r:  r<  r   )	r}   r  r!  r"  r   r   ZresidualZattention_outputsr#  r-   r-   r.   r     s"   zTFGroupViTEncoderLayer.callNc                 C  sR  | j rd S d| _ t| dd d ur-t| jj | jd  W d    n1 s(w   Y  t| dd d urVt| jj | jd d | jg W d    n1 sQw   Y  t| dd d ur{t| j	j | j	d  W d    n1 svw   Y  t| dd d urt| j
j | j
d d | jg W d    d S 1 sw   Y  d S d S )NTr:  r;  r   r<  )r   rx   r)   r   r:  r   r   r;  r   r   r<  r   r-   r-   r.   r     s(   "zTFGroupViTEncoderLayer.buildr   r   )r  r$   r!  r$   r"  r$   r   rK   r   rK   r1   re   r   r   r-   r-   r   r.   r    s
    )r  c                      s6   e Zd Zd fddZ	ddddZdddZ  ZS )TFGroupViTTextEncoderr   r   c                   s0   t  jdi |  fddt jD | _d S )Nc                   r  r  r  r  r   r-   r.   r     r  z2TFGroupViTTextEncoder.__init__.<locals>.<listcomp>r-   )r   r   r4   r.  r   r   r   r   r.   r     s   zTFGroupViTTextEncoder.__init__Fr!  r$   r"  r   rK   output_hidden_statesreturn_dictr   r1   Union[Tuple, TFBaseModelOutput]c                 C  s   |rdnd }|r
dnd }	t | jD ] \}
}|r||f }|||||d}|d }|r1|	|d f }	q|r9||f }|sGtdd |||	fD S t|||	dS )Nr-   )r   r   r   c                 s      | ]	}|d ur|V  qd S r   r-   rz   vr-   r-   r.   r~   >      z-TFGroupViTTextEncoder.call.<locals>.<genexpr>last_hidden_stater  rQ   )	enumerater   r   r
   )r}   r  r!  r"  r   r>  r?  r   Zencoder_statesZall_attentionsidxZencoder_layerlayer_outputsr-   r-   r.   r     s,   


zTFGroupViTTextEncoder.callNc              	   C  j   | j rd S d| _ t| dd d ur1| jD ]}t|j |d  W d    n1 s+w   Y  qd S d S )NTr   )r   rx   r   r)   r   r   r   r  r-   r-   r.   r   C     
zTFGroupViTTextEncoder.buildr
  r   )r!  r$   r"  r$   r   rK   r>  rK   r?  rK   r   rK   r1   r@  r   r   r-   r-   r   r.   r=    s
    %r=  c                      s6   e Zd Zd fddZ	ddddZdddZ  ZS )TFGroupViTVisionEncoderr   r   r1   Nonec                   s4   t  jdi |  fddtt jD | _d S )Nc              
     sN   g | ]#}t   j|  j|  j| |d kr j|d  nd d| dqS )r   r   z	stages_._)r   r<   r   r   r  r   )r  depthsZnum_group_tokensZnum_output_groupsr  r   r-   r.   r   Q  s    	z4TFGroupViTVisionEncoder.__init__.<locals>.<listcomp>r-   )r   r   r4   r@   rN  stagesr   r   r   r.   r   N  s   
	z TFGroupViTVisionEncoder.__init__Fr  r$   r>  rK   r   r?  r   Union[tuple, TFBaseModelOutput]c                 C  s   |rdnd }|r
dnd }d }| j D ]&}	|r||f }|	|||}
|
d }|
d }|r7|
d d ur7||
d f }q|r?||f }|sMtdd |||fD S t|||dS )Nr-   r   r   rU   c                 s  rA  r   r-   rB  r-   r-   r.   r~   z  rD  z/TFGroupViTVisionEncoder.call.<locals>.<genexpr>rE  )rO  r   r
   )r}   r  r>  r   r?  r   Zall_hidden_statesZall_groupingsr   ZstagerI  r-   r-   r.   r   ]  s&   


zTFGroupViTVisionEncoder.callNc              	   C  rJ  )NTrO  )r   rx   rO  r)   r   r   r   r  r-   r-   r.   r     rK  zTFGroupViTVisionEncoder.build)r   r   r1   rM  r   )r  r$   r>  rK   r   rK   r?  rK   r   rK   r1   rP  r   r   r-   r-   r   r.   rL  M  s
    "rL  c                      sD   e Zd Zd fddZ	ddddZejfddZdddZ  Z	S )TFGroupViTTextTransformerr   r   c                   sV   t  jdi | t|dd| _t|dd| _tjj|j	dd| _
|j| _|j| _d S )Nr   r   encoderfinal_layer_normr   r-   )r   r   r   r   r=  rR  r   r   r   r   rS  eos_token_idr   r   r   r   r-   r.   r     s   z"TFGroupViTTextTransformer.__init__Fr   r   r!  r$   r   r   rK   r>  r?  r   r1   5Union[TFBaseModelOutputWithPooling, Tuple[tf.Tensor]]c              	   C  s  t |}| j||d}	|\}
}| j|
||	jd}t|}| j|	||||||d}|d }| j|d}| jdkrTtj	|tj
tj|d tjdtjj|ddfd	d
d}n%tj	|tj
tj|d tjdtjjtj|| jktjdddfd	d
d}|s||f|d	d   S t|||j|jdS )N)r   r   r'   )r  r!  r"  r   r>  r?  r   r   r4  rU   rG   r   r   )valuesr=   r  rF  Zpooler_outputr  rQ   )r   r   _build_causal_attention_maskr(   r/   rR  rS  rT  r)   Z	gather_ndstackr4   Zint64r2   r>   r*   Zint8r   r  rQ   )r}   r   r!  r   r   r>  r?  r   r   embedding_outputrb   
seq_lengthr"  encoder_outputsZsequence_outputpooled_outputr-   r-   r.   r     sP   


$ zTFGroupViTTextTransformer.callc                 C  sd   t t |fd|}t t ||fd|}t j|dd}t jj||d}t j||d||fdS )Nr   g     r   rG   )Zdiagonalr   )r  rO   )r)   r*   fillZlinalgZ	band_partZset_diagZbroadcast_to)r}   rb   r[  r(   ZdiagZto_maskr-   r-   r.   rX    s
   z6TFGroupViTTextTransformer._build_causal_attention_maskNc                 C     | j rd S d| _ t| dd d ur-t| jj | jd  W d    n1 s(w   Y  t| dd d urRt| jj | jd  W d    n1 sMw   Y  t| dd d ur~t| jj | jd d | j	g W d    d S 1 sww   Y  d S d S )NTr   rR  rS  )
r   rx   r)   r   r   r   r   rR  rS  r   r   r-   r-   r.   r         "zTFGroupViTTextTransformer.buildr
  r   )r   r   r!  r$   r   r$   r   rK   r>  rK   r?  rK   r   rK   r1   rU  r   )
r   r   r   r   r   r)   Zfloat32rX  r   r   r-   r-   r   r.   rQ    s    GrQ  c                      r9  )TFGroupViTVisionTransformerr   r   c                   sN   t  jdi | t|dd| _t|dd| _tjj|j	dd| _
|j| _d S )Nr   r   rR  r   r   r-   )r   r   r   r   rL  rR  r   r   r   r   r   r   r   r   r   r-   r.   r      s
   z$TFGroupViTVisionTransformer.__init__Fr   r   r   rK   r>  r?  r   r1   *Union[Tuple, TFBaseModelOutputWithPooling]c           
      C  sj   |  |}| j||||d}|d }| |}tjj|dd}	|s+||	f|dd   S t||	|j|jdS )N)r  r>  r   r?  r   r   r   rW  )	r   rR  r   r)   r2   r3   r   r  rQ   )
r}   r   r   r>  r?  r   rZ  r\  rF  r]  r-   r-   r.   r     s$   

z TFGroupViTVisionTransformer.callNc                 C  r_  )NTr   rR  r   )
r   rx   r)   r   r   r   r   rR  r   r   r   r-   r-   r.   r   )  r`  z!TFGroupViTVisionTransformer.buildr   r   )r   r   r   rK   r>  rK   r?  rK   r   rK   r1   rb  r   r   r-   r-   r   r.   ra    s
    !ra  c                      s^   e Zd ZeZd fddZd ddZd!ddZe							d"d#ddZ	d$ddZ
  ZS )%TFGroupViTTextMainLayerr   r   c                   *   t  jdi | || _t|dd| _d S )N
text_modelr   r-   )r   r   r   rQ  re  r   r   r-   r.   r   =     z TFGroupViTTextMainLayer.__init__r1   keras.layers.Layerc                 C     | j jS r   )re  r   r|   r-   r-   r.   get_input_embeddingsB     z,TFGroupViTTextMainLayer.get_input_embeddingsr   tf.Variablec                 C  s    || j j_t|d | j j_d S )Nr   )re  r   r   r   r   )r}   r   r-   r-   r.   set_input_embeddingsE  s   
z,TFGroupViTTextMainLayer.set_input_embeddingsNFr   TFModelInputType | Noner!  np.ndarray | tf.Tensor | Noner   r   r3  r>  r?  r   rK   rU  c           
   	   C  sJ   |d u rt dt|}|d u rtj|dd}| j|||||||d}	|	S )NzYou have to specify input_idsr   dimsr   r   r!  r   r   r>  r?  r   )r   r   r)   r^  re  )
r}   r   r!  r   r   r>  r?  r   r   Ztext_model_outputsr-   r-   r.   r   I  s   
zTFGroupViTTextMainLayer.callc                 C  d   | j rd S d| _ t| dd d ur0t| jj | jd  W d    d S 1 s)w   Y  d S d S )NTre  )r   rx   r)   r   re  r   r   r   r-   r-   r.   r   h     "zTFGroupViTTextMainLayer.buildr
  r1   rg  )r   rk  NNNNNNFr   rm  r!  rn  r   rn  r   r3  r>  r3  r?  r3  r   rK   r1   rU  r   )r   r   r   r   config_classr   ri  rl  r   r   r   r   r-   r-   r   r.   rc  8  s    

rc  c                      sP   e Zd ZeZd fddZdddZe									
ddddZdddZ	  Z
S )TFGroupViTVisionMainLayerr   r   c                   rd  )Nvision_modelr   r-   )r   r   r   ra  ry  r   r   r-   r.   r   v  rf  z"TFGroupViTVisionMainLayer.__init__r1   rg  c                 C  rh  r   )ry  r   r|   r-   r-   r.   ri  {  rj  z.TFGroupViTVisionMainLayer.get_input_embeddingsNFr   rm  r   r3  r>  r?  r   rK   rU  c                 C  s(   |d u rt d| j|||||d}|S )N You have to specify pixel_valuesr   r   r>  r?  r   )r   ry  )r}   r   r   r>  r?  r   Zvision_model_outputsr-   r-   r.   r   ~  s   	zTFGroupViTVisionMainLayer.callc                 C  rr  )NTry  )r   rx   r)   r   ry  r   r   r   r-   r-   r.   r     rs  zTFGroupViTVisionMainLayer.buildr   rt  r8  r   rm  r   r3  r>  r3  r?  r3  r   rK   r1   rU  r   )r   r   r   r   rw  r   ri  r   r   r   r   r-   r-   r   r.   rx  q  s    
rx  c                      s   e Zd ZeZd  fddZd!ddZe							d"d#ddZe					d$d%ddZ	e										d&d'ddZ
  ZS )(TFGroupViTMainLayerr   r   c                   s,  t  jdi | t|jtstdt|j dt|jts+tdt|j d|| _	|j}|j}|j
| _
|j| _|j| _|j| _t|dd| _t|dd| _tjj| jddtjjdd	d
dtjjddtjj| j
ddg| _tjj| jddtjjdd	d
dtjjddtjj| j
ddg| _d S )NzOconfig.text_config is expected to be of type GroupViTTextConfig but is of type .zSconfig.vision_config is expected to be of type GroupViTVisionConfig but is of type re  r   ry  zvisual_projection.0zvisual_projection.1g?gh㈵>)r   Zmomentumr   zvisual_projection.2zvisual_projection.3ztext_projection.0ztext_projection.1ztext_projection.2ztext_projection.3r-   )r   r   r   text_configr   	TypeErrortypevision_configr   r   Zprojection_dimprojection_intermediate_dimr   text_embed_dimvision_embed_dimrQ  re  ra  ry  r   r   r   ZBatchNormalizationZReLUvisual_projectiontext_projection)r}   r   r   r  r  r   r-   r.   r     s@   
zTFGroupViTMainLayer.__init__Nc                 C  s  | j dtj| jjddd| _| jrd S d| _t| dd d ur=t	
| jj | jd  W d    n1 s8w   Y  t| dd d urbt	
| jj | jd  W d    n1 s]w   Y  t| dd d urt	
| jd j | jd d d d | jg W d    n1 sw   Y  t	
| jd	 j | jd	 d | jf W d    n1 sw   Y  t	
| jd
 j | jd
 d d d | jg W d    n1 sw   Y  t| dd d urYt	
| jd j | jd d d d | jg W d    n	1 sw   Y  t	
| jd	 j | jd	 d | jf W d    n	1 s*w   Y  t	
| jd
 j | jd
 d d d | jg W d    d S 1 sRw   Y  d S d S )N)r   Tlogit_scaler   re  ry  r  r   r   r   r  )r   r   ZinitializersConstantr   Zlogit_scale_init_valuer  r   rx   r)   r   re  r   r   ry  r  r  r  r  r  r   r-   r-   r.   r     sL   $zTFGroupViTMainLayer.buildFr   rm  r!  rn  r   r   r3  r>  r?  r   rK   r1   r$   c              	   C  sj   |d u rt dt|}|d u rtj|dd}| j|||||||d}	|	d }
| jD ]}||
}
q*|
}|S )N$You have to specify either input_idsr   ro  rq  )r   r   r)   r^  re  r  )r}   r   r!  r   r   r>  r?  r   r   text_outputsr]  r  text_featuresr-   r-   r.   get_text_features  s&   


z%TFGroupViTMainLayer.get_text_featuresr   c           
      C  sH   |d u rt d| j|||||d}|d }| jD ]}||}q|}	|	S )Nrz  r{  r   )r   ry  r  )
r}   r   r   r>  r?  r   vision_outputsr]  r  image_featuresr-   r-   r.   get_image_features  s   	

z&TFGroupViTMainLayer.get_image_featuresreturn_lossoutput_segmentation.Union[TFGroupViTModelOutput, Tuple[tf.Tensor]]c              
   C  s  |d u rt d|d u rt dt|}|d u rtj|dd}|r#d}| j||||	|
d}| j||||||	|
d}|d }| jD ]}||}q@|d }| jD ]}||}qN|tj|ddd	 }|tj|ddd	 }tj	
| j}tj||dd
| }t|}d }|r|d }tj|dt|d fd}| jD ]}||}q|r|d }n|d }t||jdd  }|tj|dddd }tj||dd
| }tj||jd d|jd fd}tj|dd}tj|t|d t|d dfd}t||| }tj||jd |jd |jd |jd fd}d }|rt|d }|	sB|d ur.|||||||f}n||||||f}|d ur@|f| S |S t||||||||dS )Nr  rz  r   ro  Tr{  rq  rG   r   r   r   r   r   rU   Z	euclidean)r   ordr=   r   rh   rW   )N.)rn   rp   rq   rr   rs   rt   ru   rv   )r   r   r)   r^  ry  re  r  r  Znormr2   expr  ri   r7   r]   rk   rO   r8   rl   )r}   r   r   r!  r   r  r   r>  r  r?  r   r   r  r  rt   r  rs   r  rq   rp   Z
seg_logitsZimage_group_embedsrQ   groupingZlogits_per_image_groupZflatten_groupingrn   outputr-   r-   r.   r   *  s   








$$

zTFGroupViTMainLayer.callr   r   ru  r   rm  r!  rn  r   rn  r   r3  r>  r3  r?  r3  r   rK   r1   r$   r8  r   rm  r   r3  r>  r3  r?  r3  r   rK   r1   r$   
NNNNNNNNNFr   rm  r   rm  r!  rn  r   rn  r  r3  r   r3  r>  r3  r  r3  r?  r3  r   rK   r1   r  )r   r   r   r   rw  r   r   r   r  r  r   r   r-   r-   r   r.   r}    s@    
) #r}  c                   @  s   e Zd ZdZeZdZdS )TFGroupViTPreTrainedModelz
    An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
    models.
    groupvitN)r   r   r   r   r   rw  Zbase_model_prefixr-   r-   r-   r.   r    s    r  aB  
    This model inherits from [`TFPreTrainedModel`]. Check the superclass documentation for the generic methods the
    library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
    etc.)

    This model is also a [keras.Model](https://www.tensorflow.org/api_docs/python/tf/keras/Model) subclass. Use it
    as a regular TF 2.0 Keras Model and refer to the TF 2.0 documentation for all matter related to general usage and
    behavior.

    <Tip>

    TF 2.0 models accepts two formats as inputs:

    - having all inputs as keyword arguments (like PyTorch models), or
    - having all inputs as a list, tuple or dict in the first positional arguments.

    This second option is useful when using [`keras.Model.fit`] method which currently requires having all the
    tensors in the first argument of the model call function: `model(inputs)`.

    If you choose this second option, there are three possibilities you can use to gather all the input Tensors in the
    first positional argument :

    - a single Tensor with `input_ids` only and nothing else: `model(input_ids)`
    - a list of varying length with one or several input Tensors IN THE ORDER given in the docstring:
      `model([input_ids, attention_mask])` or `model([input_ids, attention_mask, token_type_ids])`
    - a dictionary with one or several input Tensors associated to the input names given in the docstring:
      `model({"input_ids": input_ids, "token_type_ids": token_type_ids})`

    </Tip>

    Args:
        config ([`GroupViTConfig`]): Model configuration class with all the parameters of the model.
            Initializing with a config file does not load the weights associated with the model, only the
            configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
a  
    Args:
        input_ids (`np.ndarray`, `tf.Tensor`, `List[tf.Tensor]` ``Dict[str, tf.Tensor]` or `Dict[str, np.ndarray]` and each example must have the shape `({0})`):
            Indices of input sequence tokens in the vocabulary.

            Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.__call__`] and
            [`PreTrainedTokenizer.encode`] for details.

            [What are input IDs?](../glossary#input-ids)
        attention_mask (`np.ndarray` or `tf.Tensor` of shape `({0})`, *optional*):
            Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:

            - 1 for tokens that are **not masked**,
            - 0 for tokens that are **masked**.

            [What are attention masks?](../glossary#attention-mask)
        position_ids (`np.ndarray` or `tf.Tensor` of shape `({0})`, *optional*):
            Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
            config.max_position_embeddings - 1]`.

            [What are position IDs?](../glossary#position-ids)
        output_attentions (`bool`, *optional*):
            Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
            tensors for more detail. This argument can be used only in eager mode, in graph mode the value in the
            config will be used instead.
        output_hidden_states (`bool`, *optional*):
            Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
            more detail. This argument can be used only in eager mode, in graph mode the value in the config will be
            used instead.
        return_dict (`bool`, *optional*):
            Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple. This argument can be used in
            eager mode, in graph mode the value will always be set to True.
        training (`bool`, *optional*, defaults to `False``):
            Whether or not to use the model in training mode (some modules like dropout modules have different
            behaviors between training and evaluation).
a  
    Args:
        pixel_values (`np.ndarray`, `tf.Tensor`, `List[tf.Tensor]`, `Dict[str, tf.Tensor]` or `Dict[str, np.ndarray]` and each example must have the shape `(batch_size, num_channels, height, width)`):
            Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See
            [`CLIPImageProcessor.__call__`] for details.
        output_attentions (`bool`, *optional*):
            Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
            tensors for more detail. This argument can be used only in eager mode, in graph mode the value in the
            config will be used instead.
        output_hidden_states (`bool`, *optional*):
            Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
            more detail. This argument can be used only in eager mode, in graph mode the value in the config will be
            used instead.
        return_dict (`bool`, *optional*):
            Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple. This argument can be used in
            eager mode, in graph mode the value will always be set to True.
        training (`bool`, *optional*, defaults to `False``):
            Whether or not to use the model in training mode (some modules like dropout modules have different
            behaviors between training and evaluation).
al
  
    Args:
        input_ids (`np.ndarray`, `tf.Tensor`, `List[tf.Tensor]` ``Dict[str, tf.Tensor]` or `Dict[str, np.ndarray]` and each example must have the shape `({0})`):
            Indices of input sequence tokens in the vocabulary.

            Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.__call__`] and
            [`PreTrainedTokenizer.encode`] for details.

            [What are input IDs?](../glossary#input-ids)
        pixel_values (`np.ndarray`, `tf.Tensor`, `List[tf.Tensor]` `Dict[str, tf.Tensor]` or `Dict[str, np.ndarray]` and each example must have the shape `(batch_size, num_channels, height, width)`):
            Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See
            [`CLIPImageProcessor.__call__`] for details.
        attention_mask (`np.ndarray` or `tf.Tensor` of shape `({0})`, *optional*):
            Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:

            - 1 for tokens that are **not masked**,
            - 0 for tokens that are **masked**.

            [What are attention masks?](../glossary#attention-mask)
        position_ids (`np.ndarray` or `tf.Tensor` of shape `({0})`, *optional*):
            Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
            config.max_position_embeddings - 1]`.

            [What are position IDs?](../glossary#position-ids)
        return_loss (`bool`, *optional*):
            Whether or not to return the contrastive loss.
        output_attentions (`bool`, *optional*):
            Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
            tensors for more detail. This argument can be used only in eager mode, in graph mode the value in the
            config will be used instead.
        output_hidden_states (`bool`, *optional*):
            Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
            more detail. This argument can be used only in eager mode, in graph mode the value in the config will be
            used instead.
        return_dict (`bool`, *optional*):
            Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple. This argument can be used in
            eager mode, in graph mode the value will always be set to True.
        training (`bool`, *optional*, defaults to `False``):
            Whether or not to use the model in training mode (some modules like dropout modules have different
            behaviors between training and evaluation).
c                      sh   e Zd ZeZdZd fddZeee	
deeed								ddddZdddZ  ZS )TFGroupViTTextModelr   r   r   c                   ,   t  j|g|R i | t|dd| _d S Nr  r   )r   r   rc  r  r}   r   r5  r   r   r-   r.   r   A     zTFGroupViTTextModel.__init__batch_size, sequence_lengthoutput_typerw  NFrm  r!  rn  r   r   r3  r>  r?  r   rK   r1   rU  c           	   	   C  s   | j |||||||d}|S )aO  
        Returns:

        Examples:

        ```python
        >>> from transformers import CLIPTokenizer, TFGroupViTTextModel

        >>> tokenizer = CLIPTokenizer.from_pretrained("nvidia/groupvit-gcc-yfcc")
        >>> model = TFGroupViTTextModel.from_pretrained("nvidia/groupvit-gcc-yfcc")

        >>> inputs = tokenizer(["a photo of a cat", "a photo of a dog"], padding=True, return_tensors="tf")

        >>> outputs = model(**inputs)
        >>> last_hidden_state = outputs.last_hidden_state
        >>> pooled_output = outputs.pooler_output  # pooled (EOS token) states
        ```rq  r  )	r}   r   r!  r   r   r>  r?  r   r#  r-   r-   r.   r   F  s   
zTFGroupViTTextModel.callc                 C  rr  NTr  r   rx   r)   r   r  r   r   r   r-   r-   r.   r   q  rs  zTFGroupViTTextModel.buildr
  ru  rv  r   )r   r   r   r   rw  main_input_namer   r   r   GROUPVIT_TEXT_INPUTS_DOCSTRINGformatr   r   r   r   r   r-   r-   r   r.   r  =  s     
(r  c                      s^   e Zd ZeZdZd fddZeee	e
eed					ddddZdddZ  ZS )TFGroupViTVisionModelr   r   r   c                   r  r  )r   r   rx  r  r  r   r-   r.   r   ~  r  zTFGroupViTVisionModel.__init__r  NFrm  r   r3  r>  r?  r   rK   r1   rU  c                 C  s   | j |||||d}|S )a  
        Returns:

        Examples:

        ```python
        >>> from PIL import Image
        >>> import requests
        >>> from transformers import AutoProcessor, TFGroupViTVisionModel

        >>> processor = AutoProcessor.from_pretrained("nvidia/groupvit-gcc-yfcc")
        >>> model = TFGroupViTVisionModel.from_pretrained("nvidia/groupvit-gcc-yfcc")

        >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
        >>> image = Image.open(requests.get(url, stream=True).raw)

        >>> inputs = processor(images=image, return_tensors="tf")

        >>> outputs = model(**inputs)
        >>> last_hidden_state = outputs.last_hidden_state
        >>> pooled_output = outputs.pooler_output  # pooled CLS states
        ```r{  r  )r}   r   r   r>  r?  r   r#  r-   r-   r.   r     s   "zTFGroupViTVisionModel.callc                 C  rr  r  r  r   r-   r-   r.   r     rs  zTFGroupViTVisionModel.buildr   r8  r|  r   )r   r   r   r   rw  r  r   r   r    GROUPVIT_VISION_INPUTS_DOCSTRINGr   r   r   r   r   r-   r-   r   r.   r  z  s    
)r  c                      s   e Zd ZeZd& fddZeee	d							d'd(ddZ
eee					d)d*ddZeee	deeed										d+d,ddZd-d"d#Zd.d$d%Z  ZS )/TFGroupViTModelr   r   c                   r  r  )r   r   r}  r  r  r   r-   r.   r     r  zTFGroupViTModel.__init__r  NFr   rm  r!  rn  r   r   r3  r>  r?  r   rK   r1   r$   c           	   	   C  s   | j j|||||||d}|S )a  
        Returns:
            text_features (`tf.Tensor` of shape `(batch_size, output_dim`): The text embeddings obtained by applying
            the projection layer to the pooled output of [`TFGroupViTTextModel`].

        Examples:

        ```python
        >>> from transformers import CLIPTokenizer, TFGroupViTModel

        >>> model = TFGroupViTModel.from_pretrained("nvidia/groupvit-gcc-yfcc")
        >>> tokenizer = CLIPTokenizer.from_pretrained("nvidia/groupvit-gcc-yfcc")

        >>> inputs = tokenizer(["a photo of a cat", "a photo of a dog"], padding=True, return_tensors="tf")
        >>> text_features = model.get_text_features(**inputs)
        ```rq  )r  r  )	r}   r   r!  r   r   r>  r?  r   r  r-   r-   r.   r    s   
z!TFGroupViTModel.get_text_featuresr   c                 C  s   | j j|||||d}|S )aF  
        Returns:
            image_features (`tf.Tensor` of shape `(batch_size, output_dim`): The image embeddings obtained by applying
            the projection layer to the pooled output of [`TFGroupViTVisionModel`].

        Examples:

        ```python
        >>> from PIL import Image
        >>> import requests
        >>> from transformers import AutoProcessor, TFGroupViTModel

        >>> model = TFGroupViTModel.from_pretrained("nvidia/groupvit-gcc-yfcc")
        >>> processor = AutoProcessor.from_pretrained("nvidia/groupvit-gcc-yfcc")

        >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
        >>> image = Image.open(requests.get(url, stream=True).raw)

        >>> inputs = processor(images=image, return_tensors="tf")

        >>> image_features = model.get_image_features(**inputs)
        ```r{  )r  r  )r}   r   r   r>  r?  r   r  r-   r-   r.   r    s   !z"TFGroupViTModel.get_image_featuresr  r  r  r  c                 C  s"   | j |||||||||	|
d
}|S )a  
        Returns:

        Examples:

        ```python
        >>> from PIL import Image
        >>> import requests
        >>> from transformers import AutoProcessor, TFGroupViTModel
        >>> import tensorflow as tf

        >>> model = TFGroupViTModel.from_pretrained("nvidia/groupvit-gcc-yfcc")
        >>> processor = AutoProcessor.from_pretrained("nvidia/groupvit-gcc-yfcc")

        >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
        >>> image = Image.open(requests.get(url, stream=True).raw)

        >>> inputs = processor(
        ...     text=["a photo of a cat", "a photo of a dog"], images=image, return_tensors="tf", padding=True
        ... )

        >>> outputs = model(**inputs)
        >>> logits_per_image = outputs.logits_per_image  # this is the image-text similarity score
        >>> probs = tf.math.softmax(logits_per_image, axis=1)  # we can take the softmax to get the label probabilities
        ```)
r   r   r!  r   r  r   r>  r  r?  r   r  )r}   r   r   r!  r   r  r   r>  r  r?  r   r#  r-   r-   r.   r     s   *zTFGroupViTModel.callr  rl   c                 C  s   |S r   r-   )r}   r  r-   r-   r.   serving_outputN  s   zTFGroupViTModel.serving_outputc                 C  rr  r  r  r   r-   r-   r.   r   T  rs  zTFGroupViTModel.buildr   ru  r  r8  r  r  r  )r  rl   r1   rl   r   )r   r   r   r   rw  r   r   r   r  r  r  r  r  GROUPVIT_INPUTS_DOCSTRINGr   rl   r   r  r   r   r-   r-   r   r.   r    sJ    ')

6r  )r  r  r  r  r   )r#   r$   r%   r&   )r0   r$   r1   r$   )r6   r$   r1   r$   )r0   r$   r9   r:   r1   r$   )r   FrG   )
r0   r$   rH   rI   rJ   rK   r9   r:   r1   r$   r   )
rQ   r$   rR   r:   rS   r:   rT   rK   r1   r$   )rQ   re   rf   rg   r1   r$   )]r   
__future__r   collections.abcr   r2   dataclassesr   typingr   r   r   r   numpyr[   Z
tensorflowr)   Zactivations_tfr	   Zmodeling_tf_outputsr
   r   Zmodeling_tf_utilsr   r   r   r   r   r   Ztf_utilsr   r   r   utilsr   r   r   r   r   r   Zconfiguration_groupvitr   r   r   Z
get_loggerr   loggerZtensorflow_probabilityrL   rM   ZNormalr   ImportErrorerrorZ_CHECKPOINT_FOR_DOCr,   r/   r5   r8   rF   rP   rd   rk   rl   r   ZLayerr   r   r   r   r   r   r  r   r   r   r  r=  rL  rQ  ra  rc  rx  r}  r  ZGROUPVIT_START_DOCSTRINGr  r  r  r  r  r  __all__r-   r-   r-   r.   <module>   s     


	

&2"BXOR: &}F5=u97*  
$%+=> %