
    sg_                       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&jX                  e-      Z. e%       r#	 ddl/Z0e0jb                  je                  dd      Z3n"	 ddl/Z0e0jb                  je                  dd      Z3dZ6dZ7dMdNdZ8dOdZ9dPdZ:dQdZ;dRdSdZ<dTdUdZ=dVdZ>e G d de"             Z? G d dej                  j                        ZB G d d ej                  j                        ZC G d! d"ej                  j                        ZD G d# d$ej                  j                        ZE G d% d&ej                  j                        ZF G d' d(ej                  j                        ZG G d) d*ej                  j                        ZH G d+ d,ej                  j                        ZI G d- d.eI      ZJ G d/ d0ej                  j                        ZK G d1 d2ej                  j                        ZL G d3 d4ej                  j                        ZM G d5 d6ej                  j                        ZN G d7 d8ej                  j                        ZO G d9 d:ej                  j                        ZPe G d; d<ej                  j                               ZQe G d= d>ej                  j                               ZRe G d? d@ej                  j                               ZS G dA dBe      ZTdCZUdDZVdEZWdFZX G dG dHeT      ZY G dI dJeT      ZZ e#eU       G dK dLeT             Z[y# e4$ r e.jk                  d       Y w xY w# e4$ r Y w xY w)Wz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    חc                    t        |       d   }||n|}t        j                  d      }t        j                  | |j                        } t        j
                  | ddddddf   dd|df      }||z
  t        z  S )z_
    Expands attention_mask from `[bsz, seq_len]` to `[bsz, 1, tgt_seq_len, src_seq_len]`.
    r   Nr!   dtype)r   tfconstantcastr&   tileLARGE_NEGATIVE)masktgt_lensrc_lenone_cstexpanded_masks        d/var/www/html/venv/lib/python3.12/site-packages/transformers/models/groupvit/modeling_tf_groupvit.py_expand_maskr2   R   sx     q!G ,g'Gkk#G774w}}-DGGDD$!12Q7A4FGMm#~55    c           	         t         j                  j                  t        j                  j                  t        j                  t        |       d         | d            S )Nr   T)y_truey_predfrom_logits)r'   mathreduce_meanr   metricssparse_categorical_crossentropyranger   )logitss    r1   contrastive_lossr>   a   sJ    775588Jv.q126t 	6 	
 r3   c                d    t        |       }t        t        j                  |             }||z   dz  S )Ng       @)r>   r'   	transpose)
similaritycaption_loss
image_losss      r1   groupvit_lossrD   j   s/    #J/L!",,z":;J:%,,r3   c                   t        | |      }t        j                  ||      }t        j                  |t	        |       |   t        t        t	        |                   |   |j                        }|t        j                  |      z
  |z   }|S )Ndepthaxisr&   )	r   r'   argmaxone_hotr   r<   lenr&   stop_gradient)r=   dimy_softindexy_hardrets         r1   hard_softmaxrR   p   s}    FC(FIIfc"EZZ % 3z&)*+C0llF 2##F+
+f
4CJr3   c                   t         j                  j                  dd      }|j                  t	        j
                  |       | j                        }| |z   |z  }t        ||      }|rt	        j                  ||      }t	        j                  |t        |       |   t        t        t        |                   |   |j                        }|t	        j                  |      z
  |z   }	|	S |}	|	S )Nr    r!   r%   rF   )tfpdistributionsGumbelsampler'   shaper&   r   rI   rJ   r   r<   rK   rL   )
r=   tauhardrM   gumbel_distgumbelsrN   rO   rP   rQ   s
             r1   gumbel_softmaxr]      s    ##**34K  &!1 FG3&GGS)F		&#&V$S) s:f-./4,,
 r''//&8 J Jr3   c                   ||z  | j                   d   z  dz  }||kD  r3t        t        j                  ||z              }t	        |       d   |z  }n2t        t        j                  ||z              }t	        |       d   |z  }t	        |       d   }t	        |       d   }t        j                  | ||||f      } t        j                  | d      } |r:t
        j                  j                  j                  j                  | ||fd|      } n$t
        j                  j                  | ||fd	      } t        j                  | 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   r_   r	   r   permbilinear)sizemethodalign_corners)rd   re   )r   r	   r   r_   )rX   intnproundr   r'   reshaper@   compatv1imageresize)	
attentionsheightwidthrf   r#   
feat_widthfeat_height
batch_sizegroupss	            r1   resize_attention_maprv      s0    e^z//22s:E~%%-01
 ,Q/:="((6E>23
+A.+=
J'*J
#A&FJV[*(UVJj|<JYY\\''..%'	 / 

 XX__Zvuoj_Y
j|<Jr3   c                   g }d}| D ]f  }t        j                  |d      }||}nt        j                  ||      }t        t        j                  |d      g| }|j	                  |       h |d   }t        j
                  |      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   r_   r   ra   )r'   r@   matmulrv   appendrL   )ro   hw_shape	attn_mapsprev_attn_masks
attn_maskscur_attn_mapfinal_groupings          r1   get_grouping_from_attentionsr      s     IO  	'
\\*9=
"(O iiDO+BLLy,Ye\de&	' r]NN++r3   c                      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Zy)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	tf.Tensorlogits_per_imagelogits_per_textsegmentation_logitstext_embedsimage_embedsr   text_model_outputvision_model_outputc                H     t         fd j                         D              S )Nc              3  d   K   | ]'  }|d vr|   nt        |      j                          ) yw))r   r   N)getattrto_tuple).0kselfs     r1   	<genexpr>z1TFGroupViTModelOutput.to_tuple.<locals>.<genexpr>	  s=      
  LLDGRYZ^`aRbRkRkRmm
s   -0)tuplekeysr   s   `r1   r   zTFGroupViTModelOutput.to_tuple  s#     
YY[
 
 	
r3   )returnz
Tuple[Any])__name__
__module____qualname____doc__r   __annotations__r   r   r   r   r   r   r   r    r3   r1   r   r      sf    B "D
!"&i&!%OY%%))!K!"L)"6:3:8<5<
r3   r   c                  2     e Zd Zd fdZdddZddZ xZS )TFGroupViTCrossAttentionLayerc                :   t        |   di | t        |d      | _        t        j
                  j                  |j                  d      | _        t        |d      | _
        t        j
                  j                  |j                  d      | _        || _        y )Nattnnamenorm2epsilonr   mlp	norm_postr   )super__init__TFGroupViTAttentionr   r   layersLayerNormalizationlayer_norm_epsr   TFGroupViTMLPr   r   configr   r   kwargs	__class__s      r1   r   z&TFGroupViTCrossAttentionLayer.__init__  sz    "6"'V<	\\44V=R=RY`4a
 e488AVAV]h8ir3   c                    |}|| j                  ||      d   z   }|| j                  | j                  |            z   }| j                  |      }|S )N)encoder_hidden_statesr   )r   r   r   r   )r   querykeytrainingxs        r1   callz"TFGroupViTCrossAttentionLayer.call  sQ    		%s	;A>>A''NN1r3   c                   | j                   ry d| _         t        | dd       Mt        j                  | j                  j
                        5  | j                  j                  d        d d d        t        | dd       dt        j                  | j                  j
                        5  | j                  j                  d d | j                  j                  g       d d d        t        | dd       Mt        j                  | j                  j
                        5  | j                  j                  d        d d d        t        | dd       et        j                  | j                  j
                        5  | j                  j                  d d | j                  j                  g       d d d        y y # 1 sw Y   HxY w# 1 sw Y   xY w# 1 sw Y   xY w# 1 sw Y   y xY w)NTr   r   r   r   )builtr   r'   
name_scoper   r   buildr   r   hidden_sizer   r   r   input_shapes     r1   r   z#TFGroupViTCrossAttentionLayer.build  sn   ::
4&2tyy~~. &		%&4$'3tzz/ H

  $dkk.E.E!FGH4%1txx}}- %t$%4d+7t~~223 L$$dD$++2I2I%JKL L 8& &H H% %L Ls0   F-%3F:G03G-F7:GGGr   r   F)r   r   r   r   r   boolr   r   Nr   r   r   r   r   r   __classcell__r   s   @r1   r   r     s    Lr3   r   c                  <     e Zd Zd fdZdddZdd	dZd
