
    sgΑ                    ,   d Z ddlmZ ddlZddlZddl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mZ ddlmZmZmZmZmZmZmZ dd	lmZmZ dd
lm Z m!Z!m"Z"m#Z# ddl$m%Z%  e#jL                  e'      Z(dZ)dZ*g dZ+dZ,dZ- G d dej\                  j^                        Z0 G d dej\                  j^                        Z1 G d dej\                  j^                        Z2 G d dej\                  j^                        Z3 G d dej\                  j^                        Z4 G d dej\                  j^                        Z5 G d dej\                  j^                        Z6 G d  d!ej\                  j^                        Z7 G d" d#ej\                  j^                        Z8e G d$ d%ej\                  j^                               Z9 G d& d'e      Z:d(Z;d)Z< e!d*e;       G d+ d,e:             Z= G d- d.ej\                  j^                        Z> e!d/e;       G d0 d1e:e             Z?y)2zTF 2.0 ViT model.    )annotationsN)OptionalTupleUnion   )get_tf_activation)TFBaseModelOutputTFBaseModelOutputWithPoolingTFSequenceClassifierOutput)TFModelInputTypeTFPreTrainedModelTFSequenceClassificationLossget_initializerkeraskeras_serializableunpack_inputs)
shape_liststable_softmax)add_code_sample_docstringsadd_start_docstrings%add_start_docstrings_to_model_forwardlogging   )	ViTConfigr   z!google/vit-base-patch16-224-in21k)r      i   zgoogle/vit-base-patch16-224zEgyptian catc                  N     e Zd ZdZd fdZddZddZ	 d		 	 	 	 	 	 	 d
dZ xZS )TFViTEmbeddingszB
    Construct the CLS token, position and patch embeddings.

    c                    t        |   di | t        |d      | _        t        j
                  j                  |j                        | _        || _	        y )Npatch_embeddingsnamerate )
super__init__TFViTPatchEmbeddingsr   r   layersDropouthidden_dropout_probdropoutconfigselfr,   kwargs	__class__s      Z/var/www/html/venv/lib/python3.12/site-packages/transformers/models/vit/modeling_tf_vit.pyr&   zTFViTEmbeddings.__init__>   sI    "6" 4VBT U||++1K1K+L    c                d   | j                   j                  }| j                  dd| j                  j                  ft        | j                  j                        dd      | _        | j                  d|dz   | j                  j                  ft        | j                  j                        dd      | _        | 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)Nr   T	cls_token)shapeinitializer	trainabler!   position_embeddingsr   )r   num_patches
add_weightr,   hidden_sizer   initializer_ranger4   r8   builtgetattrtf
name_scoper!   build)r.   input_shaper9   s      r1   rA   zTFViTEmbeddings.buildE   s
   ++77a001'(E(EF	 ) 
 $(??kAot{{'>'>?'(E(EF&	 $3 $
  ::
4+T2>t4499: 2%%++D12 2 ?2 2s    D&&D/c                   t        |      \  }}}|dz
  }t        | j                        \  }}	}|	dz  }	||	k(  r||k(  r| j                  S | j                  ddddf   }
| j                  ddddf   }|| j                  j                  z  }|| j                  j                  z  }t        j
                  j                  t	        j                  |dt        t        j                  |	            t        t        j                  |	            |f      ||fd      }t        |      }||d   k(  r||d   k(  sJ t	        j                  |dd|f	      }t	        j                  |
|fd
      S )a#  
        This method allows to interpolate the pre-trained position encodings, to be able to use the model on higher
        resolution images.

        Source:
        https://github.com/facebookresearch/dino/blob/de9ee3df6cf39fac952ab558447af1fa1365362a/vision_transformer.py#L174
        r   N)r5   bicubic)imagessizemethodtensorr5   )valuesaxis)r   r8   r,   
