o
    Zh0                     @  s  d Z ddlmZ ddlmZmZmZmZ ddlZ	ddl
mZ ddlmZmZmZmZ ddlmZmZmZmZ dd	lmZmZmZmZmZ dd
lmZmZ ddlm Z  ddl!m"Z" e #e$Z%dZ&dZ'g dZ(dZ)dZ*dIdJddZ+G dd dej,j-Z.G dd dej,j-Z/G dd  d ej,j-Z0G d!d" d"ej,j-Z1G d#d$ d$ej,j-Z2G d%d& d&ej,j-Z3G d'd( d(ej,j-Z4G d)d* d*ej,j-Z5G d+d, d,ej,j-Z6G d-d. d.ej,j-Z7G d/d0 d0ej,j-Z8G d1d2 d2ej,j-Z9eG d3d4 d4ej,j-Z:G d5d6 d6eZ;d7Z<d8Z=ed9e<G d:d; d;e;Z>ed<e<G d=d> d>e;eZ?G d?d@ d@ej,j-Z@G dAdB dBej,j-ZAG dCdD dDej,j-ZBedEe<G dFdG dGe;ZCg dHZDdS )KzTensorFlow 2.0 MobileViT model.    )annotations)DictOptionalTupleUnionN   )get_tf_activation)add_code_sample_docstringsadd_start_docstrings%add_start_docstrings_to_model_forwardreplace_return_docstrings)TFBaseModelOutputTFBaseModelOutputWithPooling&TFImageClassifierOutputWithNoAttention(TFSemanticSegmenterOutputWithNoAttention)TFPreTrainedModelTFSequenceClassificationLosskeraskeras_serializableunpack_inputs)
shape_liststable_softmax)logging   )MobileViTConfigr   zapple/mobilevit-small)r   i     r   ztabby, tabby catr   valueintdivisor	min_valueOptional[int]returnc                 C  sF   |du r|}t |t| |d  | | }|d|  k r||7 }t|S )a  
    Ensure that all layers have a channel count that is divisible by `divisor`. This function is taken from the
    original TensorFlow repo. It can be seen here:
    https://github.com/tensorflow/models/blob/master/research/slim/nets/mobilenet/mobilenet.py
    N   g?)maxr   )r   r   r   	new_value r%   b/var/www/auris/lib/python3.10/site-packages/transformers/models/mobilevit/modeling_tf_mobilevit.pymake_divisible@   s   r'   c                      sB   e Zd Z						dd fddZd d!ddZd"ddZ  ZS )#TFMobileViTConvLayerr   FTconfigr   in_channelsr   out_channelskernel_sizestridegroupsbiasbooldilationuse_normalizationuse_activationUnion[bool, str]r!   Nonec              
     s   t  jdi | td| jj d t|d d | }tj	|| _
|| dkr6td| d| dtjj|||d	|||d
d| _|	rRtjjdddd| _nd | _|
rtt|
trbt|
| _nt|jtrot|j| _n|j| _nd | _|| _|| _d S )N
z has backpropagation operations that are NOT supported on CPU. If you wish to train/fine-tune this model, you need a GPU or a TPUr   r"   r   zOutput channels (z) are not divisible by z groups.ZVALIDconvolution)filtersr,   stridespaddingZdilation_rater.   use_biasnamegh㈵>g?normalization)epsilonZmomentumr<   r%   )super__init__loggerwarning	__class____name__r   r   layersZZeroPadding2Dr:   
ValueErrorZConv2Dr7   ZBatchNormalizationr=   
isinstancestrr   
activation
hidden_actr*   r+   )selfr)   r*   r+   r,   r-   r.   r/   r1   r2   r3   kwargsr:   rC   r%   r&   r@   P   s<   


zTFMobileViTConvLayer.__init__features	tf.Tensortrainingc                 C  sD   |  |}| |}| jd ur| j||d}| jd ur | |}|S NrP   )r:   r7   r=   rI   )rK   rN   rP   Zpadded_featuresr%   r%   r&   call   s   




