U
    (d.B                     @   s  d dl Z d dlmZ d dlmZmZmZmZmZ d dl	Z	d dl	m
Z
mZ ddlmZmZ ddlmZ ddlmZ d	d
lmZmZ d	dlmZ d	dlmZmZmZ dddddgZG dd deZG dd dZG dd de
jZ G dd de
jZ!d.e"e#e$e$edddZ%ee e&ee e$ee!ddd Z'd!ed"Z(G d#d deZ)G d$d deZ*ed%e)j+fd&dd'd(ee) e$ee!d)d*dZ,ed%e*j+fd&dd'd(ee* e$ee!d)d+dZ-d	d,lm.Z. e.e)j+j/e*j+j/d-Z0dS )/    N)partial)AnyCallableListOptionalSequence)nnTensor   )Conv2dNormActivationSqueezeExcitation)ImageClassification)_log_api_usage_once   )WeightsEnumWeights)_IMAGENET_CATEGORIES)handle_legacy_interface_ovewrite_named_param_make_divisibleMobileNetV3MobileNet_V3_Large_WeightsMobileNet_V3_Small_Weightsmobilenet_v3_largemobilenet_v3_smallc                       s*   e Zd ZdZdeed fddZ  ZS )r   Z
DEPRECATED   )input_channelssqueeze_factorc                    sD   t || d}t j||tjd | j| _t| d t	dt
 d S )N   Zscale_activation
activationzThis SqueezeExcitation class is deprecated since 0.12 and will be removed in 0.14. Use torchvision.ops.SqueezeExcitation instead.)r   super__init__r   Hardsigmoidr    ZreludelattrwarningswarnFutureWarning)selfr   r   squeeze_channels	__class__ B/tmp/pip-unpacked-wheel-vx7f76es/torchvision/models/mobilenetv3.pyr"      s    
zSqueezeExcitation.__init__)r   )__name__
__module____qualname____doc__intr"   __classcell__r,   r,   r*   r-   r      s   r   c                
   @   s>   e Zd Zeeeeeeeeed	ddZeeedddZ	dS )InvertedResidualConfig)	r   kernelexpanded_channelsout_channelsuse_ser    stridedilation
width_multc
           
      C   sP   |  ||	| _|| _|  ||	| _|  ||	| _|| _|dk| _|| _|| _d S )NHS)	adjust_channelsr   r5   r6   r7   r8   use_hsr9   r:   )
r(   r   r5   r6   r7   r8   r    r9   r:   r;   r,   r,   r-   r"   *   s    
zInvertedResidualConfig.__init__Zchannelsr;   c                 C   s   t | | dS )Nr   )r   r?   r,   r,   r-   r=   ?   s    z&InvertedResidualConfig.adjust_channelsN)
r.   r/   r0   r2   boolstrfloatr"   staticmethodr=   r,   r,   r,   r-   r4   (   s   r4   c                       sX   e Zd Zeeejdfeedej	f edej	f d fddZ
eedddZ  ZS )	InvertedResidualr   .)cnf
norm_layerse_layerc                    s$  t    d|j  kr dks*n td|jdko>|j|jk| _g }|jrRtj	ntj
}|j|jkr|t|j|jd||d |jdkrdn|j}|t|j|j|j||j|j||d |jrt|jd d}|||j| |t|j|jd|d d tj| | _|j| _|jdk| _d S )Nr   r
   zillegal stride valuekernel_sizerF   activation_layer)rI   r9   r:   groupsrF   rJ   r   r   )r!   r"   r9   
ValueErrorr   r7   use_res_connectr>   r   	HardswishZReLUr6   appendr   r:   r5   r8   r   
SequentialblockZ_is_cn)r(   rE   rF   rG   layersrJ   r9   r)   r*   r,   r-   r"   F   sX    
    zInvertedResidual.__init__)inputreturnc                 C   s   |  |}| jr||7 }|S N)rQ   rM   )r(   rS   resultr,   r,   r-   forward~   s    
zInvertedResidual.forward)r.   r/   r0   r   SElayerr   r#   r4   r   Moduler"   r	   rW   r3   r,   r,   r*   r-   rD   D   s   8rD   c                
       sr   e Zd Zdee eeeedej	f  eedej	f  e