patch_sizer?   imageresizereshapeintmathsqrtconcat)r.   
embeddingsheightwidth
batch_sizeseq_lendimr9   _num_positionsclass_pos_embedpatch_pos_embedh0w0r5   s                  r1   interpolate_pos_encodingz(TFViTEmbeddings.interpolate_pos_encoding[   s]    $.j#9 
GSk()A)AB=!-'FeO+++221bqb59221ab59t{{---dkk,,,((//::3tyy/G+H#diiXeNfJgil'm b * 
 ?+U2Y2r?22**OAr3<Pyy/ BKKr2   c                :   t        |      \  }}}}| j                  |||      }t        j                  | j                  |d      }	t        j
                  |	|fd      }|r|| j                  |||      z   }n|| j                  z   }| j                  ||      }|S )N)rc   trainingr   )repeatsrN   r   )rN   )re   )	r   r   r?   repeatr4   rV   rc   r8   r+   )
r.   pixel_valuesrc   re   rZ   num_channelsrX   rY   rW   
cls_tokenss
             r1   callzTFViTEmbeddings.call}   s     3=\2J/
L&%**3KV^ + 


 YYt~~zJ
YY
J7a@
 $#d&C&CJPVX]&^^J#d&>&>>J\\*x\@
r2   r,   r   N)return	tf.TensorFFrh   ro   rc   boolre   rr   rn   ro   )	__name__
__module____qualname____doc__r&   rA   rc   rk   __classcell__r0   s   @r1   r   r   8   sE    
2, LF af%AEY]	r2   r   c                  F     e Zd ZdZd fdZ	 d	 	 	 	 	 	 	 ddZddZ xZS )	r'   z
    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                4   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                  |||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_sizerO   ri   r;   
isinstancecollectionsabcIterabler9   r,   r   r(   Conv2Dr   r<   r~   )	r.   r,   r/   r   rO   ri   r;   r9   r0   s	           r1   r&   zTFViTPatchEmbeddings.__init__   s   "6"!'!2!2F4E4EJ
$*$7$79K9Kk#-j+//:R:R#SZZdfpYq
#-j+//:R:R#SZZdfpYq
!!}
15*Q-:VW=:XY$$&(,,--"'.t{{/L/LM$ . 

r2   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                  |||	d
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 (z).)r      r   r   permrJ   rK   )
r   r?   executing_eagerlyri   
ValueErrorr   	transposer~   rO   rR   )r.   rh   rc   re   rZ   ri   rX   rY   r~   r9   rW   s              r1   rk   zTFViTPatchEmbeddings.call   s    3=\2J/
L&%!ld6G6G&Gw  (##%T__Q//5DOOA<N3N$,VHAeW =!__Q/0$//!2D1ERI  ||L|D__\2
  22vQRAS7STZZz*kSU9VW
r2   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!   rA   ri   r.   rB   s     r1   rA   zTFViTPatchEmbeddings.build   s}    ::
4t,8t334 M%%tT49J9J&KLM M 9M Ms   *A??Brl   rp   rq   rm   rs   rt   ru   rv   r&   rk   rA   rw   rx   s   @r1   r'   r'      s?    
6 af%AEY]	<Mr2   r'   c                  N     e Zd Zd fdZddZ	 d	 	 	 	 	 	 	 	 	 ddZd	dZ xZS )
TFViTSelfAttentionc                   t        |   d
i | |j                  |j                  z  dk7  r&t	        d|j                   d|j                   d      |j                  | _        t        |j                  |j                  z        | _        | j                  | j                  z  | _        t        j                  | j                        | _
        t        j                  j                  | j                  t        |j                        d      | _        t        j                  j                  | j                  t        |j                        d      | _        t        j                  j                  | j                  t        |j                        d      | _        t        j                  j'                  |j(                  	      | _        || _        y )Nr   zThe hidden size (z6) is not a multiple of the number of attention heads ()queryunitsr   r!   keyvaluer"   r$   )r%   r&   r;   num_attention_headsr   rS   attention_head_sizeall_head_sizerT   rU   sqrt_att_head_sizer   r(   Denser   r<   r   r   r   r)   attention_probs_dropout_probr+   r,   r-   s      r1   r&   zTFViTSelfAttention.__init__   s   "6" : ::a?#F$6$6#7 8''-'A'A&B!E 
 $*#=#= #&v'9'9F<V<V'V#W !558P8PP"&))D,D,D"E\\''$$IaIa9bip ( 

 <<%%$$IaIa9bin & 
 \\''$$IaIa9bip ( 

 ||++1T1T+Ur2   c                    t        j                  ||d| j                  | j                  f      }t        j                  |g d      S )NrJ   rK   r   r   r   r   r   )r?   rR   r   r   r   )r.   rL   rZ   s      r1   transpose_for_scoresz'TFViTSelfAttention.transpose_for_scores   s;    6*b$BZBZ\`\t\t1uv ||F66r2   c                   t        |      d   }| j                  |      }| j                  |      }| j                  |      }| j	                  ||      }	| j	                  ||      }