zTFMobileViTConvLayer.callNc                 C  s   | j rd S d| _ t| dd d ur2t| jj | jd d d | jg W d    n1 s-w   Y  t| dd d uret| j	drgt| j	j | j	d d d | j
g W d    d S 1 s^w   Y  d S d S d S )NTr7   r=   r<   )builtgetattrtf
name_scoper7   r<   buildr*   hasattrr=   r+   rK   input_shaper%   r%   r&   rX      s   "zTFMobileViTConvLayer.build)r   r   Fr   TT)r)   r   r*   r   r+   r   r,   r   r-   r   r.   r   r/   r0   r1   r   r2   r0   r3   r4   r!   r5   FrN   rO   rP   r0   r!   rO   NrD   
__module____qualname__r@   rS   rX   __classcell__r%   r%   rM   r&   r(   O   s    6	r(   c                      s<   e Zd ZdZ	dd fddZddddZdddZ  ZS )TFMobileViTInvertedResidualzQ
    Inverted residual block (MobileNetv2): https://arxiv.org/abs/1801.04381
    r   r)   r   r*   r   r+   r-   r1   r!   r5   c              
     s   t  jdi | ttt||j d}|dvr!td| d|dko(||k| _t|||ddd| _	t|||d|||d	d
| _
t|||dddd| _d S )Nr   )r   r"   zInvalid stride .r   
expand_1x1r*   r+   r,   r<   r   conv_3x3)r*   r+   r,   r-   r.   r1   r<   F
reduce_1x1r*   r+   r,   r3   r<   r%   )r?   r@   r'   r   roundZexpand_ratiorF   use_residualr(   re   rg   rh   )rK   r)   r*   r+   r-   r1   rL   Zexpanded_channelsrM   r%   r&   r@      s4   
z$TFMobileViTInvertedResidual.__init__FrN   rO   rP   r0   c                 C  s@   |}| j ||d}| j||d}| j||d}| jr|| S |S rQ   )re   rg   rh   rk   )rK   rN   rP   residualr%   r%   r&   rS      s
   z TFMobileViTInvertedResidual.callNc                 C  s   | j rd S d| _ t| dd d ur-t| jj | jd  W d    n1 s(w   Y  t| dd d urRt| jj | jd  W d    n1 sMw   Y  t| dd d urzt| jj | jd  W d    d S 1 ssw   Y  d S d S )NTre   rg   rh   )	rT   rU   rV   rW   re   r<   rX   rg   rh   rZ   r%   r%   r&   rX      s    "z!TFMobileViTInvertedResidual.buildr   )r)   r   r*   r   r+   r   r-   r   r1   r   r!   r5   r\   r]   r^   rD   r`   ra   __doc__r@   rS   rX   rb   r%   r%   rM   r&   rc      s    #	rc   c                      s:   e Zd Z		dd fddZddddZdddZ  ZS )TFMobileViTMobileNetLayerr   r)   r   r*   r   r+   r-   
num_stagesr!   r5   c           	        s^   t  jdi | g | _t|D ]}t||||dkr|ndd| d}| j| |}qd S )Nr   r   layer.)r*   r+   r-   r<   r%   )r?   r@   rE   rangerc   append)	rK   r)   r*   r+   r-   rq   rL   ilayerrM   r%   r&   r@      s   	z"TFMobileViTMobileNetLayer.__init__FrN   rO   rP   r0   c                 C     | j D ]}|||d}q|S rQ   rE   )rK   rN   rP   layer_moduler%   r%   r&   rS         
zTFMobileViTMobileNetLayer.callNc              	   C  j   | j rd S d| _ t| dd d ur1| jD ]}t|j |d  W d    n1 s+w   Y  qd S d S NTrE   rT   rU   rE   rV   rW   r<   rX   rK   r[   ry   r%   r%   r&   rX         
zTFMobileViTMobileNetLayer.build)r   r   )r)   r   r*   r   r+   r   r-   r   rq   r   r!   r5   r\   r]   r^   r_   r%   r%   rM   r&   rp      s    rp   c                      s>   e Zd Zd fddZdddZddddZdddZ  ZS )TFMobileViTSelfAttentionr)   r   hidden_sizer   r!   r5   c                   s   t  jd
i | ||j dkrtd| d|j d|j| _t||j | _| j| j | _tj| jtj	d}tj
|| _tjj| j|jdd| _tjj| j|jdd| _tjj| j|jd	d| _tj|j| _|| _d S )Nr   zThe hidden size z4 is not a multiple of the number of attention heads rd   dtypequery)r;   r<   keyr   r%   )r?   r@   num_attention_headsrF   r   attention_head_sizeall_head_sizerV   castZfloat32mathsqrtscaler   rE   DenseZqkv_biasr   r   r   DropoutZattention_probs_dropout_probdropoutr   )rK   r)   r   rL   r   rM   r%   r&   r@     s"   
z!TFMobileViTSelfAttention.__init__xrO   c                 C  s:   t |d }t j||d| j| jfd}t j|g ddS )Nr   shaper   r"   r   r   perm)rV   r   reshaper   r   	transpose)rK   r   
batch_sizer%   r%   r&   transpose_for_scores  s   z-TFMobileViTSelfAttention.transpose_for_scoresFhidden_statesrP   r0   c           
      C  s   t |d }| | |}| | |}| | |}t j||dd}|| j }t|dd}| j	||d}t ||}	t j