dZ xZS )TFGroupViTAssignAttentionc                   t        |   di | |j                  dz  | _        t        j
                  j                  |j                  d      | _        t        j
                  j                  |j                  d      | _        t        j
                  j                  |j                  d      | _	        t        j
                  j                  |j                  d      | _
        |j                  | _        || _        y )N      q_projr   k_projv_projprojr   )r   r   r   r#   r   r   Denser   r   r   r   
assign_epsr   r   s      r1   r   z"TFGroupViTAssignAttention.__init__2  s    "6"''-
ll((););((Kll((););((Kll((););((KLL&&v'9'9&G	 ++r3   c                j    |r|rt        |d|      }|S |rt        |d      }|S t        |d      }|S )N)rM   rZ   )rM   rH   )r]   rR   r   )r   r   gumbelrZ   r   s        r1   get_attnz"TFGroupViTAssignAttention.get_attn=  sG    h!$BT:D  #Db1  &d4r3   c                   |}| j                  |      }| j                  |      }| j                  |      }t        j                  ||d      | j
                  z  }| j                  ||      }| j                  ||dd      }|t        j                  j                  |dd      | j                  z   z  }t        j                  ||      }| j                  |      }||fS )NTtranspose_b)r   F)r   r   rZ   ry   rH   keepdims)r   r   r   r'   rz   r#   r   r8   
reduce_sumr   r   )	r   r   r   r   valueraw_attnr   	soft_attnouts	            r1   r   zTFGroupViTAssignAttention.callH  s    E" kk# E" 99UCT:TZZG}}X}9MM(XeRWMX	rww))$R$)G$//YZiie$iinI~r3   c                   | j                   ry d| _         t        | dd       dt        j                  | j                  j
                        5  | j                  j                  d d | j                  j                  g       d d d        t        | dd       dt        j                  | j                  j
                        5  | j                  j                  d d | j                  j                  g       d d d        t        | dd       dt        j                  | j                  j
                        5  | j                  j                  d d | j                  j                  g       d d d        t        | dd       et        j                  | j                  j
                        5  | j                  j                  d d | j                  j                  g       d d d        y y # 1 sw Y   _xY w# 1 sw Y   xY w# 1 sw Y   xY w# 1 sw Y   y xY w)NTr   r   r   r   )r   r   r'   r   r   r   r   r   r   r   r   r   r   s     r1   r   zTFGroupViTAssignAttention.builda  s   ::
44(4t{{//0 I!!4t{{/F/F"GHI44(4t{{//0 I!!4t{{/F/F"GHI44(4t{{//0 I!!4t{{/F/F"GHI4&2tyy~~. G		tT[[-D-D EFG G 3I II II IG Gs0   3G<3G(-3G43H G%(G14G= H	r   )TTF)
r   r   r   r   rZ   r   r   r   r   r   r   )r   r   r   r   r   r   r   )r   r   r   r   r   r   r   r   r   s   @r1   r   r   1  s    		2Gr3   r   c                  :     e Zd Zd fdZddZdddZd	dZ xZS )
TFGroupViTTokenAssignc                   t        	|   di | || _        t        j                  j                  |j                  d      | _        t        |j                  t        j                  j                        r|j                  n|j                  |j                  f}|D cg c]  }t        ||j                  z         c}\  }}t        ||||d      | _        t        j                  j                  |j                  d      | _        t        j                  j                  |j                  d      | _        t'        |d      | _        t+        |d      | _        t        j                  j                  |j                  d	      | _        t1        ||j                  ||j                  d
      | _        || _        y c c}w )Nnorm_tokensr   	mlp_interr   norm_post_tokensnorm_xpre_assign_attnassign
norm_new_xmlp_channelsr   )r   r   num_output_groupr   r   r   r   r   
isinstanceassign_mlp_ratiocollectionsabcIterablerg   r   TFGroupViTMixerMLPr   r   r   r   r   r   r   r   r   r   r   )
r   r   num_group_tokenr   r   r   r   
tokens_dimchannels_dimr   s
            r1   r   zTFGroupViTTokenAssign.__init__t  su   "6" 0 <<::6CXCX_l:m &11;??3K3KL ##))6+B+BC 	
 JZ#ZACF,>,>(>$?#Z 
L+FOZQahst % ? ?H]H]dv ? wll55f>S>SZb5c<VJ[\/XF,,99&BWBW^j9k)F&&f6H6H~
  $[s   F=c                J    | j                  |      }| j                  |      }|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   group_tokensprojected_group_tokenss      r1   project_group_tokenz)TFGroupViTTokenAssign.project_group_token  s+     "&!=!%!6!67M!N%%r3   c                   | j                  |      }| j                  |      }| j                  |      }| j                  ||      }| j	                  ||      \  }}||z  }|| j                  | j                  |            z   }||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   image_tokensr   r   r   new_image_tokens	attentions          r1   r   zTFGroupViTTokenAssign.call  s     ''5{{<0!%!9!9,!G!%!5!56Ll![&*kk2H,&W#)22+d.?.?P`@a.bb**r3   c                R   | j                   ry d| _         t        | dd       dt        j                  | j                  j
                        5  | j                  j                  d d | j                  j                  g       d d d        t        | dd       Mt        j                  | j                  j
                        5  | j                  j                  d        d d d        t        | dd       dt        j                  | j                  j
                        5  | j                  j                  d d | j                  j                  g       d d d        t        | dd       dt        j                  | j                  j
                        5  | j                  j                  d d | j                  j                  g       d d d        t        | dd       Mt        j                  | j                  j
                        5  | j                  j                  d        d d d        t        | dd       Mt        j                  | j                  j
                        5  | j                  j                  d        d d d        t        | dd       dt        j                  | j                  j
                        5  | j                  j                  d d | j                  j                  g       d d d        t        | d	d       Nt        j                  | j                  j
                        5  | j                  j                  d        d d d        y y # 1 sw Y   xY w# 1 sw Y   zxY w# 1 sw Y   xY w# 1 sw Y   xY w# 1 sw Y   exY w# 1 sw Y   xY w# 1 sw Y   xY w# 1 sw Y   y xY w)
NTr   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     r1   r   zTFGroupViTTokenAssign.build  s   ::
4-9t//445 N  &&dDKK4K4K'LMN4d+7t~~223 +$$T*+4+T2>t4499: S%%++T49P9P,QRS44(4t{{//0 I!!4t{{/F/F"GHI4*D1=t33889 1$$**40144(4t{{//0 (!!$'(4t,8t334 M%%tT4;;3J3J&KLM4.:t00556 .!!''-. . ;)N N+ +S SI I1 1( (M M. .s`   3M<M3M3M*8M7N,3NNMMM'*M47NNNN&)r   r   r   rg   r   rg   )r   r   r   r   r   )r   r   r   r   r   r   r   )r   r   r   r   r   r   r   r   r   s   @r1   r   r   s  s    0&+&.r3   r   c                  F     e Zd ZdZd fdZ	 d	 	 	 	 	 	 	 ddZddZ x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.
    c                R   t        |   d	i | |j                  |j                  }}|j                  }|j
                  | _        t        |t        j                  j                        r|n||f}t        |t        j                  j                        r|n||f}|d   |d   z  |d   |d   z  z  }|| _        || _        || _
        || _        || _        t        j                  j                  | j
                  ||dddt        | j                  j                         dd	      | _        y )
Nr   r   validchannels_lastTzeros
projection)	filterskernel_sizestridespaddingdata_formatuse_biaskernel_initializerbias_initializerr   r   )r   r   
image_size
patch_sizenum_channelsr   r   r   r   r   num_patchesr   r   r   Conv2Dr   initializer_ranger
  )r   r   r   r  r  r  r  r   s          r1   r   z"TFGroupViTPatchEmbeddings.__init__  s   "6"!'!2!2F4E4EJ
