o
    Vh$                     @   s  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m	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mZmZ d	dlmZ d	dlmZmZ d	dlmZmZmZmZm Z  ddl!m"Z"m#Z# g dZ$G dd deZ%G dd deZ&G dd de Z'dee de(dee de)de)dede'fddZ*G d d! d!eZ+ed"d#ed$d%d& fd'dd(d)d*deee+ef  de)de)dede'f
d+d,Z,dS )-    )partial)AnyListOptionalUnionN)nnTensor)DeQuantStub	QuantStub   )Conv2dNormActivationSqueezeExcitation)ImageClassification   )register_modelWeightsWeightsEnum)_IMAGENET_CATEGORIES)_ovewrite_named_paramhandle_legacy_interface)_mobilenet_v3_confInvertedResidualInvertedResidualConfigMobileNet_V3_Large_WeightsMobileNetV3   )_fuse_modules_replace_relu)QuantizableMobileNetV3#MobileNet_V3_Large_QuantizedWeightsmobilenet_v3_largec                       sd   e Zd ZdZdededdf fddZdedefd	d
Zddee	 ddfddZ
 fddZ  ZS )QuantizableSqueezeExcitationr   argskwargsreturnNc                    s,   t j|d< t j|i | t j | _d S )Nscale_activation)r   Hardsigmoidsuper__init__	quantizedFloatFunctionalskip_mulselfr"   r#   	__class__ _/var/www/vscode/kcb/lib/python3.10/site-packages/torchvision/models/quantization/mobilenetv3.pyr(   !   s   
z%QuantizableSqueezeExcitation.__init__inputc                 C   s   | j | ||S N)r+   mul_scale)r-   r2   r0   r0   r1   forward&   s   z$QuantizableSqueezeExcitation.forwardis_qatc                 C   s   t | ddg|dd d S )Nfc1
activationTinplace)r   )r-   r7   r0   r0   r1   
fuse_model)   s   z'QuantizableSqueezeExcitation.fuse_modelc              	      s   | dd }t| drO|d u s|dk rOtdgtdgtjdgtjdtjdgtjdtdgtdgd}	|	 D ]\}
}||
 }||vrN|||< q>t ||||||| d S )	Nversionqconfigr   g      ?r   )dtyper   )z.scale_activation.activation_post_process.scalezFscale_activation.activation_post_process.activation_post_process.scalez3scale_activation.activation_post_process.zero_pointzKscale_activation.activation_post_process.activation_post_process.zero_pointz;scale_activation.activation_post_process.fake_quant_enabledz9scale_activation.activation_post_process.observer_enabled)gethasattrtorchtensorint32itemsr'   _load_from_state_dict)r-   
state_dictprefixlocal_metadatastrictmissing_keysunexpected_keys
error_msgsr=   default_state_dictkvfull_keyr.   r0   r1   rF   ,   s2   





z2QuantizableSqueezeExcitation._load_from_state_dictr3   )__name__
__module____qualname___versionr   r(   r   r6   r   boolr<   rF   __classcell__r0   r0   r.   r1   r!      s    r!   c                       s<   e Zd Zdededdf fddZdedefdd	Z  ZS )
QuantizableInvertedResidualr"   r#   r$   Nc                    s&   t  j|dti| tj | _d S )Nse_layer)r'   r(   r!   r   r)   r*   skip_addr,   r.   r0   r1   r(   U   s   z$QuantizableInvertedResidual.__init__xc                 C   s$   | j r| j|| |S | |S r3   )use_res_connectrZ   addblockr-   r[   r0   r0   r1   r6   Y   s   
z#QuantizableInvertedResidual.forward)rR   rS   rT   r   r(   r   r6   rW   r0   r0   r.   r1   rX   S   s    rX   c                       sT   e Zd Zdededdf fddZdedefdd	Zdd
ee ddfddZ	  Z
S )r   r"   r#   r$   Nc                    s&   t  j|i | t | _t | _dS )zq
        MobileNet V3 main class

        Args:
           Inherits args from floating point MobileNetV3
        N)r'   r(   r
   quantr	   dequantr,   r.   r0   r1   r(   a   s   zQuantizableMobileNetV3.__init__r[   c                 C   s"   |  |}| |}| |}|S r3   )r`   _forward_implra   r_   r0   r0   r1   r6   l   s   


zQuantizableMobileNetV3.forwardr7   c                 C   sv   |   D ]4}t|tu r-ddg}t|dkr$t|d tju r$|d t|||dd qt|tu r8|	| qd S )N01r   r   2Tr:   )
modulestyper   lenr   ReLUappendr   r!   r<   )r-   r7   mmodules_to_fuser0   r0   r1   r<   r   s   