|	g dd}	t j|	|d| jfd	}	|	S )
Nr   T)Ztranspose_br   ZaxisrR   r   r   r   )rV   r   r   r   r   r   matmulr   r   r   r   r   r   )
rK   r   rP   r   Z	key_layerZvalue_layerZquery_layerZattention_scoresZattention_probsZcontext_layerr%   r%   r&   rS     s   
zTFMobileViTSelfAttention.callNc                 C  s  | j rd S d| _ t| dd d ur1t| jj | jd d | jg W d    n1 s,w   Y  t| dd d urZt| jj | jd d | jg W d    n1 sUw   Y  t| dd d urt| j	j | j	d d | jg W d    d S 1 sw   Y  d S d S )NTr   r   r   )
rT   rU   rV   rW   r   r<   rX   r   r   r   rZ   r%   r%   r&   rX   7  s    "zTFMobileViTSelfAttention.buildr)   r   r   r   r!   r5   )r   rO   r!   rO   r\   r   rO   rP   r0   r!   rO   r^   )rD   r`   ra   r@   r   rS   rX   rb   r%   r%   rM   r&   r     s
    
r   c                      s4   e Zd Zd fddZddddZdddZ  ZS )TFMobileViTSelfOutputr)   r   r   r   r!   r5   c                   s>   t  jdi | tjj|dd| _tj|j| _|| _	d S Ndenser<   r%   )
r?   r@   r   rE   r   r   r   hidden_dropout_probr   r   rK   r)   r   rL   rM   r%   r&   r@   G     
zTFMobileViTSelfOutput.__init__Fr   rO   rP   r0   c                 C  s   |  |}| j||d}|S rQ   r   r   )rK   r   rP   r%   r%   r&   rS   M  rz   zTFMobileViTSelfOutput.callNc                 C  l   | j rd S d| _ t| dd d ur4t| jj | jd d | jg W d    d S 1 s-w   Y  d S d S NTr   rT   rU   rV   rW   r   r<   rX   r   rZ   r%   r%   r&   rX   R     "zTFMobileViTSelfOutput.buildr   r\   r   r^   r_   r%   r%   rM   r&   r   F  s    r   c                      s<   e Zd Zd fddZd	d
 ZddddZdddZ  ZS )TFMobileViTAttentionr)   r   r   r   r!   r5   c                   s6   t  jdi | t||dd| _t||dd| _d S )N	attentionr   outputr%   )r?   r@   r   r   r   dense_outputr   rM   r%   r&   r@   \  s   zTFMobileViTAttention.__init__c                 C     t r^   NotImplementedError)rK   Zheadsr%   r%   r&   prune_headsa  s   z TFMobileViTAttention.prune_headsFr   rO   rP   r0   c                 C  s    | j ||d}| j||d}|S rQ   )r   r   )rK   r   rP   Zself_outputsattention_outputr%   r%   r&   rS   d  s   zTFMobileViTAttention.callNc                 C     | j rd S d| _ t| dd d ur-t| jj | jd  W d    n1 s(w   Y  t| dd d urUt| jj | jd  W d    d S 1 sNw   Y  d S d S )NTr   r   )rT   rU   rV   rW   r   r<   rX   r   rZ   r%   r%   r&   rX   i     "zTFMobileViTAttention.buildr   r\   r   r^   )rD   r`   ra   r@   r   rS   rX   rb   r%   r%   rM   r&   r   [  s
    r   c                      s2   e Zd Zd fdd	ZdddZdddZ  ZS )TFMobileViTIntermediater)   r   r   r   intermediate_sizer!   r5   c                   sP   t  jdi | tjj|dd| _t|jtrt	|j| _
n|j| _
|| _d S r   )r?   r@   r   rE   r   r   rG   rJ   rH   r   intermediate_act_fnr   rK   r)   r   r   rL   rM   r%   r&   r@   v  s   
z TFMobileViTIntermediate.__init__r   rO   c                 C  s   |  |}| |}|S r^   )r   r   )rK   r   r%   r%   r&   rS     s   

zTFMobileViTIntermediate.callNc                 C  r   r   r   rZ   r%   r%   r&   rX     r   zTFMobileViTIntermediate.buildr)   r   r   r   r   r   r!   r5   )r   rO   r!   rO   r^   r_   r%   r%   rM   r&   r   u  s    
	r   c                      s4   e Zd Zd fdd	ZddddZdddZ  ZS )TFMobileViTOutputr)   r   r   r   r   r!   r5   c                   s>   t  jdi | tjj|dd| _tj|j| _|| _	d S r   )
