U
    5Af=                     @   sD  d 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 ddlmZmZmZmZ dd	lmZ dd
lmZmZmZmZmZ ddlmZ eeZdZ dZ!ddddgZ"dZ#dZ$d?e%e%ee% e%dddZ&e'de'dfe'e'e'e'dddZ(G dd dej)Z*G dd dej)Z+G dd dej)Z,G d d! d!ej)Z-G d"d# d#ej)Z.G d$d% d%ej)Z/G d&d' d'ej)Z0G d(d) d)ej)Z1G d*d+ d+ej)Z2G d,d- d-eZ3d.Z4d/Z5ed0e4G d1d2 d2e3Z6ed3e4G d4d5 d5e3Z7G d6d7 d7ej)Z8G d8d9 d9ej)Z9G d:d; d;ej)Z:ed<e4G d=d> d>e3Z;dS )@zPyTorch MobileViTV2 model.    )OptionalTupleUnionN)nn)BCEWithLogitsLossCrossEntropyLossMSELoss   )ACT2FN)BaseModelOutputWithNoAttention(BaseModelOutputWithPoolingAndNoAttention$ImageClassifierOutputWithNoAttentionSemanticSegmenterOutput)PreTrainedModel)add_code_sample_docstringsadd_start_docstrings%add_start_docstrings_to_model_forwardloggingreplace_return_docstrings   )MobileViTV2Configr   z$apple/mobilevitv2-1.0-imagenet1k-256      ztabby, tabby cat)valuedivisor	min_valuereturnc                 C   sF   |dk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?)maxint)r   r   r   	new_value r!   X/tmp/pip-unpacked-wheel-zw5xktn0/transformers/models/mobilevitv2/modeling_mobilevitv2.pymake_divisible<   s    r#   z-infinf)r   min_valmax_valr   c                 C   s   t |t|| S N)r   minr   r%   r&   r!   r!   r"   clipK   s    r*   c                       sT   e Zd Zdeeeeeeeeeeeef dd fddZe	j
e	j
dd	d
Z  ZS )MobileViTV2ConvLayerr   FTN)configin_channelsout_channelskernel_sizestridegroupsbiasdilationuse_normalizationuse_activationr   c                    s   t    t|d d | }|| dkr@td| d| d|| dkrbtd| d| dtj||||||||dd		| _|	rtj|d
dddd| _nd | _|
rt	|
t
rt|
 | _qt	|jt
rt|j | _q|j| _nd | _d S )Nr   r   r   zInput channels (z) are not divisible by z groups.zOutput channels (zeros)	r-   r.   r/   r0   paddingr3   r1   r2   Zpadding_modegh㈵>g?T)Znum_featuresepsZmomentumZaffineZtrack_running_stats)super__init__r   
ValueErrorr   Conv2dconvolutionZBatchNorm2dnormalization
isinstancestrr
   
activationZ
hidden_act)selfr,   r-   r.   r/   r0   r1   r2   r3   r4   r5   r7   	__class__r!   r"   r:   Q   sB    



zMobileViTV2ConvLayer.__init__featuresr   c                 C   s6   |  |}| jd k	r| |}| jd k	r2| |}|S r'   )r=   r>   rA   )rB   rF   r!   r!   r"   forward   s    




zMobileViTV2ConvLayer.forward)r   r   Fr   TT)__name__
__module____qualname__r   r   boolr   r@   r:   torchTensorrG   __classcell__r!   r!   rC   r"   r+   P   s(         
6r+   c                       sF   e Zd ZdZd
eeeeedd fddZejejddd	Z	  Z
S )MobileViTV2InvertedResidualzQ
    Inverted residual block (MobileNetv2): https://arxiv.org/abs/1801.04381
    r   N)r,   r-   r.   r0   r3   r   c              	      s   t    ttt||j d}|dkr:td| d|dkoH||k| _t|||dd| _	t|||d|||d| _
t|||dd	d
| _d S )Nr   )r   r   zInvalid stride .r   )r-   r.   r/   r	   )r-   r.   r/   r0   r1   r3   Fr-   r.   r/   r5   )r9   r:   r#   r   roundZexpand_ratior;   use_residualr+   
expand_1x1conv_3x3
reduce_1x1)rB   r,   r-   r.   r0   r3   Zexpanded_channelsrC   r!   r"   r:      s6    
   