| j	                  ||      }t        j                  |	|
d      }t        j                  | j                  |j                        }t        j                  ||      }t        |d      }| j                  ||      }|t        j                  ||      }t        j                  ||      }t        j                  |g d	
      }t        j                  ||d| j                   f      }|r||f}|S |f}|S )Nr   inputsT)transpose_b)dtyperJ   )logitsrN   r   re   r   r   rK   )r   r   r   r   r   r?   matmulcastr   r   divider   r+   multiplyr   rR   r   )r.   hidden_states	head_maskoutput_attentionsre   rZ   mixed_query_layermixed_key_layermixed_value_layerquery_layer	key_layervalue_layerattention_scoresdkattention_probsattention_outputoutputss                    r1   rk   zTFViTSelfAttention.call   se     .q1
 JJmJ<((-(8 JJmJ<//0A:N--ozJ	//0A:N 99[)NWWT,,4D4J4JK99%5r: )0@rJ ,,o,Q   kk/9EO99_kB<<(8|L ::-=jRTVZVhVhEij9J#_5 RbPcr2   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       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)NTr   r   r   )r=   r>   r?   r@   r   r!   rA   r,   r;   r   r   r   s     r1   rA   zTFViTSelfAttention.build)  s9   ::
4$'3tzz/ H

  $dkk.E.E!FGH4%1txx}}- FdDKK,C,CDEF4$'3tzz/ H

  $dkk.E.E!FGH H 4H HF FH Hs$   3E*<3E6-3F*E36E?Frl   )rL   ro   rZ   rS   rn   ro   F
r   ro   r   ro   r   rr   re   rr   rn   Tuple[tf.Tensor]rm   )rs   rt   ru   r&   r   rk   rA   rw   rx   s   @r1   r   r      sN    47 ' ' '  	'
 ' 
'RHr2   r   c                  6     e Zd ZdZd fdZdddZddZ xZS )	TFViTSelfOutputz
    The residual connection is defined in TFViTLayer instead of here (as is the case with other models), due to the
    layernorm applied before each block.
    c                   t        |   di | t        j                  j	                  |j
                  t        |j                        d      | _        t        j                  j                  |j                        | _        || _        y Ndenser   r"   r$   r%   r&   r   r(   r   r;   r   r<   r   r)   r*   r+   r,   r-   s      r1   r&   zTFViTSelfOutput.__init__>  o    "6"\\''$$IaIa9bip ( 

 ||++1K1K+Lr2   c                P    | j                  |      }| j                  ||      }|S Nr   r   r   r+   r.   r   input_tensorre   s       r1   rk   zTFViTSelfOutput.callG  s*    

-
8MHMr2   c                (   | j                   ry 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   y xY wNTr   	r=   r>   r?   r@   r   r!   rA   r,   r;   r   s     r1   rA   zTFViTSelfOutput.buildM  }    ::
4$'3tzz/ H

  $dkk.E.E!FGH H 4H H   3BBrl   r   r   ro   r   ro   re   rr   rn   ro   rm   r   rx   s   @r1   r   r   8  s    
Hr2   r   c                  L     e Zd Zd fdZd Z	 d	 	 	 	 	 	 	 	 	 ddZddZ xZS )	TFViTAttentionc                l    t        |   di | t        |d      | _        t	        |d      | _        y )N	attentionr    outputr$   )r%   r&   r   self_attentionr   dense_outputr-   s      r1   r&   zTFViTAttention.__init__W  s1    "6"0kJ+FBr2   c                    t         rm   NotImplementedError)r.   headss     r1   prune_headszTFViTAttention.prune_heads]  s    !!r2   c                p    | j                  ||||      }| j                  |d   ||      }|f|dd  z   }|S )Nr   r   r   re   r   r   r   re   r   )r   r   )r.   r   r   r   re   self_outputsr   r   s           r1   rk   zTFViTAttention.call`  sb     **&)O`ks + 
  ,,&q/x - 
 $%QR(88r2   c                   | j                   ry d| _         t        | dd       Mt        j                  | j                  j
                        5  | j                  j                  d        d d d        t        | dd       Nt        j                  | j                  j
                        5  | j                  j                  d        d d d        y y # 1 sw Y   exY w# 1 sw Y   y xY w)NTr   r   )r=   r>   r?   r@   r   r!   rA   r   r   s     r1   rA   zTFViTAttention.buildq  s    ::
4)40<t22778 0##))$/04.:t00556 .!!''-. . ;0 0. .s   C%CCC rl   r   )
r   ro   r   ro   r   rr   re   rr   rn   r   rm   )rs   rt   ru   r&   r   rk   rA   rw   rx   s   @r1   r   r   V  sM    C"    	
  