r?   r@   r   rE   r   r   r   r   r   r   r   rM   r%   r&   r@     r   zTFMobileViTOutput.__init__Fr   rO   input_tensorrP   r0   c                 C  s$   |  |}| j||d}|| }|S rQ   r   )rK   r   r   rP   r%   r%   r&   rS     s   
zTFMobileViTOutput.callNc                 C  r   r   )rT   rU   rV   rW   r   r<   rX   r   rZ   r%   r%   r&   rX     r   zTFMobileViTOutput.buildr   r\   )r   rO   r   rO   rP   r0   r!   rO   r^   r_   r%   r%   rM   r&   r     s    r   c                      4   e Zd Zd fdd	ZddddZdddZ  ZS )TFMobileViTTransformerLayerr)   r   r   r   r   r!   r5   c                   sx   t  jdi | t||dd| _t|||dd| _t|||dd| _tj	j
|jdd| _tj	j
|jdd| _|| _d S )	Nr   r   intermediater   layernorm_beforer>   r<   layernorm_afterr%   )r?   r@   r   r   r   r   r   mobilevit_outputr   rE   LayerNormalizationlayer_norm_epsr   r   r   r   rM   r%   r&   r@     s   
z$TFMobileViTTransformerLayer.__init__Fr   rO   rP   r0   c                 C  sD   | j | ||d}|| }| |}| |}| j|||d}|S rQ   )r   r   r   r   r   )rK   r   rP   r   Zlayer_outputr%   r%   r&   rS     s   

z TFMobileViTTransformerLayer.callNc                 C  s  | j rd S d| _ t| dd d ur-t| jj | jd  W d    n1 s(w   Y  t| dd d urRt| jj | jd  W d    n1 sMw   Y  t| dd d urwt| jj | jd  W d    n1 srw   Y  t| dd d urt| j	j | j	d d | j
g W d    n1 sw   Y  t| dd d urt| jj | jd d | j
g W d    d S 1 sw   Y  d S d S )NTr   r   r   r   r   )rT   rU   rV   rW   r   r<   rX   r   r   r   r   r   rZ   r%   r%   r&   rX     s0   "z!TFMobileViTTransformerLayer.buildr   r\   r   r^   r_   r%   r%   rM   r&   r     s    		r   c                      r   )TFMobileViTTransformerr)   r   r   r   rq   r!   r5   c                   sV   t  jdi | g | _t|D ]}t||t||j d| d}| j| qd S )Nrr   )r   r   r<   r%   )r?   r@   rE   rs   r   r   Z	mlp_ratiort   )rK   r)   r   rq   rL   ru   Ztransformer_layerrM   r%   r&   r@     s   zTFMobileViTTransformer.__init__Fr   rO   rP   r0   c                 C  rw   rQ   rx   )rK   r   rP   ry   r%   r%   r&   rS     rz   zTFMobileViTTransformer.callNc              	   C  r{   r|   r}   r~   r%   r%   r&   rX     r   zTFMobileViTTransformer.build)r)   r   r   r   rq   r   r!   r5   r\   r   r^   r_   r%   r%   rM   r&   r     s    r   c                      sP   e Zd ZdZ	d"d# fddZd$ddZd%ddZd&d'ddZd(d d!Z  Z	S ))TFMobileViTLayerz;
    MobileViT block: https://arxiv.org/abs/2110.02178
    r   r)   r   r*   r   r+   r-   r   rq   r1   r!   r5   c           	   	     s   t  jdi | |j| _|j| _|dkr1t||||dkr|nd|dkr(|d nddd| _|}nd | _t||||jdd| _	t|||ddddd	| _
t|||d
d| _tjj|jdd| _t|||ddd| _t|d| ||jdd| _|| _d S )Nr"   r   downsampling_layer)r*   r+   r-   r1   r<   conv_kxkrf   Fconv_1x1)r*   r+   r,   r2   r3   r<   transformer)r   rq   r<   	layernormr   conv_projectionfusionr%   )r?   r@   Z
patch_sizepatch_widthpatch_heightrc   r   r(   Zconv_kernel_sizer   r   r   r   r   rE   r   r   r   r   r   r   )	rK   r)   r*   r+   r-   r   rq   r1   rL   rM   r%   r&   r@     sZ   