z$MobileViTV2InvertedResidual.__init__rE   c                 C   s4   |}|  |}| |}| |}| jr0|| S |S r'   )rT   rU   rV   rS   )rB   rF   Zresidualr!   r!   r"   rG      s
    


z#MobileViTV2InvertedResidual.forward)r   rH   rI   rJ   __doc__r   r   r:   rL   rM   rG   rN   r!   r!   rC   r"   rO      s        !rO   c                       sB   e Zd Zd	eeeeedd fddZejejdddZ  Z	S )
MobileViTV2MobileNetLayerr   N)r,   r-   r.   r0   
num_stagesr   c                    sR   t    t | _t|D ]0}t||||dkr4|ndd}| j| |}qd S )Nr   r   )r-   r.   r0   )r9   r:   r   
ModuleListlayerrangerO   append)rB   r,   r-   r.   r0   rZ   ir\   rC   r!   r"   r:      s    

z"MobileViTV2MobileNetLayer.__init__rE   c                 C   s   | j D ]}||}q|S r'   r\   )rB   rF   layer_moduler!   r!   r"   rG      s    

z!MobileViTV2MobileNetLayer.forward)r   r   
rH   rI   rJ   r   r   r:   rL   rM   rG   rN   r!   r!   rC   r"   rY      s          rY   c                       s>   e Zd ZdZeedd fddZejejdddZ	  Z
S )	MobileViTV2LinearSelfAttentionaq  
    This layer applies a self-attention with linear complexity, as described in MobileViTV2 paper:
    https://arxiv.org/abs/2206.02680

    Args:
        config (`MobileVitv2Config`):
             Model configuration object
        embed_dim (`int`):
            `input_channels` from an expected input of size :math:`(batch_size, input_channels, height, width)`
    N)r,   	embed_dimr   c              	      s\   t    t||dd|  ddddd| _tj|jd| _t|||ddddd| _|| _d S )Nr   r   TF)r,   r-   r.   r2   r/   r4   r5   p)	r9   r:   r+   qkv_projr   Dropoutattn_dropoutout_projrd   )rB   r,   rd   rC   r!   r"   r:      s*    


	z'MobileViTV2LinearSelfAttention.__init__hidden_statesr   c           	      C   s   |  |}tj|d| j| jgdd\}}}tjjj|dd}| |}|| }tj|ddd}tjj	||
| }| |}|S )Nr   )Zsplit_size_or_sectionsdimrm   Trm   Zkeepdim)rg   rL   splitrd   r   
functionalZsoftmaxri   sumreluZ	expand_asrj   )	rB   rl   Zqkvquerykeyr   Zcontext_scoresZcontext_vectoroutr!   r!   r"   rG      s    
 

z&MobileViTV2LinearSelfAttention.forwardrW   r!   r!   rC   r"   rc      s   rc   c                       s@   e Zd Zd	eeeedd fddZejejdddZ	  Z
S )
MobileViTV2FFN        N)r,   rd   ffn_latent_dimffn_dropoutr   c              
      sZ   t    t|||dddddd| _t|| _t|||dddddd| _t|| _d S )Nr   TF)r,   r-   r.   r/   r0   r2   r4   r5   )	r9   r:   r+   conv1r   rh   dropout1conv2dropout2)rB   r,   rd   rz   r{   rC   r!   r"   r:     s.    


zMobileViTV2FFN.__init__rk   c                 C   s,   |  |}| |}| |}| |}|S r'   )r|   r}   r~   r   )rB   rl   r!   r!   r"   rG   9  s
    



zMobileViTV2FFN.forward)ry   rH   rI   rJ   r   r   floatr:   rL   rM   rG   rN   r!   r!   rC   r"   rx     s     rx   c                       s@   e Zd Zd	eeeedd fddZejejdddZ	  Z
S )
MobileViTV2TransformerLayerry   N)r,   rd   rz   dropoutr   c                    sb   t    tjd||jd| _t||| _tj|d| _	tjd||jd| _
t||||j| _d S )Nr   Z
num_groupsnum_channelsr8   re   )r9   r:   r   	GroupNormlayer_norm_epslayernorm_beforerc   	attentionrh   r}   layernorm_afterrx   r{   ffn)rB   r,   rd   rz   r   rC   r!   r"   r:   B  s    
z$MobileViTV2TransformerLayer.__init__rk   c                 C   s<   |  |}| |}|| }| |}| |}|| }|S r'   )r   r   r   r   )rB   rl   Zlayernorm_1_outZattention_outputZlayer_outputr!   r!   r"   rG   P  s    