"	.r2   r   c                  0     e Zd Zd fdZddZddZ xZS )TFViTIntermediatec                T   t        |   di | t        j                  j	                  |j
                  t        |j                        d      | _        t        |j                  t              r"t        |j                        | _        || _        y |j                  | _        || _        y )Nr   r   r$   )r%   r&   r   r(   r   intermediate_sizer   r<   r   r   
hidden_actstrr   intermediate_act_fnr,   r-   s      r1   r&   zTFViTIntermediate.__init__~  s    "6"\\''**vOgOg?hov ( 

 f''-'89J9J'KD$  (.'8'8D$r2   c                L    | j                  |      }| j                  |      }|S )Nr   )r   r   )r.   r   s     r1   rk   zTFViTIntermediate.call  s(    

-
800?r2   c                (   | j                   ry 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   y xY wr   r   r   s     r1   rA   zTFViTIntermediate.build  r   r   rl   r   ro   rn   ro   rm   rs   rt   ru   r&   rk   rA   rw   rx   s   @r1   r   r   }  s    Hr2   r   c                  2     e Zd Zd fdZdddZddZ xZS )TFViTOutputc                   t        |   di | t        j                  j	                  |j
                  t        |j                        d      | _        t        j                  j                  |j                        | _        || _        y r   r   r-   s      r1   r&   zTFViTOutput.__init__  r   r2   c                Z    | j                  |      }| j                  ||      }||z   }|S r   r   r   s       r1   rk   zTFViTOutput.call  s4    

-
8MHM%4r2   c                (   | j                   ry 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   y xY wr   )	r=   r>   r?   r@   r   r!   rA   r,   r   r   s     r1   rA   zTFViTOutput.build  s}    ::
4$'3tzz/ N

  $dkk.K.K!LMN N 4N Nr   rl   r   r   rm   r   rx   s   @r1   r   r     s    Nr2   r   c                  J     e Zd ZdZd fdZ	 d	 	 	 	 	 	 	 	 	 ddZddZ xZS )	
TFViTLayerz?This corresponds to the Block class in the timm implementation.c                ^   t        |   di | t        |d      | _        t	        |d      | _        t        |d      | _        t        j                  j                  |j                  d      | _        t        j                  j                  |j                  d      | _        || _        y )	Nr   r    intermediater   layernorm_beforeepsilonr!   layernorm_afterr$   )r%   r&   r   r   r   r   r   
vit_outputr   r(   LayerNormalizationlayer_norm_epsr   r  r,   r-   s      r1   r&   zTFViTLayer.__init__  s    "6"'[A-f>J%f8< % ? ?H]H]dv ? w$||>>vG\G\ct>ur2   c                    | j                  | j                  |      |||      }|d   }||z   }| j                  |      }| j                  |      }| j	                  |||      }|f|dd  z   }	|	S )Nr   )r   r   r   re   r   r   r   r   )r   r   r  r   r  )
r.   r   r   r   re   attention_outputsr   layer_outputintermediate_outputr   s
             r1   rk   zTFViTLayer.call  s     !NN..m.D/ + 
 -Q/ )=8 ++=+A"//l/K -MT\ ' 
  /$5ab$99r2   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       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       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   Ux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!   rA   r   r  r   r,   r;   r  r   s     r1   rA   zTFViTLayer.build  s   ::
4d+7t~~223 +$$T*+4.:t00556 .!!''-.4t,8t334 ,%%d+,4+T2>t4499: S%%++T49P9P,QRS4*D1=t33889 R$$**D$8O8O+PQR R >+ +. ., ,S SR Rs<   H%H?H!3H.
3H:HH!H+.H7:Irl   r   r   rm   r   rx   s   @r1   r   r     sL    I	      	
  