zTFMobileViTLayer.__init__rN   rO   Tuple[tf.Tensor, Dict]c                 C  sf  | j | j}}t|| d}t|d }t|d }t|d }t|d }ttj|| | d}	ttj|| | d}
|
|kpN|	|k}|r\tjj||	|
fdd}|
| }|	| }|| }t	|g d}t
||| | |||f}t	|g d	}t
|||||f}t	|g d
}t
||| ||f}||f||||||d}||fS )NZint32r   r   r"   r   bilinearsizemethodr   r   r   r"   r   r   r   r"   r   )	orig_sizer   channelsinterpolatenum_patchesnum_patches_widthnum_patches_height)r   r   rV   r   r   r   ceilimageresizer   r   )rK   rN   r   r   
patch_arear   Zorig_heightZ
orig_widthr   Z
new_heightZ	new_widthr   num_patch_widthnum_patch_heightr   patches	info_dictr%   r%   r&   	unfolding.  s>   	zTFMobileViTLayer.unfoldingr   r   r   c                 C  s   | j | j}}t|| }|d }|d }|d }|d }	|d }
t||||df}tj|dd}t||| |	 |
||f}tj|d	d}t||||	| |
| f}tj|d
d}|d rktjj||d dd}|S )Nr   r   r   r   r   r   r   r   r   r   r"   r   r   r   r   r   r   )r   r   r   rV   r   r   r   r   )rK   r   r   r   r   r   r   r   r   r   r   rN   r%   r%   r&   foldingZ  s(   zTFMobileViTLayer.foldingFrP   r0   c                 C  s   | j r
| j ||d}|}| j||d}| j||d}| |\}}| j||d}| |}| ||}| j||d}| jt	j
||gdd|d}|S )NrR   r   r   )r   r   r   r   r   r   r   r   r   rV   concat)rK   rN   rP   rl   r   r   r%   r%   r&   rS   v  s   
zTFMobileViTLayer.callNc                 C  s,  | j rd S d| _ t| dd d ur-t| jj | jd  W d    n1 s(w   Y  t| dd d urRt| jj | jd  W d    n1 sMw   Y  t| dd d urwt| jj | jd  W d    n1 srw   Y  t| dd d urt| j	j | j	d d | j
g W d    n1 sw   Y  t| dd d urt| jj | jd  W d    n1 sw   Y  t| dd d urt| jj | jd  W d    n1 sw   Y  t| dd d urt| jj | jd  W d    d S 1 sw   Y  d S d S )	NTr   r   r   r   r   r   r   )rT   rU   rV   rW   r   r<   rX   r   r   r   r   r   r   r   rZ   r%   r%   r&   rX     s@   $zTFMobileViTLayer.buildrm   )r)   r   r*   r   r+   r   r-   r   r   r   rq   r   r1   r   r!   r5   )rN   rO   r!   r   )r   rO   r   r   r!   rO   r\   r]   r^   )
rD   r`   ra   ro   r@   r   r   rS   rX   rb   r%   r%   rM   r&   r     s    
A
,r   c                      s:   e Zd Zd fddZ			ddddZdddZ  ZS )TFMobileViTEncoderr)   r   r!   r5   c              
     s`  t  jdi | || _g | _d }}|jdkrd}d}n|jdkr$d}d}t||jd |jd dddd}| j| t||jd |jd	 d	d
dd}| j| t||jd	 |jd
 d	|j	d d	dd}| j| |rr|d	9 }t||jd
 |jd d	|j	d d|dd}	| j|	 |r|d	9 }t||jd |jd d	|j	d	 d
|dd}
| j|
 d S )NFr   T   r   r   zlayer.0)r*   r+   r-   rq   r<   r"   r   zlayer.1zlayer.2)r*   r+   r-   r   rq   r<      zlayer.3)r*   r+   r-   r   rq   r1   r<      zlayer.4r%   )
r?   r@   r)   rE   Zoutput_striderp   neck_hidden_sizesrt   r   Zhidden_sizes)rK   r)   rL   Zdilate_layer_4Zdilate_layer_5r1   Zlayer_1Zlayer_2Zlayer_3Zlayer_4Zlayer_5rM   r%   r&   r@     s   

	