z#MobileViTV2TransformerLayer.forward)ry   r   r!   r!   rC   r"   r   A  s    r   c                       s<   e Zd Zeeedd fddZejejdddZ  Z	S )MobileViTV2TransformerN)r,   n_layersd_modelr   c                    sf   t    |j}|| g| }dd |D }t | _t|D ]"}t|||| d}| j| q>d S )Nc                 S   s   g | ]}t |d  d  qS )   )r   ).0dr!   r!   r"   
<listcomp>e  s     z3MobileViTV2Transformer.__init__.<locals>.<listcomp>)rd   rz   )	r9   r:   ffn_multiplierr   r[   r\   r]   r   r^   )rB   r,   r   r   r   Zffn_dimsZ	block_idxtransformer_layerrC   r!   r"   r:   ]  s    

  zMobileViTV2Transformer.__init__rk   c                 C   s   | j D ]}||}q|S r'   r`   )rB   rl   ra   r!   r!   r"   rG   n  s    

zMobileViTV2Transformer.forwardrb   r!   r!   rC   r"   r   \  s   r   c                
       s   e Zd ZdZdeeeeeeedd fddZeje	eje	eef f dd	d
Z
eje	eef ejdddZejejdddZ  ZS )MobileViTV2Layerz=
    MobileViTV2 layer: https://arxiv.org/abs/2206.02680
    r   r   N)r,   r-   r.   attn_unit_dimn_attn_blocksr3   r0   r   c           	         s   t    |j| _|j| _|}|dkr\t||||dkr:|nd|dkrL|d ndd| _|}nd | _t||||j|d| _	t|||dddd| _
t|||d| _tjd||jd| _t|||dd	dd| _d S )
Nr   r   )r-   r.   r0   r3   )r-   r.   r/   r1   F)r-   r.   r/   r4   r5   )r   r   r   T)r9   r:   
patch_sizepatch_widthpatch_heightrO   downsampling_layerr+   Zconv_kernel_sizeconv_kxkconv_1x1r   transformerr   r   r   	layernormconv_projection)	rB   r,   r-   r.   r   r   r3   r0   Zcnn_out_dimrC   r!   r"   r:   y  sN    


zMobileViTV2Layer.__init__)feature_mapr   c                 C   sT   |j \}}}}tjj|| j| jf| j| jfd}|||| j| j d}|||ffS )N)r/   r0   rn   )shaper   rr   Zunfoldr   r   reshape)rB   r   
batch_sizer-   Z
img_heightZ	img_widthpatchesr!   r!   r"   	unfolding  s    

zMobileViTV2Layer.unfolding)r   output_sizer   c                 C   sH   |j \}}}}|||| |}tjj||| j| jf| j| jfd}|S )N)r   r/   r0   )r   r   r   rr   foldr   r   )rB   r   r   r   Zin_dimr   Z	n_patchesr   r!   r!   r"   folding  s    