@Rr2   r   c                  N     e Zd Zd fdZ	 d	 	 	 	 	 	 	 	 	 	 	 	 	 ddZddZ xZS )TFViTEncoderc                    t        |   di | t        |j                        D cg c]  }t	        |d|        c}| _        y c c}w )Nzlayer_._r    r$   )r%   r&   rangenum_hidden_layersr   layer)r.   r,   r/   ir0   s       r1   r&   zTFViTEncoder.__init__  s@    "6"GLVMeMeGfg!jn=g
gs   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$   r   r   r   c              3  &   K   | ]	  }||  y wrm   r$   ).0vs     r1   	<genexpr>z$TFViTEncoder.call.<locals>.<genexpr>  s     hqZ[Zghs   )last_hidden_stater   
attentions)	enumerater  tupler	   )r.   r   r   r   output_hidden_statesreturn_dictre   all_hidden_statesall_attentionsr  layer_modulelayer_outputss               r1   rk   zTFViTEncoder.call  s     #7BD0d(4 	FOA|#$58H$H!(+#A,"3!	M *!,M !/=3C2E!E	F    1]4D Dh]4E~$Vhhh +;LYg
 	
r2   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!   rA   )r.   rB   r  s      r1   rA   zTFViTEncoder.build#  sp    ::
4$'3 &]]5::. &KK%& && 4& &s   A..A7	rl   r   )r   ro   r   ro   r   rr   r  rr   r  rr   re   rr   rn   z*Union[TFBaseModelOutput, Tuple[tf.Tensor]]rm   r   rx   s   @r1   r  r    s]    h $
 $
 $
  	$

 #$
 $
 $
 
4$
L&r2   r  c                  |     e Zd ZeZdd fdZddZd Ze	 	 	 	 	 	 	 d		 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d
d       Z	ddZ
 xZS )TFViTMainLayerc                   t        |   di | || _        t        |d      | _        t        |d      | _        t        j                  j                  |j                  d      | _        |rt        |d      | _        y d | _        y )NrW   r    encoder	layernormr   poolerr$   )r%   r&   r,   r   rW   r  r%  r   r(   r  r  r&  TFViTPoolerr'  )r.   r,   add_pooling_layerr/   r0   s       r1   r&   zTFViTMainLayer.__init__1  so    "6")&|D#F;88AVAV]h8i<Mk&x8SWr2   c                .    | j                   j                  S rm   )rW   r   )r.   s    r1   get_input_embeddingsz#TFViTMainLayer.get_input_embeddings;  s    ///r2   c                    t         )z
        Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer} See base
        class PreTrainedModel
        r   )r.   heads_to_prunes     r1   _prune_headszTFViTMainLayer._prune_heads>  s
    
 "!r2   c                   |t        d      | j                  |||      }|t        d g| j                  j                  z  }| j                  ||||||      }	|	d   }
| j                  |
      }
| j                  | j                  |
      nd }|s
|
|f|	dd  z   S t        |
||	j                  |	j                        S )	Nz You have to specify pixel_values)rh   rc   re   )r   r   r   r  r  re   r   r   r  r   )r  pooler_outputr   r  )r   rW   r   r,   r  r%  r&  r'  r
   r   r  )r.   rh   r   r   r  rc   r  re   embedding_outputencoder_outputssequence_outputpooled_outputs               r1   rk   zTFViTMainLayer.callE  s     ?@@??%%= + 
  %%!>!>>I,,*/!5# ' 
 *!,...@FJkkF]/Bcg#]3oab6III+-')77&11	
 	