zTFMobileViTEncoder.__init__FTr   rO   output_hidden_statesr0   return_dictrP   Union[tuple, TFBaseModelOutput]c                 C  s`   |rdnd }t | jD ]\}}|||d}|r||f }q|s*tdd ||fD S t||dS )Nr%   rR   c                 s  s    | ]	}|d ur|V  qd S r^   r%   ).0vr%   r%   r&   	<genexpr>	  s    z*TFMobileViTEncoder.call.<locals>.<genexpr>)last_hidden_stater   )	enumeraterE   tupler   )rK   r   r   r   rP   Zall_hidden_statesru   ry   r%   r%   r&   rS     s   
zTFMobileViTEncoder.callNc              	   C  r{   r|   r}   r~   r%   r%   r&   rX     r   zTFMobileViTEncoder.buildr)   r   r!   r5   )FTF)
r   rO   r   r0   r   r0   rP   r0   r!   r   r^   r_   r%   r%   rM   r&   r     s    Qr   c                      sN   e Zd ZeZdd fddZdd	 Ze	
	
	
	ddddZdddZ	  Z
S )TFMobileViTMainLayerTr)   r   expand_outputr0   c                   s   t  jdi | || _|| _t||j|jd dddd| _t|dd| _	| jr8t||jd |jd	 d
dd| _
tjjddd| _d S )Nr   r   r"   	conv_stem)r*   r+   r,   r-   r<   encoderr   r      r   conv_1x1_exprf   Zchannels_firstpooler)Zdata_formatr<   r%   )r?   r@   r)   r   r(   Znum_channelsr   r   r   r   r   r   rE   GlobalAveragePooling2Dr   )rK   r)   r   rL   rM   r%   r&   r@     s*   	zTFMobileViTMainLayer.__init__c                 C  r   )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   )rK   Zheads_to_pruner%   r%   r&   _prune_heads6  s   z!TFMobileViTMainLayer._prune_headsNFpixel_valuestf.Tensor | Noner   Optional[bool]r   rP   r!   5Union[Tuple[tf.Tensor], TFBaseModelOutputWithPooling]c                 C  s<  |d ur|n| j j}|d ur|n| j j}tj|dd}| j||d}| j||||d}| jrD| |d }tj|g dd}| 	|}n|d }tj|g dd}d }|s|d ur]||fn|f}	| js{|dd  }
t
dd	 |
d D }
|
f}
|	|
 S |	|dd   S |rt
d
d	 |d D }t|||r|dS |jdS )Nr   r   rR   r   r   rP   r   r   r   c                 S     g | ]	}t j|d dqS r   r   rV   r   r   hr%   r%   r&   
<listcomp>j      z-TFMobileViTMainLayer.call.<locals>.<listcomp>c                 S  r  r	  r
  r  r%   r%   r&   r  s  r  )r   pooler_outputr   )r)   r   use_return_dictrV   r   r   r   r   r   r   r   r   r   )rK   r  r   r   rP   Zembedding_outputZencoder_outputsr   pooled_outputr   Zremaining_encoder_outputsr   r%   r%   r&   rS   =  sD   	zTFMobileViTMainLayer.callc                 C  sF  | j rd S d| _ t| dd d ur-t| jj | jd  W d    n1 s(w   Y  t| dd d urRt| jj | jd  W d    n1 sMw   Y  t| dd d uryt| jj | jg d W d    n1 stw   Y  t| dd d urt| j	j | j	d  W d    d S 1 sw   Y  d S d S )NTr   r   r   NNNNr   )
rT   rU   rV   rW   r   r<   rX   r   r   r   rZ   r%   r%   r&   rX   {  s(   "zTFMobileViTMainLayer.buildTr)   r   r   r0   NNNF
r  r  r   r  r   r  rP   r0   r!   r  r^   )rD   r`   ra   r   config_classr@   r  r   rS   rX   rb   r%   r%   rM   r&   r     s    =r   c                   @  s   e Zd ZdZeZdZdZdS )TFMobileViTPreTrainedModelz
    An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
    models.
    	mobilevitr  N)rD   r`   ra   ro   r   r  Zbase_model_prefixZmain_input_namer%   r%   r%   r&   r    s
    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>

    Parameters:
        config ([`MobileViTConfig`]): 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.
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
            [`MobileViTImageProcessor.__call__`] for details.

        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.
zWThe bare MobileViT model outputting raw hidden-states without any specific head on top.c                	      s\   e Zd Zdd fddZeeeeee	e
ded		
	
	
	ddddZdddZ  ZS )TFMobileViTModelTr)   r   r   r0   c                   s:   t  j|g|R i | || _|| _t||dd| _d S )Nr  r   r<   )r?   r@   r)   r   r   r  )rK   r)   r   inputsrL   rM   r%   r&   r@     s   zTFMobileViTModel.__init__Zvision)
checkpointoutput_typer  Zmodalityexpected_outputNFr  r  r   r  r   rP   r!   r  c                 C  s   | j ||||d}|S rQ   )r  )rK   r  r   r   rP   r   r%   r%   r&   rS     s   zTFMobileViTModel.callc                 C  sd   | j rd S d| _ t| dd d ur0t| jj | jd  W d    d S 1 s)w   Y  d S d S )NTr  )rT   rU   rV   rW   r  r<   rX   rZ   r%   r%   r&   rX     s   "zTFMobileViTModel.buildr  r  r  r  r^   )rD   r`   ra   r@   r   r   MOBILEVIT_INPUTS_DOCSTRINGr	   _CHECKPOINT_FOR_DOCr   _CONFIG_FOR_DOC_EXPECTED_OUTPUT_SHAPErS   rX   rb   r%   r%   rM   r&   r    s"    	
r  z
    MobileViT model with an image classification head on top (a linear layer on top of the pooled features), e.g. for
    ImageNet.
    c                      sZ   e Zd Zd fddZeeeeee	e
ed						ddddZdddZ  ZS )!TFMobileViTForImageClassificationr)   r   r!   r5   c                   sn   t  j|g|R i | |j| _t|dd| _tj|j| _	|jdkr.tjj
|jddntj| _|| _d S )Nr  r   r   
classifier)r?   r@   
num_labelsr   r  r   rE   r   classifier_dropout_probr   r   rV   identityr%  r)   )rK   r)   r  rL   rM   r%   r&   r@     s    
z*TFMobileViTForImageClassification.__init__)r  r  r  r  NFr  r  r   r  labelsr   rP   4Union[tuple, TFImageClassifierOutputWithNoAttention]c                 C  s   |dur|n| j j}| j||||d}|r|jn|d }| | j||d}|du r,dn| j||d}	|sI|f|dd  }
|	durG|	f|
 S |