zMobileViTV2Layer.foldingrE   c                 C   s`   | j r|  |}| |}| |}| |\}}| |}| |}| ||}| |}|S r'   )r   r   r   r   r   r   r   r   )rB   rF   r   r   r!   r!   r"   rG     s    





zMobileViTV2Layer.forward)r   r   r   )rH   rI   rJ   rX   r   r   r:   rL   rM   r   r   r   rG   rN   r!   r!   rC   r"   r   t  s"   
   =$r   c                       sD   e Zd Zedd fddZd
ejeeee	e
f ddd	Z  ZS )MobileViTV2EncoderNr,   r   c                    s  t    || _t | _d| _d }}|jdkr<d}d}n|jdkrJd}d}tt	d|j
 dddddd	}td|j
 dd
}td|j
 dd
}td|j
 dd
}td|j
 dd
}	td|j
 dd
}
t|||ddd}| j| t|||ddd}| j| t|||t|jd |j
 dd
|jd d}| j| |rH|d9 }t|||	t|jd |j
 dd
|jd |d}| j| |r|d9 }t||	|
t|jd |j
 dd
|jd |d}| j| d S )NFr   Tr   r       @   r)   r   r   r         i  r   )r-   r.   r0   rZ   r   r   )r-   r.   r   r   )r-   r.   r   r   r3   )r9   r:   r,   r   r[   r\   gradient_checkpointingZoutput_strider#   r*   width_multiplierrY   r^   r   Zbase_attn_unit_dimsr   )rB   r,   Zdilate_layer_4Zdilate_layer_5r3   layer_0_dimZlayer_1_dimZlayer_2_dimZlayer_3_dimZlayer_4_dimZlayer_5_dimZlayer_1Zlayer_2Zlayer_3Zlayer_4Zlayer_5rC   r!   r"   r:     s    



  zMobileViTV2Encoder.__init__FT)rl   output_hidden_statesreturn_dictr   c                 C   sx   |rdnd }t | jD ]:\}}| jr:| jr:| |j|}n||}|r||f }q|sltdd ||fD S t||dS )Nr!   c                 s   s   | ]}|d k	r|V  qd S r'   r!   )r   vr!   r!   r"   	<genexpr>M  s      z-MobileViTV2Encoder.forward.<locals>.<genexpr>)last_hidden_staterl   )	enumerater\   r   ZtrainingZ_gradient_checkpointing_func__call__tupler   )rB   rl   r   r   Zall_hidden_statesr_   ra   r!   r!   r"   rG   8  s    zMobileViTV2Encoder.forward)FT)rH   rI   rJ   r   r:   rL   rM   rK   r   r   r   rG   rN   r!   r!   rC   r"   r     s   T  
r   c                   @   sF   e Zd ZdZeZdZdZdZdgZ	e
ejejejf dddd	ZdS )
MobileViTV2PreTrainedModelz
    An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
    models.
    mobilevitv2pixel_valuesTr   N)moduler   c                 C   sj   t |tjtjfr@|jjjd| jjd |j	dk	rf|j	j
  n&t |tjrf|j	j
  |jjd dS )zInitialize the weightsry   )meanZstdNg      ?)r?   r   Linearr<   ZweightdataZnormal_r,   Zinitializer_ranger2   Zzero_	LayerNormZfill_)rB   r   r!   r!   r"   _init_weights_  s    
z(MobileViTV2PreTrainedModel._init_weights)rH   rI   rJ   rX   r   config_classZbase_model_prefixZmain_input_nameZsupports_gradient_checkpointingZ_no_split_modulesr   r   r   r<   r   r   r!   r!   r!   r"   r   S  s   r   aM  
    This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass. Use it
    as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and
    behavior.

    Parameters:
        config ([`MobileViTV2Config`]): 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.
aF  
    Args:
        pixel_values (`torch.FloatTensor` of 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.
        return_dict (`bool`, *optional*):
            Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
zYThe bare MobileViTV2 model outputting raw hidden-states without any specific head on top.c                	       st   e Zd Zdeed fddZdd Zeee	e
eededdeej ee ee eeef d
ddZ  ZS )MobileViTV2ModelT)r,   expand_outputc              	      sf   t  | || _|| _ttd|j dddddd}t||j|ddd	d	d
| _	t
|| _|   d S )Nr   r   r   r)   r   r   r	   r   Tr-   r.   r/   r0   r4   r5   )r9   r:   r,   r   r#   r*   r   r+   r   	conv_stemr   encoder	post_init)rB   r,   r   r   rC   r!   r"   r:     s&      	
zMobileViTV2Model.__init__c                 C   sF   |  D ]8\}}| jj| }t|tr|jjD ]}|j| q.qdS )zPrunes heads of the model.
        heads_to_prune: dict of {layer_num: list of heads to prune in this layer} See base class PreTrainedModel
        N)itemsr   r\   r?   r   r   r   Zprune_heads)rB   Zheads_to_pruneZlayer_indexZheadsZmobilevitv2_layerr   r!   r!   r"   _prune_heads  s
    
zMobileViTV2Model._prune_headsZvision)
checkpointoutput_typer   Zmodalityexpected_outputN)r   r   r   r   c           	      C   s   |d k	r|n| j j}|d k	r |n| j j}|d kr8td| |}| j|||d}| jrv|d }tj|ddgdd}n|d }d }|s|d k	r||fn|f}||dd   S t	|||j
d	S )
Nz You have to specify pixel_valuesr   r   r   rn   Frp   r   )r   pooler_outputrl   )r,   r   use_return_dictr;   r   r   r   rL   r   r   rl   )	rB   r   r   r   Zembedding_outputZencoder_outputsr   pooled_outputoutputr!   r!   r"   rG     s0    
zMobileViTV2Model.forward)T)NNN)rH   rI   rJ   r   rK   r:   r   r   MOBILEVITV2_INPUTS_DOCSTRINGr   _CHECKPOINT_FOR_DOCr   _CONFIG_FOR_DOC_EXPECTED_OUTPUT_SHAPEr   rL   rM   r   r   rG   rN   r!   r!   rC   r"   r     s&   
	   
r   z
    MobileViTV2 model with an image classification head on top (a linear layer on top of the pooled features), e.g. for
    ImageNet.
    c                
       sp   e Zd Zedd fddZeeeee	e
edd	eej ee eej ee eee	f dddZ  ZS )
!MobileViTV2ForImageClassificationNr   c                    s`   t  | |j| _t|| _td|j dd}|jdkrJtj||jdnt	 | _
|   d S )Nr   r   r   r   )Zin_featuresZout_features)r9   r:   
num_labelsr   r   r#   r   r   r   ZIdentity
classifierr   )rB   r,   r.   rC   r!   r"   r:     s    
z*MobileViTV2ForImageClassification.__init__)r   r   r   r   )r   r   labelsr   r   c                 C   sl  |dk	r|n| j j}| j|||d}|r.|jn|d }| |}d}|dk	r,| j jdkr| jdkrnd| j _n4| jdkr|jtj	ks|jtj
krd| j _nd| j _| j jdkrt }	| jdkr|	| | }n
|	||}nN| j jdkrt }	|	|d| j|d}n| j jdkr,t }	|	||}|s\|f|dd  }
|dk	rX|f|
 S |