z!QuantizableMobileNetV3.fuse_modelr3   )rR   rS   rT   r   r(   r   r6   r   rV   r<   rW   r0   r0   r.   r1   r   `   s     r   inverted_residual_settinglast_channelweightsprogressquantizer#   r$   c                 K   s   |d urt |dt|jd  d|jv rt |d|jd  |dd}t| |fdti|}t| |rK|jdd tj	j
||_tj	j
j|dd |d urY||j|dd	 |rhtj	j
j|dd |  |S )
Nnum_classes
categoriesbackendqnnpackr^   T)r7   r:   )rp   
check_hash)r   rh   metapopr   rX   r   r<   rB   aoquantizationget_default_qat_qconfigr>   prepare_qatload_state_dictget_state_dictconverteval)rm   rn   ro   rp   rq   r#   rt   modelr0   r0   r1   _mobilenet_v3_model}   s"   
r   c                   @   sH   e Zd Zedeeddddeddejdd	d
didddd
dZ	e	Z
dS )r   zUhttps://download.pytorch.org/models/quantized/mobilenet_v3_large_qnnpack-5bcacf28.pth   )	crop_sizeiS )r   r   ru   zUhttps://github.com/pytorch/vision/tree/main/references/classification#qat-mobilenetv3zImageNet-1KgK7A@R@gxV@)zacc@1zacc@5g-?gҍ5@z
                These weights were produced by doing Quantization Aware Training (eager mode) on top of the unquantized
                weights listed below.
            )

num_paramsmin_sizers   rt   recipeunquantized_metrics_ops
_file_size_docs)url
transformsrw   N)rR   rS   rT   r   r   r   r   r   IMAGENET1K_V1IMAGENET1K_QNNPACK_V1DEFAULTr0   r0   r0   r1   r      s*    
r   quantized_mobilenet_v3_large)name
pretrainedc                 C   s   |  ddr	tjS tjS )Nrq   F)r@   r   r   r   r   )r#   r0   r0   r1   <lambda>   s   
r   )ro   TF)ro   rp   rq   c                 K   s<   |rt nt| } tdi |\}}t||| ||fi |S )a  
    MobileNetV3 (Large) model from
    `Searching for MobileNetV3 <https://arxiv.org/abs/1905.02244>`_.

    .. note::
        Note that ``quantize = True`` returns a quantized model with 8 bit
        weights. Quantized models only support inference and run on CPUs.
        GPU inference is not yet supported.

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

    .. autoclass:: torchvision.models.quantization.MobileNet_V3_Large_QuantizedWeights
        :members:
    .. autoclass:: torchvision.models.MobileNet_V3_Large_Weights
        :members:
        :noindex:
    r    N)r    )r   r   verifyr   r   )ro   rp   rq   r#   rm   rn   r0   r0   r1   r       s   -r    )-	functoolsr   typingr   r   r   r   rB   r   r   torch.ao.quantizationr	   r
   ops.miscr   r   transforms._presetsr   _apir   r   r   _metar   _utilsr   r   mobilenetv3r   r   r   r   r   utilsr   r   __all__r!   rX   r   intrV   r   r   r    r0   r0   r0   r1   <module>   sh    5
$