S t|	||jdS )a  
        labels (`tf.Tensor` 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).
        Nr  r   rR   )r)  logitsr"   lossr+  r   )	r)   r  r  r  r%  r   hf_compute_lossr   r   )rK   r  r   r)  r   rP   outputsr  r+  r-  r   r%   r%   r&   rS     s   z&TFMobileViTForImageClassification.callc                 C  s   | j rd S d| _ t| dd d ur-t| jj | jd  W d    n1 s(w   Y  t| dd d urbt| jdrdt| jj | jd d | j	j
d g W d    d S 1 s[w   Y  d S d S d S )NTr  r%  r<   r   )rT   rU   rV   rW   r  r<   rX   rY   r%  r)   r   rZ   r%   r%   r&   rX   5  s   "z'TFMobileViTForImageClassification.buildr   NNNNF)r  r  r   r  r)  r  r   r  rP   r  r!   r*  r^   )rD   r`   ra   r@   r   r   r   r	   _IMAGE_CLASS_CHECKPOINTr   r"  _IMAGE_CLASS_EXPECTED_OUTPUTrS   rX   rb   r%   r%   rM   r&   r$    s"    r$  c                      r   )TFMobileViTASPPPoolingr)   r   r*   r   r+   r!   r5   c              
     sB   t  jdi | tjjddd| _t|||dddddd| _d S )	NTglobal_pool)Zkeepdimsr<   r   relur   )r*   r+   r,   r-   r2   r3   r<   r%   )r?   r@   r   rE   r  r4  r(   r   )rK   r)   r*   r+   rL   rM   r%   r&   r@   C  s   zTFMobileViTASPPPooling.__init__FrN   rO   rP   r0   c                 C  s>   t |dd }| |}| j||d}tjj||dd}|S )Nr   r   rR   r   r   )r   r4  r   rV   r   r   )rK   rN   rP   Zspatial_sizer%   r%   r&   rS   S  s
   
zTFMobileViTASPPPooling.callNc                 C  s   | j rd S d| _ t| dd d ur/t| jj | jg d W d    n1 s*w   Y  t| dd d urWt| jj | jd  W d    d S 1 sPw   Y  d S d S )NTr4  r  r   )rT   rU   rV   rW   r4  r<   rX   r   rZ   r%   r%   r&   rX   Z  s   "zTFMobileViTASPPPooling.build)r)   r   r*   r   r+   r   r!   r5   r\   r]   r^   r_   r%   r%   rM   r&   r3  B  s    r3  c                      8   e Zd ZdZd fddZddddZdddZ  ZS )TFMobileViTASPPzs
    ASPP module defined in DeepLab papers: https://arxiv.org/abs/1606.00915, https://arxiv.org/abs/1706.05587
    r)   r   r!   r5   c                   s   t  jdi |  jd  jt jdkrtdg | _t dddd}| j	| | j
 fdd	t jD  t d
t jd  d}| j	| t d dddd| _tj j| _d S )Nr   z"Expected 3 values for atrous_ratesr   r5  zconvs.0ri   c                   s0   g | ]\}}t  d |dd|d  dqS )r   r5  convs.r   )r*   r+   r,   r1   r3   r<   )r(   )r   ru   Zrater)   r*   r+   r%   r&   r    s    
z,TFMobileViTASPP.__init__.<locals>.<listcomp>r9  r   r   projectr%   )r?   r@   r   aspp_out_channelslenZatrous_ratesrF   convsr(   rt   extendr   r3  r;  r   rE   r   Zaspp_dropout_probr   )rK   r)   rL   Zin_projectionZ
pool_layerrM   r:  r&   r@   k  sB   

	zTFMobileViTASPP.__init__FrN   rO   rP   r0   c                 C  sb   t j|g dd}g }| jD ]}||||d qt j|dd}| j||d}| j||d}|S )Nr   r   rR   r   r   )rV   r   r>  rt   r   r;  r   )rK   rN   rP   ZpyramidconvZpooled_featuresr%   r%   r&   rS     s   
zTFMobileViTASPP.callNc              	   C  s   | j rd S d| _ t| dd d ur-t| jj | jd  W d    n1 s(w   Y  t| dd d urV| jD ]}t|j |d  W d    n1 sPw   Y  q8d S d S )NTr;  r>  )rT   rU   rV   rW   r;  r<   rX   r>  )rK   r[   r@  r%   r%   r&   rX     s   
zTFMobileViTASPP.buildr   r\   r]   r^   rn   r%   r%   rM   r&   r7  f  s
    4r7  c                      r6  )TFMobileViTDeepLabV3zB
    DeepLabv3 architecture: https://arxiv.org/abs/1706.05587
    r)   r   r!   r5   c              
     sR   t  jdi | t|dd| _tj|j| _t	||j