S t|||jd	S )
a  
        labels (`torch.LongTensor` 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   Z
regressionZsingle_label_classificationZmulti_label_classificationrn   r   )losslogitsrl   )r,   r   r   r   r   Zproblem_typer   ZdtyperL   longr   r   Zsqueezer   viewr   r   rl   )rB   r   r   r   r   outputsr   r   r   loss_fctr   r!   r!   r"   rG     s>    



"


z)MobileViTV2ForImageClassification.forward)NNNN)rH   rI   rJ   r   r:   r   r   r   _IMAGE_CLASS_CHECKPOINTr   r   _IMAGE_CLASS_EXPECTED_OUTPUTr   rL   rM   rK   r   r   rG   rN   r!   r!   rC   r"   r     s&       
r   c                       s<   e Zd Zeeedd fddZejejdddZ  Z	S )MobileViTV2ASPPPoolingN)r,   r-   r.   r   c              	      s4   t    tjdd| _t|||ddddd| _d S )Nr   )r   Trt   r   )r9   r:   r   ZAdaptiveAvgPool2dglobal_poolr+   r   )rB   r,   r-   r.   rC   r!   r"   r:   5  s    
zMobileViTV2ASPPPooling.__init__rE   c                 C   s:   |j dd  }| |}| |}tjj||ddd}|S )Nr   bilinearFsizemodeZalign_corners)r   r   r   r   rr   interpolate)rB   rF   Zspatial_sizer!   r!   r"   rG   D  s
    

zMobileViTV2ASPPPooling.forwardrb   r!   r!   rC   r"   r   4  s   r   c                       s<   e Zd ZdZedd fddZejejdddZ  Z	S )	MobileViTV2ASPPzs
    ASPP module defined in DeepLab papers: https://arxiv.org/abs/1606.00915, https://arxiv.org/abs/1706.05587
    Nr   c                    s   t    td j dd}| jt jdkr<tdt	 | _
t ddd}| j
| | j
 fd	d
 jD  t }| j
| t d ddd| _tj jd| _d S )Nr   r   r   r	   z"Expected 3 values for atrous_ratesr   rt   rQ   c              
      s    g | ]}t  d |ddqS )r	   rt   )r-   r.   r/   r3   r5   )r+   )r   Zrater,   r-   r.   r!   r"   r   g  s   	z,MobileViTV2ASPP.__init__.<locals>.<listcomp>   re   )r9   r:   r#   r   aspp_out_channelslenZatrous_ratesr;   r   r[   convsr+   r^   extendr   projectrh   Zaspp_dropout_probr   )rB   r,   Zencoder_out_channelsZin_projectionZ