edd fddZeedd	d
ZeedddZ  ZS )r     N皙?.)inverted_residual_settinglast_channelnum_classesrQ   rF   dropoutkwargsrT   c              
      s  t    t|  |s tdn$t|tr<tdd |D sDtd|dkrPt}|dkrht	t
jddd}g }|d	 j}	|td
|	d
d|t
jd |D ]}
|||
| q|d j}d| }|t||d|t
jd t
j| | _t
d| _t
t
||t
jddt
j|ddt
||| _|  D ]}t|t
jrlt
jj|jdd |jdk	rt
j|j n`t|t
jt
jfrt
j |j t
j|j n.t|t
jr,t
j!|jd	d t
j|j q,dS )a.  
        MobileNet V3 main class

        Args:
            inverted_residual_setting (List[InvertedResidualConfig]): Network structure
            last_channel (int): The number of channels on the penultimate layer
            num_classes (int): Number of classes
            block (Optional[Callable[..., nn.Module]]): Module specifying inverted residual building block for mobilenet
            norm_layer (Optional[Callable[..., nn.Module]]): Module specifying the normalization layer to use
            dropout (float): The droupout probability
        z1The inverted_residual_setting should not be emptyc                 S   s   g | ]}t |tqS r,   )
isinstancer4   ).0sr,   r,   r-   
<listcomp>   s     z(MobileNetV3.__init__.<locals>.<listcomp>zDThe inverted_residual_setting should be List[InvertedResidualConfig]NgMbP?g{Gz?)ZepsZmomentumr      r
   )rI   r9   rF   rJ      r   rH   T)inplace)prh   Zfan_out)mode)"r!   r"   r   rL   ra   r   all	TypeErrorrD   r   r   ZBatchNorm2dr   rO   r   rN   r7   rP   featuresZAdaptiveAvgPool2davgpoolZLinearZDropout
classifiermodulesZConv2dinitZkaiming_normal_ZweightZbiasZzeros_Z	GroupNormZones_Znormal_)r(   r\   r]   r^   rQ   rF   r_   r`   rR   Zfirstconv_output_channelsrE   Zlastconv_input_channelsZlastconv_output_channelsmr*   r,   r-   r"      sr    







zMobileNetV3.__init__)xrT   c                 C   s.   |  |}| |}t|d}| |}|S )Nr   )rm   rn   torchflattenro   r(   rs   r,   r,   r-   _forward_impl   s
    


zMobileNetV3._forward_implc                 C   s
   |  |S rU   )rw   rv   r,   r,   r-   rW      s    zMobileNetV3.forward)rZ   NNr[   )r.   r/   r0   r   r4   r2   r   r   r   rY   rB   r   r"   r	   rw   rW   r3   r,   r,   r*   r-   r      s        [
      ?F)archr;   reduced_taildilatedr`   c                 K   s  |rdnd}|rdnd}t t|d}t tj|d}| dkr|dddddddd|ddd	d
dddd|d
ddd
dddd|d
ddddddd|dddddddd|dddddddd|dddddddd|dddddddd|dddddddd|dddddddd|dddddddd|dddddddd|dddd| ddd||d| dd| d| ddd||d| dd| d| ddd|g}	|d| }
n"| dkr|dddddddd|dddd
dddd|d
ddd
dddd|d
ddddddd|dddddddd|dddddddd|dddddddd|dddddddd|ddd d| ddd||d| dd!| d| ddd||d| dd!| d| ddd|g}	|d"| }
ntd#|  |	|
fS )$Nr
   r   )r;   r      re   FZRE@      H      (   Tx      P   r<         i  p   i     i  i   r   X   `   0      i   i@  i   zUnsupported model type )r   r4   r=   rL   )ry   r;   rz   r{   r`   Zreduce_dividerr:   Z
bneck_confr=   r\   r]   r,   r,   r-   _mobilenet_v3_conf   sL    
  
  r   )r\   r]   weightsprogressr`   rT   c                 K   sJ   |d k	rt |dt|jd  t| |f|}|d k	rF||j|d |S )Nr^   