**!--#-j+//:R:R#SZZdfpYq
#-j+//:R:R#SZZdfpYq
!!}
15*Q-:VW=:XY$$&(,,--$$"'.t{{/L/LM$ . 

r3   c                <   t        |      \  }}}}t        j                         r|| j                  k7  rt	        d      |sjt        j                         rV|| j
                  d   k7  s|| j
                  d   k7  r2t	        d| d| d| j
                  d    d| j
                  d    d	      t        j                  |d	      }| j                  |      }|| j                  d   z  || j                  d   z  z  }	t        j                  |||	| j                  f
      }
|
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 ().r`   ra   tensorrX   )r   r'   executing_eagerlyr  
ValueErrorr  r@   r
  r  rj   r   )r   pixel_valuesinterpolate_pos_encodingr   rt   r  rp   rq   r
  r  
embeddingss              r1   r   zTFGroupViTPatchEmbeddings.call  s(    3=\2J/
L&%!ld6G6G&Gw  )$$&4??1--$//!:L1L$VHAeW4KDOO\]L^K__`aeapapqras`ttvw  ||L|D__\2
  22vQRAS7ST ZZz*kSWScSc9de
r3   c                   | j                   ry d| _         t        | dd       \t        j                  | j                  j
                        5  | j                  j                  d d d | j                  g       d d d        y y # 1 sw Y   y xY w)NTr
  )r   r   r'   r   r
  r   r   r  r   s     r1   r   zTFGroupViTPatchEmbeddings.build  s}    ::
4t,8t334 M%%tT49J9J&KLM M 9M Ms   *A??Br   r   FFr   r   r!  r   r   r   r   r   r   )r   r   r   r   r   r   r   r   r   s   @r1   r  r    s@    
: af % AE Y] 	 DMr3   r  c                  N     e Zd ZdZd fdZddZddZ	 d		 	 	 	 	 	 	 d
dZ xZS )TFGroupViTVisionEmbeddingsz7
    Construct the position and patch embeddings.

    c                   t        |   di | t        |d      | _        t        j
                  j                  |j                  d      | _        t        j
                  j                  |j                  d      | _
        || _        y )Npatch_embeddingsr   dropout)rater   	layernormr   r   )r   r   r  r*  r   r   Dropoutr+  r   r   r-  r   r   s      r1   r   z#TFGroupViTVisionEmbeddings.__init__   sk    "6" 9&GY Z||++i+P88AVAV]h8ir3   c                N   | j                   j                  }| j                  d|| j                  j                  fddd      | _        | j                  ry d| _        t        | dd       Mt        j                  | j                   j                        5  | j                   j                  d        d d d        t        | dd       Mt        j                  | j                  j                        5  | j                  j                  d        d d d        t        | dd       et        j                  | j                  j                        5  | j                  j                  d d | j                  j                  g       d d d        y y # 1 sw Y   xY w# 1 sw Y   xY w# 1 sw Y   y xY w)	Nr   r	  Tposition_embeddingsrX   initializer	trainabler   r*  r+  r-  )r*  r  
add_weightr   r   r0  r   r   r'   r   r   r   r+  r-  )r   r   r  s      r1   r   z TFGroupViTVisionEmbeddings.build(  sb   ++77#'??k4;;#:#:;&	 $3 $
  ::
4+T2>t4499: 2%%++D124D)5t||001 )""4()4d+7t~~223 L$$dD$++2I2I%JKL L 82 2) )L Ls$   F,F3FFFF$c                   t        |      \  }}}t        | j                        d   }||k(  r||k(  r| j                  S | j                  }|| j                  j                  z  }	|| j                  j                  z  }
t        j
                  j                  t	        j                  |dt        t        j                  |            t        t        j                  |            |f      |	|
fd      }t	        j                  |dd|f      }|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   rX   bicubic)imagesrd   re   ry   r  )r   r0  r   r  r'   rm   rn   rj   rg   r8   sqrt)r   r"  rp   rq   rt   r  rM   num_positionspatch_pos_embedh0w0s              r1   r!  z3TFGroupViTVisionEmbeddings.interpolate_pos_encoding>  s     (2*'=$
K"4#;#;<Q?-'FeO+++22t{{---dkk,,,((//::3tyy/G+H#diiXeNfJgil'm b * 
 **OAr3<Pr3   c                    t        |      \  }}}}| j                  ||      }| j                  |      }|r|| j                  |||      z   }n|| j                  z   }| j                  |      }|S )N)r!  )r   r*  r-  r!  r0  r+  )r   r   r!  r   _rp   rq   r"  s           r1   r   zTFGroupViTVisionEmbeddings.callY  s     )61fe**<Rj*k
^^J/
 $#d&C&CJPVX]&^^J#d&>&>>J\\*-
r3   r   r   )r   r   r%  r&  )	r   r   r   r   r   r   r!  r   r   r   s   @r1   r(  r(    sD    
L,8 af%AEY]	r3   r(  c                  L     e Zd Zd fdZdd fdZ	 	 	 d	 	 	 	 	 	 	 ddZ xZS )	TFGroupViTTextEmbeddingsc                T    t        |   di | |j                  | _        || _        y )Nr   )r   r   r   	embed_dimr   r   s      r1   r   z!TFGroupViTTextEmbeddings.__init__m  s'    "6"++r3   c                   t        j                  d      5  | j                  | j                  j                  | j
                  ft        | j                  j                  | j                  j                  z        dd      | _	        d d d        t        j                  d      5  | j                  | j                  j                  | j
                  ft        | j                  j                  | j                  j                  z        dd      | _        d d d        t        | 5  |       y # 1 sw Y   xY w# 1 sw Y   %xY w)Ntoken_embeddingTweightr1  position_embeddingr"  )r'   r   r4  r   
vocab_sizerC  r   initializer_factorr  rF  max_position_embeddingsrG  r   r   )r   r   r   s     r1   r   zTFGroupViTTextEmbeddings.buildt  s    ]],- 	//{{--t~~>+DKK,J,JT[[MjMj,jk	 * DK	 ]]/0 	&*oo{{::DNNK+DKK,J,JT[[MjMj,jk!	 '6 'D#	 	k"!	 		 	s   A/D*#A/D6*D36D?c                   ||t        d      |At        || j                  j                         t	        j
                  | j                  |      }t        |      dd }|/t	        j                  t	        j                  d|d         d      }t	        j
                  | j                  |      }t	        j                  ||d   ddf	      }||z   }|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indicesry   r   )startlimitr   r   )input	multiples)r  r   r   rH  r'   gatherrF  r   expand_dimsr<   rG  r*   )r   	input_idsposition_idsinputs_embedsr   position_embedsfinal_embeddingss          r1   r   zTFGroupViTTextEmbeddings.call  s     !6TUU *9dkk6L6LMIIT[[)LM /4>>"((+b/*RYZ[L))4+B+BLY''KPQNTUWXCYZ(?:r3   r   r   r   )r   ztf.TensorShapeNNN)rU  r   rV  r   rW  r   r   r   )r   r   r   r   r   r   r   r   s   @r1   rA  rA  l  sC    #*  $"&#'	      !	 
 
 r3   rA  c                       e Zd ZdZ	 	 	 	 	 	 	 	 	 	 d fdZd	dZed        Zd
dZd	ddZ		 	 	 d	 	 	 	 	 	 	 	 	 ddZ
 xZS )TFGroupViTStagezMThis corresponds to the `GroupingLayer` class in the GroupViT implementation.c                   t        |   d
i | || _        || _        || _        t        |      D cg c]  }t        |d|        c}| _        |dkD  rt        |||d      | _	        nd | _	        |dkD  rS|dkD  rNt        j                  j                  |j                  d      t        |||j                  dz  |d	      g| _        y d | _        y c c}w )N	layers_._r   r   
downsample)r   r   r   r   zgroup_projector.0r   r_   zgroup_projector.1r   )r   r   r   rG   r   r<   TFGroupViTEncoderLayerr   r   r`  r   r   r   r   r   group_projector)	r   r   rG   num_prev_group_tokenr   r   r   ir   s	           r1   r   zTFGroupViTStage.__init__  s     	"6"
.UZ[`UabPQ-fYqc?KbQ3 /!1!	DO #DO!#!(;//8M8MTg/h"0&2D2D2I?at$D  $(D ) cs   Cc                ,   | j                   dkD  r<| j                  d| j                   | j                  j                  fddd      | _        nd | _        | j
                  ry d| _        t        | dd       Mt        j                  | j                  j                        5  | j                  j                  d        d d d        t        | dd       J| j                  D ];  }t        j                  |j                        5  |j                  d        d d d        = t        | d	d       t        j                  | j                  d   j                        5  | j                  d   j                  d d | j                  j                  g       d d d        t        j                  | j                  d   j                        5  | j                  d   j                  d        d d d        y y # 1 sw Y   -xY w# 1 sw Y   !xY w# 1 sw Y   xxY w# 1 sw Y   y xY w)
Nr   r   r	  Tgroup_tokenr1  r`  r   rb  )r   r4  r   r   rf  r   r   r'   r   r`  r   r   r   rb  r   r   layers      r1   r   zTFGroupViTStage.build  s   !##$..0G0GH#"	  /  D  $D::
4t,8t334 ,%%d+,44(4 &]]5::. &KK%& && 4*D1=t33A6;;< U$$Q'--tT4;;;R;R.STUt33A6;;< 4$$Q'--d34 4 >, ,& &U U4 4s0   G$<G16G>;H
$G.1G;	>H
Hc                    | j                   d uS r   )rf  r   s    r1   with_group_tokenz TFGroupViTStage.with_group_token  s    t++r3   c                z    | j                   r,|d d d | j                   f   |d d | j                   d f   fS |d fS r   )rj  r   )r   r   s     r1   split_xzTFGroupViTStage.split_x  sN      Q/4/////0!A8L8L7L7N4N2OOOd7Nr3   c                <    ||S t        j                  ||gd      S )Nr   r   )r'   concat)r   r   rf  s      r1   concat_xzTFGroupViTStage.concat_x  s#    Hyy![)22r3   c                   | j                   r[t        j                  | j                  t	        |      d   ddf      }| j
                  !| j
                  D ]
  } ||      } ||z   }nd}|}| j                  ||      }| j                  D ]  } ||ddd      }	|	d   } | j                  |      \  }}d}