|jdddddd| _d S )	Nasppr   r   FTr%  )r*   r+   r,   r2   r3   r/   r<   r%   )r?   r@   r7  rB  r   rE   r   r'  r   r(   r<  r&  r%  rK   r)   rL   rM   r%   r&   r@     s   zTFMobileViTDeepLabV3.__init__Fr   rO   rP   r0   c                 C  s2   | j |d |d}| j||d}| j||d}|S )Nr   rR   )rB  r   r%  )rK   r   rP   rN   r%   r%   r&   rS     s   zTFMobileViTDeepLabV3.callNc                 C  r   )NTrB  r%  )rT   rU   rV   rW   rB  r<   rX   r%  rZ   r%   r%   r&   rX     r   zTFMobileViTDeepLabV3.buildr   r\   r   r^   rn   r%   r%   rM   r&   rA    s
    rA  zX
    MobileViT model with a semantic segmentation head on top, e.g. for Pascal VOC.
    c                      s^   e Zd Zd fddZdd Zeeeee	e
d		
	
	
	
	ddddZdddZ  ZS )"TFMobileViTForSemanticSegmentationr)   r   r!   r5   c                   s>   t  j|fi | |j| _t|ddd| _t|dd| _d S )NFr  r  segmentation_headr   )r?   r@   r&  r   r  rA  rE  rC  rM   r%   r&   r@     s   z+TFMobileViTForSemanticSegmentation.__init__c                   sJ   t |dd  }tjj||dd}tjjddd  fdd}|||S )	Nr   r   r   Tnone)Zfrom_logitsZ	reductionc                   sJ    | |}t j| jjk|jd}|| }t |t | }t |dS )Nr   rm   )rV   r   r)   Zsemantic_loss_ignore_indexr   Z
reduce_sumr   )realpredZunmasked_lossmaskmasked_lossZreduced_masked_lossZloss_fctrK   r%   r&   rJ    s
   
zGTFMobileViTForSemanticSegmentation.hf_compute_loss.<locals>.masked_loss)r   rV   r   r   r   ZlossesZSparseCategoricalCrossentropy)rK   r+  r)  Zlabel_interp_shapeZupsampled_logitsrJ  r%   rK  r&   r.    s
   
	z2TFMobileViTForSemanticSegmentation.hf_compute_loss)r  r  NFr  r  r)  r   r  r   rP   r0   6Union[tuple, TFSemanticSegmenterOutputWithNoAttention]c                 C  s  |dur|n| j j}|dur|n| j j}|dur"| j jdks"td| j|d||d}|r0|jn|d }| j||d}d}	|durH| j||d}	t	j
|g dd	}|ss|r_|f|dd  }
n	|f|d
d  }
|	durq|	f|
 S |
S t|	||r}|jdS ddS )aK  
        labels (`tf.Tensor` of shape `(batch_size, height, width)`, *optional*):
            Ground truth semantic segmentation maps for computing the loss. Indices should be in `[0, ...,
            config.num_labels - 1]`. If `config.num_labels > 1`, a classification loss is computed (Cross-Entropy).

        Returns:

        Examples:

        ```python
        >>> from transformers import AutoImageProcessor, TFMobileViTForSemanticSegmentation
        >>> from PIL import Image
        >>> import requests

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

        >>> image_processor = AutoImageProcessor.from_pretrained("apple/deeplabv3-mobilevit-small")
        >>> model = TFMobileViTForSemanticSegmentation.from_pretrained("apple/deeplabv3-mobilevit-small")

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

        >>> outputs = model(**inputs)

        >>> # logits are of shape (batch_size, num_labels, height, width)
        >>> logits = outputs.logits
        ```Nr   z/The number of labels should be greater than oneTr  rR   )r+  r)  r   r   r"   r,  )r)   r   r  r&  rF   r  r   rE  r.  rV   r   r   )rK   r  r)  r   r   rP   r/  Zencoder_hidden_statesr+  r-  r   r%   r%   r&   rS     s:   'z'TFMobileViTForSemanticSegmentation.callc                 C  r   )NTr  rE  )rT   rU   rV   rW   r  r<   rX   rE  rZ   r%   r%   r&   rX   Q  r   z(TFMobileViTForSemanticSegmentation.buildr   r0  )r  r  r)  r  r   r  r   r  rP   r0   r!   rL  r^   )rD   r`   ra   r@   r.  r   r   r   r   r   r"  rS   rX   rb   r%   r%   rM   r&   rD    s    
KrD  )r$  rD  r  r  )r   N)r   r   r   r   r   r    r!   r   )Ero   
__future__r   typingr   r   r   r   Z
tensorflowrV   Zactivations_tfr   Z
file_utilsr	   r
   r   r   Zmodeling_tf_outputsr   r   r   r   Zmodeling_tf_utilsr   r   r   r   r   Ztf_utilsr   r   utilsr   Zconfiguration_mobilevitr   Z
get_loggerrD   rA   r"  r!  r#  r1  r2  r'   rE   ZLayerr(   rc   rp   r   r   r   r   r   r   r   r   r   r   r  ZMOBILEVIT_START_DOCSTRINGr   r  r$  r3  r7  rA  rD  __all__r%   r%   r%   r&   <module>   sn   
M@'C( Cmu)$B$S(v