categories)r   )r   lenmetar   Zload_state_dictZget_state_dict)r\   r]   r   r   r`   modelr,   r,   r-   _mobilenet_v3   s    r   )r   r   )Zmin_sizer   c                
   @   sn   e Zd Zedeeddedddddd	id
ddZedeedddedddddd	idddZeZ	dS )r   zChttps://download.pytorch.org/models/mobilenet_v3_large-8738ca79.pth   	crop_sizeiS ^https://github.com/pytorch/vision/tree/main/references/classification#mobilenetv3-large--smallImageNet-1Kg R@g(\V@zacc@1zacc@5zJThese weights were trained from scratch by using a simple training recipe.Z
num_paramsZrecipeZ_metricsZ_docsurlZ
transformsr   zChttps://download.pytorch.org/models/mobilenet_v3_large-5c1a4163.pth   )r   Zresize_sizezHhttps://github.com/pytorch/vision/issues/3995#new-recipe-with-reg-tuninggK7R@gNbX9$W@a/  
                These weights improve marginally upon the results of the original paper by using a modified version of
                TorchVision's `new training recipe
                <https://pytorch.org/blog/how-to-train-state-of-the-art-models-using-torchvision-latest-primitives/>`_.
            N)
r.   r/   r0   r   r   r   _COMMON_METAIMAGENET1K_V1ZIMAGENET1K_V2DEFAULTr,   r,   r,   r-   r   8  s:   
c                
   @   s>   e Zd Zedeeddedddddd	id
ddZeZdS )r   zChttps://download.pytorch.org/models/mobilenet_v3_small-047dcff4.pthr   r   i& r   r   gnP@g}?5^U@r   z}
                These weights improve upon the results of the original paper by using a simple training recipe.
            r   r   N)	r.   r/   r0   r   r   r   r   r   r   r,   r,   r,   r-   r   `  s   
Z
pretrained)r   T)r   r   )r   r   r`   rT   c                 K   s*   t | } td|\}}t||| |f|S )a  
    Constructs a large MobileNetV3 architecture from
    `Searching for MobileNetV3 <https://arxiv.org/abs/1905.02244>`__.

    Args:
        weights (:class:`~torchvision.models.MobileNet_V3_Large_Weights`, optional): The
            pretrained weights to use. See
            :class:`~torchvision.models.MobileNet_V3_Large_Weights` below for
            more details, and possible values. By default, no pre-trained
            weights are used.
        progress (bool, optional): If True, displays a progress bar of the
            download to stderr. Default is True.
        **kwargs: parameters passed to the ``torchvision.models.resnet.MobileNetV3``
            base class. Please refer to the `source code
            <https://github.com/pytorch/vision/blob/main/torchvision/models/mobilenetv3.py>`_
            for more details about this class.

    .. autoclass:: torchvision.models.MobileNet_V3_Large_Weights
        :members:
    r   )r   )r   verifyr   r   r   r   r`   r\   r]   r,   r,   r-   r   v  s    
c                 K   s*   t | } td|\}}t||| |f|S )a  
    Constructs a small MobileNetV3 architecture from
    `Searching for MobileNetV3 <https://arxiv.org/abs/1905.02244>`__.

    Args:
        weights (:class:`~torchvision.models.MobileNet_V3_Small_Weights`, optional): The
            pretrained weights to use. See
            :class:`~torchvision.models.MobileNet_V3_Small_Weights` below for
            more details, and possible values. By default, no pre-trained
            weights are used.
        progress (bool, optional): If True, displays a progress bar of the
            download to stderr. Default is True.
        **kwargs: parameters passed to the ``torchvision.models.resnet.MobileNetV3``
            base class. Please refer to the `source code
            <https://github.com/pytorch/vision/blob/main/torchvision/models/mobilenetv3.py>`_
            for more details about this class.

    .. autoclass:: torchvision.models.MobileNet_V3_Small_Weights
        :members:
    r   )r   )r   r   r   r   r   r,   r,   r-   r     s    
)
_ModelURLs)r   r   )rx   FF)1r%   	functoolsr   typingr   r   r   r   r   rt   r   r	   Zops.miscr   r   rX   Ztransforms._presetsr   utilsr   Z_apir   r   Z_metar   _utilsr   r   r   __all__r4   rY   rD   r   rA   rB   r@   r   r2   r   r   r   r   r   r   r   r   r   Z
model_urlsr,   r,   r,   r-   <module>   s   	Ak         2(      