| j                  | j                  ||      \  }}
||f}|r||
fz   }|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   )rR  N)attention_maskcausal_attention_maskoutput_attentions)
rj  r'   r*   rf  r   rb  ro  r   rl  r`  )r   hidden_statesprev_group_tokenrs  r   rf  rh  r   cat_x	layer_outr  outputss               r1   r   zTFGroupViTStage.call  s       ''$"2"2z-?XYZ?[]^`a>bcK##/!11 ?E',-='>$?),<<Ka-[[ 	!E#&*"&	I aLE	! e,;	??&??1k:LAyk",Gr3   )
r   r   rG   rg   rc  rg   r   rg   r   rg   r   )r   r   r   r   )r   r   rf  r   r   r   )NFF)
rt  r   ru  r   rs  r   r   r   r   Tuple[tf.Tensor])r   r   r   r   r   r   propertyrj  rl  ro  r   r   r   s   @r1   r]  r]    s    W!($!( !( "	!(
 !( !(F46 , ,3 .2"'/ / +/  	/
 / 
/r3   r]  c                  H     e Zd Z	 	 	 d	 	 	 	 	 	 	 d fdZdddZddZ xZS )	r   c                f   t        |   di | || _        t        |j                        | _        ||n|j                  }||n|j                  }||n|}t        j                  j                  |d      | _        t        j                  j                  |d      | _        || _        || _        y )Nfc1r   fc2r   )r   r   r   r
   