r2   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       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   1xY w# 1 sw Y   xY w# 1 sw Y   ~xY w# 1 sw Y   y xY w)NTrW   r%  r&  r'  )r=   r>   r?   r@   rW   r!   rA   r%  r&  r,   r;   r'  r   s     r1   rA   zTFViTMainLayer.buildz  sb   ::
4t,8t334 ,%%d+,4D)5t||001 )""4()4d+7t~~223 L$$dD$++2I2I%JKL44(4t{{//0 (!!$'( ( 5, ,) )L L( (s0   F%F#?3F/0F;F #F,/F8;G)T)r,   r   r)  rr   )rn   zkeras.layers.LayerNNNNNNFrh   TFModelInputType | Noner   np.ndarray | tf.Tensor | Noner   Optional[bool]r  r:  rc   r:  r  r:  re   rr   rn   z5Union[TFBaseModelOutputWithPooling, Tuple[tf.Tensor]]rm   )rs   rt   ru   r   config_classr&   r+  r.  r   rk   rA   rw   rx   s   @r1   r#  r#  -  s    LX0"  1537,0/337&*2
-2
 12
 *	2

 -2
 #12
 $2
 2
 
?2
 2
h(r2   r#  c                      e Zd ZdZeZdZdZy)TFViTPreTrainedModelz
    An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
    models.
    vitrh   N)rs   rt   ru   rv   r   r;  base_model_prefixmain_input_namer$   r2   r1   r=  r=    s    
 L$Or2   r=  a	  

    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>

    TensorFlow models and layers in `transformers` accept two formats as input:

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

    The reason the second format is supported is that Keras methods prefer this format when passing inputs to models
    and layers. Because of this support, when using methods like `model.fit()` things should "just work" for you - just
    pass your inputs and labels in any format that `model.fit()` supports! If, however, you want to use the second
    format outside of Keras methods like `fit()` and `predict()`, such as when creating your own layers or models with
    the Keras `Functional` API, there are three possibilities you can use to gather all the input Tensors in the first
    positional argument:

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

    Note that when creating models and layers with
    [subclassing](https://keras.io/guides/making_new_layers_and_models_via_subclassing/) then you don't need to worry
    about any of this, as you can just pass inputs like you would to any other Python function!

    </Tip>

    Args:
        config ([`ViTConfig`]): 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 [`~TFPreTrainedModel.from_pretrained`] method to load the model weights.
ar  
    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 [`ViTImageProcessor.__call__`]
            for details.

        head_mask (`np.ndarray` or `tf.Tensor` of shape `(num_heads,)` or `(num_layers, num_heads)`, *optional*):
            Mask to nullify selected heads of the self-attention modules. Mask values selected in `[0, 1]`:

            - 1 indicates the head is **not masked**,
            - 0 indicates the head is **masked**.

        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.
        interpolate_pos_encoding (`bool`, *optional*):
            Whether to interpolate the pre-trained position encodings.
        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).
z]The bare ViT Model transformer outputting raw hidden-states without any specific head on top.c            	           e Zd Zddd fdZe ee       eee	e
de      	 	 	 	 	 	 	 d		 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d
d                     ZddZ xZS )
TFViTModelT)r)  c               R    t        |   |g|i | t        ||d      | _        y )Nr>  r)  r!   )r%   r&   r#  r>  )r.   r,   r)  r   r/   r0   s        r1   r&   zTFViTModel.__init__  s,    3&3F3!&<MTYZr2   vision)
checkpointoutput_typer;  modalityexpected_outputc           	     6    | j                  |||||||      }|S )Nrh   r   r   r  rc   r  re   )r>  )	r.   rh   r   r   r  rc   r  re   r   s	            r1   rk   zTFViTModel.call  s3    & ((%/!5%=#  
 r2   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!   rA   r   s     r1   rA   zTFViTModel.build	  se    ::
4%1txx}}- %t$% % 2% %s   A11A:rl   r6  r7  rm   )rs   rt   ru   r&   r   r   VIT_INPUTS_DOCSTRINGr   _CHECKPOINT_FOR_DOCr
   _CONFIG_FOR_DOC_EXPECTED_OUTPUT_SHAPErk   rA   rw   rx   s   @r1   rB  rB    s    
 FJ [
 *+?@&0$. 1537,0/337&*- 1 *	
 - #1 $  
? A ,%r2   rB  c                  0     e Zd Zd fdZddZddZ xZS )r(  c                    t        |   di | t        j                  j	                  |j
                  t        |j                        dd      | _        || _	        y )Ntanhr   )r   r   
activationr!   r$   )
r%   r&   r   r(   r   r;   r   r<   r   r,   r-   s      r1   r&   zTFViTPooler.__init__  sT    "6"\\''$$.v/G/GH	 ( 

 r2   c                <    |d d df   }| j                  |      }|S )Nr   r   )r   )r.   r   first_token_tensorr4  s       r1   rk   zTFViTPooler.call  s*     +1a40