pool_layerrC   r   r"   r:   Q  s<    

	    zMobileViTV2ASPP.__init__rE   c                 C   sD   g }| j D ]}||| q
tj|dd}| |}| |}|S )Nr   ro   )r   r^   rL   catr   r   )rB   rF   ZpyramidconvZpooled_featuresr!   r!   r"   rG   }  s    


zMobileViTV2ASPP.forward
rH   rI   rJ   rX   r   r:   rL   rM   rG   rN   r!   r!   rC   r"   r   L  s   ,r   c                       s<   e Zd ZdZedd fddZejejdddZ  Z	S )	MobileViTV2DeepLabV3zB
    DeepLabv3 architecture: https://arxiv.org/abs/1706.05587
    Nr   c              	      sB   t    t|| _t|j| _t||j	|j
ddddd| _d S )Nr   FT)r-   r.   r/   r4   r5   r2   )r9   r:   r   asppr   Z	Dropout2dZclassifier_dropout_probr   r+   r   r   r   rB   r,   rC   r!   r"   r:     s    

zMobileViTV2DeepLabV3.__init__rk   c                 C   s&   |  |d }| |}| |}|S )Nrn   )r   r   r   )rB   rl   rF   r!   r!   r"   rG     s    

zMobileViTV2DeepLabV3.forwardr   r!   r!   rC   r"   r     s   r   zZ
    MobileViTV2 model with a semantic segmentation head on top, e.g. for Pascal VOC.
    c                
       sl   e Zd Zedd fddZeeeee	dd	e
ej e
ej e
e e
e eeef dddZ  ZS )
"MobileViTV2ForSemanticSegmentationNr   c                    s8   t  | |j| _t|dd| _t|| _|   d S )NF)r   )r9   r:   r   r   r   r   segmentation_headr   r   rC   r!   r"   r:     s
    
z+MobileViTV2ForSemanticSegmentation.__init__)r   r   )r   r   r   r   r   c                 C   s  |dk	r|n| j j}|dk	r |n| j j}|dk	rD| j jdkrDtd| j|d|d}|r^|jn|d }| |}d}|dk	rtj	j
||jdd ddd	}	t| j jd
}
|
|	|}|s|r|f|dd  }n|f|dd  }|dk	r|f| S |S t|||r|jndddS )a  
        labels (`torch.LongTensor` 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
        >>> import requests
        >>> import torch
        >>> from PIL import Image
        >>> from transformers import AutoImageProcessor, MobileViTV2ForSemanticSegmentation

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

        >>> image_processor = AutoImageProcessor.from_pretrained("apple/mobilevitv2-1.0-imagenet1k-256")
        >>> model = MobileViTV2ForSemanticSegmentation.from_pretrained("apple/mobilevitv2-1.0-imagenet1k-256")

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

        >>> with torch.no_grad():
        ...     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   r   r   Fr   )Zignore_indexr   )r   r   rl   Z
attentions)r,   r   r   r   r;   r   rl   r   r   rr   r   r   r   Zsemantic_loss_ignore_indexr   )rB   r   r   r   r   r   Zencoder_hidden_statesr   r   Zupsampled_logitsr   r   r!   r!   r"   rG     sB    '
   
z*MobileViTV2ForSemanticSegmentation.forward)NNNN)rH   rI   rJ   r   r:   r   r   r   r   r   r   rL   rM   rK   r   r   rG   rN   r!   r!   rC   r"   r     s   

    
r   )r   N)<rX   typingr   r   r   rL   Ztorch.utils.checkpointr   Ztorch.nnr   r   r   Zactivationsr
   Zmodeling_outputsr   r   r   r   Zmodeling_utilsr   utilsr   r   r   r   r   Zconfiguration_mobilevitv2r   Z
get_loggerrH   loggerr   r   r   r   r   r   r#   r   r*   Moduler+   rO   rY   rc   rx   r   r   r   r   r   ZMOBILEVITV2_START_DOCSTRINGr   r   r   r   r   r   r   r!   r!   r!   r"   <module>   s`   
"A1?)rmTQ=