hidden_actactivation_fnr   intermediate_sizer   r   r   r}  r~  )r   r   r   r  output_sizer   r   s         r1   r   zTFGroupViTMLP.__init__)  s     	"6".v/@/@A%0%<k&BTBT1B1N-TZTlTl%0%<k+<<%%&7e%D<<%%k%>!2&r3   c                l    | j                  |      }| j                  |      }| j                  |      }|S r   )r}  r  r~  )r   rt  r   s      r1   r   zTFGroupViTMLP.call<  s4    /**=9/r3   c                   | j                   ry d| _         t        | dd       Zt        j                  | j                  j
                        5  | j                  j                  d d | j                  g       d d d        t        | dd       [t        j                  | j                  j
                        5  | j                  j                  d d | j                  g       d d d        y y # 1 sw Y   rxY w# 1 sw Y   y xY w)NTr}  r~  )
r   r   r'   r   r}  r   r   r   r~  r  r   s     r1   r   zTFGroupViTMLP.buildB  s    ::
4%1txx}}- ?dD,<,<=>?4%1txx}}- EdD,B,BCDE E 2? ?E Es   )C%2)C1%C.1C:r[  )r   r   r   Optional[int]r  r  r  r  r   )rt  r   r   r   r   r   r   r   r   s   @r1   r   r   (  sD     &*+/%)'$' #' )	'
 #'&	Er3   r   c                  "     e Zd Zdd fdZ xZS )r   c                |    t         |   t        j                  |d            }t        j                  |d      S )Nrx   ra   rt  )r   r   r'   r@   )r   r   r   r   s      r1   r   zTFGroupViTMixerMLP.callO  s/    GLr||AI'FLG||AI..r3   r   )r   r   )r   r   r   r   r   r   s   @r1   r   r   N  s    / /r3   r   c                  b     e Zd ZdZd fdZddZ	 	 	 	 	 d	 	 	 	 	 	 	 	 	 	 	 	 	 d	dZd
dZ xZS )r   z=Multi-headed attention from 'Attention Is All You Need' paperc                8   t        |   di | |j                  | _        |j                  | _        | j                  | j                  z  | _        | j
                  | j                  z  | j                  k7  r&t        d| j                   d| j                   d      |j                  }| j                  dz  d|j                  z  dz  z  |z  }| j                  dz  |z  }t        j                  | j
                        | _        t        j                  j                  | j                  t        |      d      | _        t        j                  j                  | j                  t        |      d      | _        t        j                  j                  | j                  t        |      d	      | _        t        j                  j'                  |j(                  
      | _        t        j                  j                  | j                  t        |      d      | _        y )Nz;embed_dim must be divisible by num_heads (got `embed_dim`: z and `num_heads`: r  r   r_   r   )unitsr  r   r   r   )r,  out_projr   )r   r   r   rC  num_attention_headsattention_head_sizer  rI  num_hidden_layersr8   r9  sqrt_att_head_sizer   r   r   r   r   r   r   r.  attention_dropoutr+  r  )r   r   r   factorin_proj_stdout_proj_stdr   s         r1   r   zTFGroupViTAttention.__init__X  s   "6"++#)#=#= #'>>T5M5M#M ##d&>&>>$..PMdnnM] ^,,-R1 
 **~~t+V5M5M1MRV0VWZ``,6"&))D,D,D"Ell((.._[5QX` ) 
 ll((.._[5QX` ) 
 ll((.._[5QX` ) 
 ||++1I1I+J**.._\5RYc + 
r3   c                    t        j                  ||d| j                  | j                  f      }t        j                  |g d      S )Nry   r  r   r_   r   r	   ra   )r'   rj   r  r  r@   )r   r  rt   s      r1   transpose_for_scoresz(TFGroupViTAttention.transpose_for_scores{  s;    6*b$BZBZ\`\t\t1uv ||F66r3   c                ~   t        |      d   }|du}| j                  |      }	|r%| j                  |      }
| j                  |      }n$| j                  |      }
| j                  |      }| j	                  |	|      }| j	                  |
|      }| j	                  ||      }t        j                  ||d      }t        j                  | j                  |j                        }t        j                  ||      }|t        j                  ||      }|t        j                  ||      }t        |d      }| j                  |      }t        j                  ||      }t        j                  |g d	
      }t        j                  ||d| j                   f      }| j#                  |      }|r||f}|S |f}|S )z#Input shape: Batch x Time x Channelr   NinputsTr   r%   ry   )r=   rH   r  ra   r  )r   r   r   r   r  r'   rz   r)   r  r&   divideaddr   r+  r@   rj   rC  r  )r   rt  rq  rr  rs  r   r   rt   is_cross_attentionmixed_query_layermixed_key_layermixed_value_layerquery_layer	key_layervalue_layerattention_scoresdk_attention_probsattention_probsattention_outputrx  s                        r1   r   zTFGroupViTAttention.call  s     .q1
2$> KK}K="kk1FkGO $3H I"kkk?O $= A//0A:N--ozJ	//0A:N 99[)NWWT,,4D4J4JK99%5r: !,!vv&68MN%!vv&6G *1AK ,,.>,?99_kB<<(8|L ::-=jRTVZVdVdEef==)9: ;L#%56 ScQdr3   c                   | j                   ry d| _         t        | dd       Zt        j                  | j                  j
                        5  | j                  j                  d d | j                  g       d d d        t        | dd       Zt        j                  | j                  j
                        5  | j                  j                  d d | j                  g       d d d        t        | dd       Zt        j                  | j                  j
                        5  | j                  j                  d d | j                  g       d d d        t        | dd       [t        j                  | j                  j
                        5  | j                  j                  d d | j                  g       d d d        y y # 1 sw Y   AxY w# 1 sw Y   xY w# 1 sw Y   xY w# 1 sw Y   y xY w)NTr   r   r   r  )r   r   r'   r   r   r   r   rC  r   r   r  r   s     r1   r   zTFGroupViTAttention.build  s   ::
44(4t{{//0 @!!4t~~">?@44(4t{{//0 @!!4t~~">?@44(4t{{//0 @!!4t~~">?@4T*6t}}112 B##T4$@AB B 7@ @@ @@ @B Bs0   )F32)G )G )G3F= G	GG!r$  )r  r   rt   rg   r   r   NNNNF)rt  r   rq  r   rr  r   rs  r   r   r   r   r   r   ry  r   )	r   r   r   r   r   r  r   r   r   r   s   @r1   r   r   U  sr    G 
F7 %)+/"&+/; ; ";  )	;
  ;  ); ; 
;zBr3   r   c                  J     e Zd Zd fdZ	 d	 	 	 	 	 	 	 	 	 	 	 ddZddZ xZS )ra  c                N   t        |   di | |j                  | _        t	        |d      | _        t        j                  j                  |j                  d      | _
        t        |d      | _        t        j                  j                  |j                  d      | _        y )N	self_attnr   layer_norm1r   r   layer_norm2r   )r   r   r   rC  r   r  r   r   r   r   r  r   r   r  r   s      r1   r   zTFGroupViTEncoderLayer.__init__  s    "6"++,V+F <<::6CXCX_l:m e4 <<::6CXCX_l:mr3   c                    |}| j                  |      }| j                  |||||      }|d   }||z   }|}| j                  |      }| j                  |      }||z   }|f|dd z   }|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.
        r  )rt  rq  rr  rs  r   r   r  r   N)r  r  r  r   )	r   rt  rq  rr  rs  r   residualattention_outputsrx  s	            r1   r   zTFGroupViTEncoderLayer.call  s    & !(((> NN')"7/ + 
 *!, =0 (((>}= =0 "%6qr%::r3   c                   | j                   ry d| _         t        | dd       Mt        j                  | j                  j
                        5  | j                  j                  d        d d d        t        | dd       Zt        j                  | j                  j
                        5  | j                  j                  d d | j                  g       d d d        t        | dd       Mt        j                  | j                  j
                        5  | j                  j                  d        d d d        t        | dd       [t        j                  | j                  j
                        5  | j                  j                  d d | j                  g       d d d        y y # 1 sw Y   4xY w# 1 sw Y   xY w# 1 sw Y   xY w# 1 sw Y   y xY w)NTr  r  r   r  )r   r   r'   r   r  r   r   r  rC  r   r  r   s     r1   r   zTFGroupViTEncoderLayer.build  sp   ::
4d+7t~~223 +$$T*+4-9t//445 E  &&dDNN'CDE4%1txx}}- %t$%4-9t//445 E  &&dDNN'CDE E :+ +E E% %E Es0   F%)F&F2&)F>F#&F/2F;>Gr$  r   )rt  r   rq  r   rr  r   rs  r   r   r   r   ry  r   r   r   s   @r1   ra  ra    sT    n ' ' "'  )	'
  ' ' 
'REr3   ra  c                  N     e Zd Zd fdZ	 d	 	 	 	 	 	 	 	 	 	 	 	 	 ddZddZ xZS )TFGroupViTTextEncoderc                    t        |   di | t        |j                        D cg c]  }t	        |d|        c}| _        y c c}w )Nr_  r   r   )r   r   r<   r  ra  r   r   r   r   rd  r   s       r1   r   zTFGroupViTTextEncoder.__init__  sC    "6"UZ[a[s[sUtuPQ-fYqc?Kuus   Ac                    |rdnd }|rdnd }	t        | j                        D ]*  \  }
}|r||fz   } |||||      }|d   }|s"|	|d   fz   }	, |r||fz   }|st        d |||	fD              S t        |||	      S )Nr   )rs  r   r   c              3  &   K   | ]	  }||  y wr   r   r   vs     r1   r   z-TFGroupViTTextEncoder.call.<locals>.<genexpr>>  s     eqWXWde   last_hidden_statert  ro   )	enumerater   r   r   )r   rt  rq  rr  rs  output_hidden_statesreturn_dictr   encoder_statesall_attentionsidxencoder_layerlayer_outputss                r1   r   zTFGroupViTTextEncoder.call  s      40d"+DKK"8 	FC#!/=2B!B)%"3	M *!,M !/=3C2E!E	F  +}.>>Ne]NN$Seee +>Vd
 	
r3   c                    | j                   ry d| _         t        | dd       K| j                  D ];  }t        j                  |j
                        5  |j                  d        d d d        = y y # 1 sw Y   IxY w)NTr   )r   r   r   r'   r   r   r   rg  s      r1   r   zTFGroupViTTextEncoder.buildC  p    ::
44(4 &]]5::. &KK%& && 5& &   A..A7	rZ  r   )rq  r   rr  r   rs  r   r  r   r  r   r   r   r   zUnion[Tuple, TFBaseModelOutput]r   r   r   s   @r1   r  r    s_    v #
 "#
  )	#

  #
 ##
 #
 #
 
)#
J&r3   r  c                  J     e Zd Zd fdZ	 d	 	 	 	 	 	 	 	 	 	 	 ddZddZ xZS )TFGroupViTVisionEncoderc                0   t        |   di | t        t        |j                              D cg c]T  }t        ||j                  |   |j                  |   |j                  |   |dkD  r|j                  |dz
     ndd|       V c}| _        y c c}w )Nr   r   z	stages_._)r   rG   r   r   rc  r   r   )	r   r   r<   rK   depthsr]  num_group_tokensnum_output_groupsstagesr  s       r1   r   z TFGroupViTVisionEncoder.__init__N  s    "6" 3v}}-.

  mmA& & 7 7 :!'!9!9!!<HIAV%=%=a!e%DST _

 

s   ABc                    |rdnd }|rdnd }d }| j                   D ]0  }	|r||fz   } |	|||      }
|
d   }|
d   }|s"|
d   (||
d   fz   }2 |r||fz   }|st        d |||fD              S t        |||      S )Nr   r   r   r_   c              3  &   K   | ]	  }||  y wr   r   r  s     r1   r   z/TFGroupViTVisionEncoder.call.<locals>.<genexpr>z  s     gqYZYfgr  r  )r  r   r   )r   rt  r  rs  r  r   all_hidden_statesall_groupingsr   stager  s              r1   r   zTFGroupViTVisionEncoder.call]  s     #7BD/T[[ 
	DE#$58H$H!!-?PQM)!,M(+L ]1%5%A -q1A0C C
	D   1]4D Dg]4E}$Uggg +;LYf
 	
r3   c                    | j                   ry d| _         t        | dd       K| j                  D ];  }t        j                  |j
                        5  |j                  d        d d d        = y y # 1 sw Y   IxY w)NTr  )r   r   r  r'   r   r   r   rg  s      r1   r   zTFGroupViTVisionEncoder.build  r  r  )r   r   r   Noner   )rt  r   r  r   rs  r   r  r   r   r   r   zUnion[tuple, TFBaseModelOutput]r   r   r   s   @r1   r  r  M  sR    
*  
  
 # 
  	 

  
  
 
) 
D&r3   r  c                  p     e Zd Zd fdZ	 d	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 ddZej                  fdZddZ xZ	S )	TFGroupViTTextTransformerc                   t        |   di | t        |d      | _        t	        |d      | _        t        j                  j                  |j                  d      | _
        |j                  | _        |j                  | _        y )Nr"  r   encoderfinal_layer_normr   r   )r   r   rA  r"  r  r  r   r   r   r   r  eos_token_idr   rC  r   s      r1   r   z"TFGroupViTTextTransformer.__init__  so    "6"26M,V)D % ? ?H]H]dv ? w #//++r3   c                   t        |      }| j                  ||      }	|\  }
}| j                  |
||	j                        }t	        |      }| j                  |	||||||      }|d   }| j                  |      }| j                  dk(  rtt        j                  |t        j                  t        j                  |d   t        j                        t        j                  j                  |d      fd	
            }nt        j                  |t        j                  t        j                  |d   t        j                        t        j                  j                  t        j                  || j                  k(  t        j                         d      fd	
            }|s
||f|d	d  z   S t#        |||j$                  |j&                        S )N)rU  rV  r%   )rt  rq  rr  rs  r  r  r   r   r  r_   ry   r   r   )valuesrH   rL  r  pooler_outputrt  ro   )r   r"  _build_causal_attention_maskr&   r2   r  r  r  r'   	gather_ndstackr<   int64r8   rI   r)   int8r   rt  ro   )r   rU  rq  rV  rs  r  r  r   r   embedding_outputrt   
seq_lengthrr  encoder_outputssequence_outputpooled_outputs                   r1   r   zTFGroupViTTextTransformer.call  s    !+??Y\?Z!,
J !% A A*j`p`v`v A w &n5,,*)"7/!5# ' 
 *!,///G! LL&HH[^288DbggnnU^egnFhipqM LL&Qrxx@rwwyD<M<M/MUWU\U\']dfg 	M #]3oab6III+-')77&11	
 	
r3   c                j   t        j                  t        j                  |fd      |      }t        j                  t        j                  ||fd      |      }t         j                  j	                  |dd      }t         j                  j                  ||      }t        j                  ||d||f      S )Nr    g     r   ry   )diagonalr   )rQ  rX   )r'   r)   filllinalg	band_partset_diagbroadcast_to)r   rt   r  r&   diagto_masks         r1   r  z6TFGroupViTTextTransformer._build_causal_attention_mask  s    
 wwrww
}c2E: ''"'':z":HEuM ))%%gq"5))$$Wt$<WZJPZ4[\\r3   c                   | j                   ry d| _         t        | dd       Mt        j                  | j                  j
                        5  | j                  j                  d        d d d        t        | dd       Mt        j                  | j                  j
                        5  | j                  j                  d        d d d        t        | dd       [t        j                  | j                  j
                        5  | j                  j                  d d | j                  g       d d d        y y # 1 sw Y   xY w# 1 sw Y   ~xY w# 1 sw Y   y xY w)NTr"  r  r  )
r   r   r'   r   r"  r   r   r  r  rC  r   s     r1   r   zTFGroupViTTextTransformer.build  s   ::
4t,8t334 ,%%d+,4D)5t||001 )""4()4+T2>t4499: J%%++T4,HIJ J ?, ,) )J J$   D2%D>?)E
2D;>E
ErZ  r   )rU  r   rq  r   rV  r   rs  r   r  r   r  r   r   r   r   5Union[TFBaseModelOutputWithPooling, Tuple[tf.Tensor]]r   )
r   r   r   r   r   r'   float32r  r   r   r   s   @r1   r  r    s    	,& E
#E
 "E
  	E

  E
 #E
 E
 E
 
?E
N JL ]$Jr3   r  c                  J     e Zd Zd fdZ	 d	 	 	 	 	 	 	 	 	 	 	 ddZddZ xZS )TFGroupViTVisionTransformerc                    t        |   di | t        |d      | _        t	        |d      | _        t        j                  j                  |j                  d      | _
        |j                  | _        y )Nr"  r   r  r-  r   r   )r   r   r(  r"  r  r  r   r   r   r   r-  r   rC  r   s      r1   r   z$TFGroupViTVisionTransformer.__init__   s^    "6"4V,O.vIF88AVAV]h8i++r3   c                   | j                  |      }| j                  ||||      }|d   }| j                  |      }t        j                  j                  |d      }	|s
||	f|dd  z   S t        ||	|j                  |j                        S )N)rt  r  rs  r  r   r   r   r  )	r"  r  r-  r'   r8   r9   r   rt  ro   )
r   r   rs  r  r  r   r  r  r  r  s
             r1   r   z TFGroupViTVisionTransformer.call  s      ??<8,,*!5/#	 ' 
 ,A. !NN+<=++,=A+F%}58KKK+/')77&11	
 	
r3   c                   | j                   ry d| _         t        | dd       Mt        j                  | j                  j
                        5  | j                  j                  d        d d d        t        | dd       Mt        j                  | j                  j
                        5  | j                  j                  d        d d d        t        | dd       [t        j                  | j                  j
                        5  | j                  j                  d d | j                  g       d d d        y y # 1 sw Y   xY w# 1 sw Y   ~xY w# 1 sw Y   y xY w)NTr"  r  r-  )
r   r   r'   r   r"  r   r   r  r-  rC  r   s     r1   r   z!TFGroupViTVisionTransformer.build)  s   ::
4t,8t334 ,%%d+,4D)5t||001 )""4()4d+7t~~223 C$$dD$..%ABC C 8, ,) )C Cr  r   r   )r   r   rs  r   r  r   r  r   r   r   r   z*Union[Tuple, TFBaseModelOutputWithPooling]r   r   r   s   @r1   r  r    sS    , 
&
  
 #	

 
 
 
4
BCr3   r  c                  |     e Zd ZeZd fdZddZddZe	 	 	 	 	 	 	 d		 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d
d       Z	ddZ
 xZS )TFGroupViTTextMainLayerc                V    t        |   di | || _        t        |d      | _        y )N
text_modelr   r   )r   r   r   r  r  r   s      r1   r   z TFGroupViTTextMainLayer.__init__=  s(    "6"3FNr3   c                .    | j                   j                  S r   )r  r"  r   s    r1   get_input_embeddingsz,TFGroupViTTextMainLayer.get_input_embeddingsB  s    )))r3   c                    || j                   j                  _        t        |      d   | j                   j                  _        y )Nr   )r  r"  rF  r   rH  )r   r   s     r1   set_input_embeddingsz,TFGroupViTTextMainLayer.set_input_embeddingsE  s0    ,1"")0:50A!0D""-r3   c           	         |t        d      t        |      }|t        j                  |d      }| j	                  |||||||      }	|	S )NzYou have to specify input_idsr   dimsr   rU  rq  rV  rs  r  r  r   )r  r   r'   r  r  )
r   rU  rq  rV  rs  r  r  r   r   text_model_outputss
             r1   r   zTFGroupViTTextMainLayer.callI  sg     <== +!WW+Q?N!__)%/!5# - 
 "!r3   c                    | j                   ry d| _         t        | dd       Nt        j                  | j                  j
                        5  | j                  j                  d        d d d        y y # 1 sw Y   y xY w)NTr  )r   r   r'   r   r  r   r   r   s     r1   r   zTFGroupViTTextMainLayer.buildh  si    ::
4t,8t334 ,%%d+, , 9, ,   A11A:rZ  r   zkeras.layers.Layer)r   ztf.VariableNNNNNNFrU  TFModelInputType | Nonerq  np.ndarray | tf.Tensor | NonerV  r  rs  Optional[bool]r  r  r  r  r   r   r   r  r   )r   r   r   r   config_classr   r  r  r   r   r   r   r   s   @r1   r  r  8  s     &LO
*E  .28<6:,0/3&*"*" 6" 4	"
 *" -" $" " 
?" "<,r3   r  c                  h     e Zd ZeZd fdZddZe	 	 	 	 	 d	 	 	 	 	 	 	 	 	 	 	 dd       Zd	dZ	 xZ
S )
TFGroupViTVisionMainLayerc                V    t        |   di | || _        t        |d      | _        y )Nvision_modelr   r   )r   r   r   r  r  r   s      r1   r   z"TFGroupViTVisionMainLayer.__init__v  s)    "6"7^Tr3   c                .    | j                   j                  S r   )r  r"  r   s    r1   r  z.TFGroupViTVisionMainLayer.get_input_embeddings{  s      +++r3   c                L    |t        d      | j                  |||||      }|S )N You have to specify pixel_valuesr   rs  r  r  r   )r  r  )r   r   rs  r  r  r   vision_model_outputss          r1   r   zTFGroupViTVisionMainLayer.call~  sC     ?@@#00%/!5#  1  
 $#r3   c                    | j                   ry d| _         t        | dd       Nt        j                  | j                  j
                        5  | j                  j                  d        d d d        y y # 1 sw Y   y xY w)NTr  )r   r   r'   r   r  r   r   r   s     r1   r   zTFGroupViTVisionMainLayer.build  sm    ::
4.:t00556 .!!''-. . ;. .r  r   r  r  r   r  rs  r  r  r  r  r  r   r   r   r  r   )r   r   r   r   r  r   r  r   r   r   r   r   s   @r1   r  r  q  sy     (LU
,  15,0/3&*$-$ *$ -	$
 $$ $ 
?$ $*.r3   r  c                       e Zd ZeZd fdZddZe	 	 	 	 	 	 	 d	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d	d       Ze	 	 	 	 	 d
	 	 	 	 	 	 	 	 	 	 	 dd       Z	e	 	 	 	 	 	 	 	 	 	 d	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 dd       Z
 xZS )TFGroupViTMainLayerc                   t        |   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      | _        t#        |d      | _        t&        j(                  j+                  | j                  d      t&        j(                  j-                  dd	d
      t&        j(                  j/                  d      t&        j(                  j+                  | j                  d      g| _        t&        j(                  j+                  | j                  d      t&        j(                  j-                  dd	d
      t&        j(                  j/                  d      t&        j(                  j+                  | j                  d      g| _        y )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 r  r   r  zvisual_projection.0zvisual_projection.1g?gh㈵>)r   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   projection_dimprojection_intermediate_dimr   text_embed_dimvision_embed_dimr  r  r  r  r   r   r   BatchNormalizationReLUvisual_projectiontext_projection)r   r   r   r$  r'  r   s        r1   r   zTFGroupViTMainLayer.__init__  s   "6"&,,.@A++,-Q0 
 &..0DE--./q2 
 ((,,$33+1+M+M()55 - 9 93KlS7N[ LLt??F[\LL++1FQT^b+cLL#89LLt229NO	"
 LLt??FYZLL++1Ds\`+aLL#67LLt229LM	 
r3   c                   | j                  dt        j                  j                  | j                  j
                        dd      | _        | j                  ry d| _        t        | dd       Mt        j                  | j                  j                        5  | j                  j                  d        d d d        t        | dd       Mt        j                  | j                  j                        5  | j                  j                  d        d d d        t        | dd       !t        j                  | j                  d   j                        5  | j                  d   j                  d d d | j                   g       d d d        t        j                  | j                  d	   j                        5  | j                  d	   j                  d | j"                  f       d d d        t        j                  | j                  d
   j                        5  | j                  d
   j                  d d d | j"                  g       d d d        t        | dd       "t        j                  | j$                  d   j                        5  | j$                  d   j                  d d d | j&                  g       d d d        t        j                  | j$                  d	   j                        5  | j$                  d	   j                  d | j"                  f       d d d        t        j                  | j$                  d
   j                        5  | j$                  d
   j                  d d d | j"                  g       d d d        y y # 1 sw Y   xY w# 1 sw Y   wxY w# 1 sw Y   xY w# 1 sw Y   xY w# 1 sw Y   oxY w# 1 sw Y   xY w# 1 sw Y   xY w# 1 sw Y   y xY w)N)r   Tlogit_scaler1  r  r  r.  r   r   r	   r/  )r4  r   initializersConstantr   logit_scale_init_valuer1  r   r   r'   r   r  r   r   r  r.  r+  r)  r/  r*  r   s     r1   r   zTFGroupViTMainLayer.build  sE   ??**33DKK4V4VW	 + 
 ::
4t,8t334 ,%%d+,4.:t00556 .!!''-.4,d3?t55a8==> [&&q)//tT4CXCX0YZ[t55a8==> Z&&q)//t7W7W0XYZt55a8==> f&&q)//tT4CcCc0def4*D1=t33A6;;< W$$Q'--tT4ATAT.UVWt33A6;;< X$$Q'--tT5U5U.VWXt33A6;;< d$$Q'--tT4AaAa.bcd d >, ,. .[ [Z Zf fW WX Xd ds`   M40N-N/+N-N(=-N5+O=-O4M>NNN%(N25N?OOc           	         |t        d      t        |      }|t        j                  |d      }| j	                  |||||||      }	|	d   }
| j
                  D ]
  } ||
      }
 |
}|S )N$You have to specify either input_idsr   r  r	  )r  r   r'   r  r  r/  )r   rU  rq  rV  rs  r  r  r   r   text_outputsr  rh  text_featuress                r1   get_text_featuresz%TFGroupViTMainLayer.get_text_features  s     CDD +!WW+Q?N)%/!5# ' 
 %Q)) 	1E!-0M	1 &r3   c                    |t        d      | j                  |||||      }|d   }| j                  D ]
  } ||      } |}	|	S )Nr  r  r   )r  r  r.  )
r   r   rs  r  r  r   vision_outputsr  rh  image_featuress
             r1   get_image_featuresz&TFGroupViTMainLayer.get_image_features  sr     ?@@**%/!5# + 
 'q)++ 	1E!-0M	1 'r3   c           
        |t        d      |t        d      t        |      }|t        j                  |d      }|rd}| j	                  ||||	|
      }| j                  ||||||	|
      }|d   }| j                  D ]
  } ||      } |d   }| j                  D ]
  } ||      } |t        j                  |dd	      z  }|t        j                  |dd	      z  }t        j                  j                  | j                        }t        j                  ||d
      |z  }t        j                  |      }d }|r|d   }t        j                  |dt        |      d   f      }| j                  D ]
  } ||      } |r|d   }n|d   }t        ||j                   dd        }|t        j                  |ddd      z  }t        j                  ||d
      |z  }t        j                  ||j                   d   d|j                   d   f      }t        j                  |d      }t        j                  |t        |      d   t        |      d   df      }t        j                  ||      |z  }t        j                  ||j                   d   |j                   d   |j                   d   |j                   d   f      }d }|rt#        |      d   }|	s|
|||||||f}n||||||f}||f|z   S |S t%        ||||||||      S )Nr6  r  r   r  Tr  r	  ry   r   r   r   r6  r	   r_   	euclidean)r  ordrH   r   rx   ra   )N.)r   r   r   r   r   r   r   r   )r  r   r'   r  r  r  r.  r/  normr8   expr1  rz   r@   rj   r   rX   rD   r   )r   rU  r   rq  rV  return_lossrs  r  output_segmentationr  r   r   r;  r7  r   rh  r   r1  r   r   
seg_logitsimage_group_embedsro   groupinglogits_per_image_groupflatten_groupingr   outputs                               r1   r   zTFGroupViTMainLayer.call*  s    CDD?@@ +!WW+Q?N $**%/!5# + 
 )%/!5# ' 
 &a(++ 	/E .L	/ #1o)) 	-E,K	- $bggld&SS!BGGKb4$PP ggkk$"2"23))K4PS^^<<8
 "0!2!#,>r:VhKijlKmFn!o// ?%*+=%>"?#+A.
+A.
3J@R@RSTSU@VWH "4bgg){d7 " &(YY/A;\`%ado%o"%'ZZ&|/A/A!/Db+J[J[\]J^._&" &(\\2Hy%Y"  "zz(:h;OPQ;RT^_gThijTkmo:pq #9;KL{ZJ:#3#3A#6
8H8H8KX^^\]M^`h`n`nop`q"rJ  1)<D%$#  " +O[,Xdftu)-)9TGf$EvE$-+ *#%* .	
 		
r3   r$  r   r  rU  r  rq  r  rV  r  rs  r  r  r  r  r  r   r   r   r   r  r   r  rs  r  r  r  r  r  r   r   r   r   
NNNNNNNNNFrU  r  r   r  rq  r  rV  r  rC  r  rs  r  r  r  rD  r  r  r  r   r   r   z.Union[TFGroupViTModelOutput, Tuple[tf.Tensor]])r   r   r   r   r  r   r   r   r9  r=  r   r   r   s   @r1   r   r     s    "L'
Rd@  .28<6:,0/3&*!*! 6! 4	!
 *! -! $! ! 
! !F  15,0/3&*- * -	
 $  
 4  .2048<6:&*,0/3.2&*|
*|
 .|
 6	|

 4|
 $|
 *|
 -|
 ,|
 $|
 |
 
8|
 |
r3   r   c                      e Zd ZdZeZdZy)TFGroupViTPreTrainedModelz
    An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
    models.
    groupvitN)r   r   r   r   r   r  base_model_prefixr   r3   r1   rP  rP    s    
 "L"r3   rP  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                       e Zd ZeZdZd fdZe ee	j                  d             eee      	 	 	 	 	 	 	 d	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d	d                     Zd
dZ xZS )TFGroupViTTextModelrU  c                P    t        |   |g|i | t        |d      | _        y NrQ  r   )r   r   r  rQ  r   r   r  r   r   s       r1   r   zTFGroupViTTextModel.__init__A  s(    3&3F3/ZHr3   batch_size, sequence_lengthoutput_typer  c           	     6    | j                  |||||||      }|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
        ```r	  rQ  )	r   rU  rq  rV  rs  r  r  r   rx  s	            r1   r   zTFGroupViTTextModel.callF  s3    > --)%/!5#   
 r3   c                    | j                   ry d| _         t        | dd       Nt        j                  | j                  j
                        5  | j                  j                  d        d d d        y y # 1 sw Y   y xY wNTrQ  r   r   r'   r   rQ  r   r   r   s     r1   r   zTFGroupViTTextModel.buildq  i    ::
4T*6t}}112 *##D)* * 7* *r  rZ  r  r  r   )r   r   r   r   r  main_input_namer   r   r   GROUPVIT_TEXT_INPUTS_DOCSTRINGformatr   r   r   r   r   r   s   @r1   rT  rT  =  s    %L!OI
 *+I+P+PQn+op+GVhi .28<6:,0/3&*&*& 6& 4	&
 *& -& $& & 
?& j q &P*r3   rT  c                       e Zd ZeZdZd fdZe ee	       e
ee      	 	 	 	 	 d	 	 	 	 	 	 	 	 	 	 	 dd                     Zd	dZ xZS )
TFGroupViTVisionModelr   c                P    t        |   |g|i | t        |d      | _        y rV  )r   r   r  rQ  rW  s       r1   r   zTFGroupViTVisionModel.__init__~  s(    3&3F31&zJr3   rY  c                2    | j                  |||||      }|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   rs  r  r  r   rx  s          r1   r   zTFGroupViTVisionModel.call  s.    D --%/!5#   
 r3   c                    | j                   ry d| _         t        | dd       Nt        j                  | j                  j
                        5  | j                  j                  d        d d d        y y # 1 sw Y   y xY wr^  r_  r   s     r1   r   zTFGroupViTVisionModel.build  r`  r  r   r  r  r   )r   r   r   r   r  ra  r   r   r    GROUPVIT_VISION_INPUTS_DOCSTRINGr   r   r   r   r   r   s   @r1   re  re  z  s    'L$OK
 *+KL+GVjk 15,0/3&*'-' *' -	'
 $' ' 
?' l M 'R*r3   re  c                      e Zd ZeZd	 fdZe eej                  d            	 	 	 	 	 	 	 d
	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 dd              Z
e ee      	 	 	 	 	 d	 	 	 	 	 	 	 	 	 	 	 dd              Ze eej                  d             eee      	 	 	 	 	 	 	 	 	 	 d	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 dd                     ZddZddZ xZS )TFGroupViTModelc                P    t        |   |g|i | t        |d      | _        y rV  )r   r   r   rQ  rW  s       r1   r   zTFGroupViTModel.__init__  s(    3&3F3+FDr3   rX  c           	     J    | j                   j                  |||||||      }|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)
        ```r	  )rQ  r9  )	r   rU  rq  rV  rs  r  r  r   r8  s	            r1   r9  z!TFGroupViTModel.get_text_features  s:    : 77)%/!5# 8 
 r3   c                F    | j                   j                  |||||      }|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  )rQ  r=  )r   r   rs  r  r  r   r<  s          r1   r=  z"TFGroupViTModel.get_image_features  s5    B 99%/!5# : 
 r3   rY  c                <    | j                  |||||||||	|

      }|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
        ```)
rU  r   rq  rV  rC  rs  r  rD  r  r   r\  )r   rU  r   rq  rV  rC  rs  r  rD  r  r   rx  s               r1   r   zTFGroupViTModel.call  s=    T --%)%#/!5 3#   
 r3   c                    |S r   r   )r   rJ  s     r1   serving_outputzTFGroupViTModel.serving_outputN  s	     r3   c                    | j                   ry d| _         t        | dd       Nt        j                  | j                  j
                        5  | j                  j                  d        d d d        y y # 1 sw Y   y xY wr^  r_  r   s     r1   r   zTFGroupViTModel.buildT  r`  r  r$  r  rK  r  rL  rM  rN  )rJ  r   r   r   r   )r   r   r   r   r  r   r   r   rb  rc  r9  ri  r=  GROUPVIT_INPUTS_DOCSTRINGr   r   r   rq  r   r   r   s   @r1   rk  rk    s   !LE
 *+I+P+PQn+op .28<6:,0/3&*%*% 6% 4	%
 *% -% $% % 
% q %N *+KL 15,0/3&*'-' *' -	'
 $' ' 
' M 'R *+D+K+KLi+jk+@~^ .2048<6:&*,0/3.2&*4*4 .4 6	4
 44 $4 *4 -4 ,4 $4 4 
84 _ l 4l*r3   rk  r   )r,   r   r-   r  )r=   r   r   r   )rA   r   r   r   )r=   r   rM   rg   r   r   )r   Fry   )
r=   r   rY   floatrZ   r   rM   rg   r   r   r   )
ro   r   rp   rg   rq   rg   rf   r   r   r   )ro   ry  r|   z
Tuple[int]r   r   )\r   
__future__r   collections.abcr   r8   dataclassesr   typingr   r   r   r   numpyrh   
tensorflowr'   activations_tfr
   modeling_tf_outputsr   r   modeling_tf_utilsr   r   r   r   r   r   tf_utilsr   r   r   utilsr   r   r   r   r   r   configuration_groupvitr   r   r   
get_loggerr   loggertensorflow_probabilityrT   rU   Normalr?  ImportErrorerror_CHECKPOINT_FOR_DOCr+   r2   r>   rD   rR   r]   rv   r   r   r   Layerr   r   r   r  r(  rA  r]  r   r   r   ra  r  r  r  r  r  r  r   rP  GROUPVIT_START_DOCSTRINGrb  ri  rs  rT  re  rk  r   r3   r1   <module>r     s    "   ! . .   / R  S R  ] \ 
		H	% '(
, $$C$8, $$C$8 1  
6-"2#L,8 /
K /
 /
dLELL$6$6 LD?G 2 2 ?GDT.ELL.. T.pKM 2 2 KM^N!3!3 Nd7 u||11 7 tell(( D#EELL&& #EL/ /yB%,,,, yBzBEU\\// BEL2&ELL.. 2&j9&ell00 9&zqJ 2 2 qJj6C%,,"4"4 6Cr 4,ell00 4, 4,n '. 2 2 '. '.T H
%,,,, H
 H
V# 1 #" H#" J$  *( V:*3 :*z;*5 ;*| ./a*/ a* 0a*};  
u	

  s$   !M' *!N 'N NNN