*<
=r2   c                (   | j                   ry 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   y xY wr   r   r   s     r1   rA   zTFViTPooler.build&  r   r   rl   r   rm   r   rx   s   @r1   r(  r(    s    	Hr2   r(  a  
    ViT Model transformer with an image classification head on top (a linear layer on top of the final hidden state of
    the [CLS] token) e.g. for ImageNet.

    <Tip>

        Note that it's possible to fine-tune ViT on higher resolution images than the ones it has been trained on, by
        setting `interpolate_pos_encoding` to `True` in the forward of the model. This will interpolate the pre-trained
        position embeddings to the higher resolution.

    </Tip>
    c                       e Zd Zd fdZe ee       eee	e
e      	 	 	 	 	 	 	 	 d	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 dd                     ZddZ xZS )	TFViTForImageClassificationc                
   t        |   |g|i | |j                  | _        t        |dd      | _        t
        j                  j                  |j                  t        |j                        d      | _
        || _        y )NFr>  rD  
classifierr   )r%   r&   
num_labelsr#  r>  r   r(   r   r   r<   r[  r,   )r.   r,   r   r/   r0   s       r1   r&   z$TFViTForImageClassification.__init__?  sw    3&3F3 ++!&EN  ,,,,##.v/G/GH - 

 r2   )rF  rG  r;  rI  c	           	        | j                  |||||||      }	|	d   }
| j                  |
dddddf         }|dn| j                  ||      }|s|f|	dd z   }||f|z   S |S t        |||	j                  |	j
                        S )a  
        labels (`tf.Tensor` or `np.ndarray` of shape `(batch_size,)`, *optional*):
            Labels for computing the image classification/regression loss. Indices should be in `[0, ...,
            config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
            `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
        rK  r   Nr   )labelsr   r   )lossr   r   r  )r>  r[  hf_compute_lossr   r   r  )r.   rh   r   r   r  rc   r  r^  re   r   r3  r   r_  r   s                 r1   rk   z TFViTForImageClassification.callM  s    4 ((%/!5%=#  
 "!*1a(@A~t4+?+?vV\+?+]Y,F)-)9TGf$EvE)!//))	
 	
r2   c                   | j                   ry 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   y xY w)NTr>  r[  )
r=   r>   r?   r@   r>  r!   rA   r[  r,   r;   r   s     r1   rA   z!TFViTForImageClassification.build  s    ::
4%1txx}}- %t$%4t,8t334 M%%tT4;;3J3J&KLM M 9% %M Ms   C"%3C."C+.C7rl   )NNNNNNNF)rh   r8  r   r9  r   r:  r  r:  rc   r:  r  r:  r^  r9  re   r:  rn   z3Union[TFSequenceClassifierOutput, Tuple[tf.Tensor]]rm   )rs   rt   ru   r&   r   r   rM  r   _IMAGE_CLASS_CHECKPOINTr   rO  _IMAGE_CLASS_EXPECTED_OUTPUTrk   rA   rw   rx   s   @r1   rY  rY  /  s      *+?@*.$4	 1537,0/337&*04#((
-(
 1(
 *	(

 -(
 #1(
 $(
 .(
 !(
 
=(
 A (
T	Mr2   rY  )@rv   
__future__r   collections.abcr   rT   typingr   r   r   numpynp
tensorflowr?   activations_tfr   modeling_tf_outputsr	   r
   r   modeling_tf_utilsr   r   r   r   r   r   r   tf_utilsr   r   utilsr   r   r   r   configuration_vitr   
get_loggerrs   loggerrO  rN  rP  rb  rc  r(   Layerr   r'   r   r   r   r   r   r   r  r#  r=  VIT_START_DOCSTRINGrM  rB  r(  rY  r$   r2   r1   <module>rt     s    "   ) )   / n n   3 u u ( 
		H	%  : &  8 - Yell(( Y|EM5<<-- EMPWH++ WHtHell(( H<$.U\\'' $.NH** H:N%,,$$ N4@R## @RF3&5<<%% 3&l [(U\\'' [( [(|%, %( T > c+%% +%	+%\H%,,$$ H:  JM"68T JMJMr2   