o
    ,hA                     @   s  d dl Z d dlmZ d dlmZ d dlmZmZ d dlZd dl	m
Z
 d dlm
  mZ d dlm  mZ d dlmZ ddl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 g 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&de
j dede'ddfddZ(de)de*e)e)e)e)f de)dee de'dede&fd d!Z+d"ed#d$d%Z,G d&d' d'eZ-G d(d) d)eZ.G d*d+ d+eZ/G d,d- d-eZ0e ed.e-j1fd/dd0d1dee- de'dede&fd2d3Z2e ed.e.j1fd/dd0d1dee. de'dede&fd4d5Z3e ed.e/j1fd/dd0d1dee/ de'dede&fd6d7Z4e ed.e0j1fd/dd0d1dee0 de'dede&fd8d9Z5dS ):    N)OrderedDict)partial)AnyOptional)Tensor   )ImageClassification)_log_api_usage_once   )register_modelWeightsWeightsEnum)_IMAGENET_CATEGORIES)_ovewrite_named_paramhandle_legacy_interface)	DenseNetDenseNet121_WeightsDenseNet161_WeightsDenseNet169_WeightsDenseNet201_Weightsdensenet121densenet161densenet169densenet201c                       s   e Zd Z	ddedededededdf fd	d
Zdee defddZ	dee defddZ
ejjdee defddZejjdee defddZejjdedefddZdedefddZ  ZS )_DenseLayerFnum_input_featuresgrowth_ratebn_size	drop_ratememory_efficientreturnNc                    s   t    t|| _tjdd| _tj||| dddd| _t|| | _	tjdd| _
tj|| |ddddd| _t|| _|| _d S )NTinplacer
   Fkernel_sizestridebias   r$   r%   paddingr&   )super__init__nnBatchNorm2dnorm1ReLUrelu1Conv2dconv1norm2relu2conv2floatr   r   )selfr   r   r   r   r   	__class__ V/var/www/html/scripts/venv/lib/python3.10/site-packages/torchvision/models/densenet.pyr+       s   


z_DenseLayer.__init__inputsc                 C   s&   t |d}| | | |}|S Nr
   )torchcatr2   r0   r.   )r7   r<   concated_featuresbottleneck_outputr:   r:   r;   bn_function/   s   z_DenseLayer.bn_functioninputc                 C   s   |D ]}|j r
 dS qdS )NTF)requires_grad)r7   rC   tensorr:   r:   r;   any_requires_grad5   s
   z_DenseLayer.any_requires_gradc                    s$    fdd}t j|g|R ddiS )Nc                     s
     | S N)rB   )r<   r7   r:   r;   closure=   s   
z7_DenseLayer.call_checkpoint_bottleneck.<locals>.closureuse_reentrantF)cp
checkpoint)r7   rC   rI   r:   rH   r;   call_checkpoint_bottleneck;   s   z&_DenseLayer.call_checkpoint_bottleneckc                 C      d S rG   r:   r7   rC   r:   r:   r;   forwardB      z_DenseLayer.forwardc                 C   rN   rG   r:   rO   r:   r:   r;   rP   F   rQ   c                 C   s   t |tr	|g}n|}| jr"| |r"tj rtd| |}n| 	|}| 
| | |}| jdkrAtj|| j| jd}|S )Nz%Memory Efficient not supported in JITr   )ptraining)
isinstancer   r   rF   r>   jitis_scripting	ExceptionrM   rB   r5   r4   r3   r   FdropoutrS   )r7   rC   prev_featuresrA   new_featuresr:   r:   r;   rP   L   s   



F)__name__
__module____qualname__intr6   boolr+   listr   rB   rF   r>   rU   unusedrM   _overload_methodrP   __classcell__r:   r:   r8   r;   r      s0    r   c                       sT   e Zd ZdZ	ddedededededed	d
f fddZded	efddZ	  Z
S )_DenseBlockr   F
num_layersr   r   r   r   r   r    Nc           	         sJ   t    t|D ]}t|||  ||||d}| d|d  | q	d S )N)r   r   r   r   zdenselayer%dr
   )r*   r+   ranger   
add_module)	r7   rg   r   r   r   r   r   ilayerr8   r:   r;   r+   c   s   
	
z_DenseBlock.__init__init_featuresc                 C   s6   |g}|   D ]\}}||}|| qt|dS r=   )itemsappendr>   r?   )r7   rl   featuresnamerk   r[   r:   r:   r;   rP   w   s
   z_DenseBlock.forwardr\   )r]   r^   r_   _versionr`   r6   ra   r+   r   rP   re   r:   r:   r8   r;   rf   `   s&    	rf   c                       s*   e Zd Zdededdf fddZ  ZS )_Transitionr   num_output_featuresr    Nc                    sN   t    t|| _tjdd| _tj||dddd| _tj	ddd| _
d S )NTr!   r
   Fr#   r   )r$   r%   )r*   r+   r,   r-   normr/   relur1   conv	AvgPool2dpool)r7   r   rs   r8   r:   r;   r+      s
   
z_Transition.__init__)r]   r^   r_   r`   r+   re   r:   r:   r8   r;   rr      s    "rr   c                       sp   e Zd ZdZ							dd	ed
eeeeef dedededededdf fddZde	de	fddZ
  ZS )r   aK  Densenet-BC model class, based on
    `"Densely Connected Convolutional Networks" <https://arxiv.org/pdf/1608.06993.pdf>`_.

    Args:
        growth_rate (int) - how many filters to add each layer (`k` in paper)
        block_config (list of 4 ints) - how many layers in each pooling block
        num_init_features (int) - the number of filters to learn in the first convolution layer
        bn_size (int) - multiplicative factor for number of bottle neck layers
          (i.e. bn_size * k features in the bottleneck layer)
        drop_rate (float) - dropout rate after each dense layer
        num_classes (int) - number of classification classes
        memory_efficient (bool) - If True, uses checkpointing. Much more memory efficient,
          but slower. Default: *False*. See `"paper" <https://arxiv.org/pdf/1707.06990.pdf>`_.
                    @      r     Fr   block_confignum_init_featuresr   r   num_classesr   r    Nc                    s  t    t|  ttdtjd|dddddfdt|fdtjd	d
fdtj	ddddfg| _
|}t|D ]>\}	}
t|
|||||d}| j
d|	d  | ||
|  }|	t|d krwt||d d}| j
d|	d  | |d }q9| j
dt| t||| _|  D ]5}t|tjrtj|j qt|tjrtj|jd tj|jd qt|tjrtj|jd qd S )Nconv0r'      r   Fr(   norm0relu0Tr!   pool0r
   )r$   r%   r)   )rg   r   r   r   r   r   zdenseblock%d)r   rs   ztransition%dnorm5r   )r*   r+   r	   r,   
Sequentialr   r1   r-   r/   	MaxPool2dro   	enumeraterf   ri   lenrr   Linear
classifiermodulesrT   initkaiming_normal_weight	constant_r&   )r7   r   r   r   r   r   r   r   num_featuresrj   rg   blocktransmr8   r:   r;   r+      sP   
zDenseNet.__init__xc                 C   s>   |  |}tj|dd}t|d}t|d}| |}|S )NTr!   )r
   r
   r
   )ro   rX   ru   adaptive_avg_pool2dr>   flattenr   )r7   r   ro   outr:   r:   r;   rP      s   

zDenseNet.forward)ry   rz   r   r   r   r   F)r]   r^   r_   __doc__r`   tupler6   ra   r+   r   rP   re   r:   r:   r8   r;   r      s6    	<r   modelweightsprogressr    c                 C   sl   t d}|j|dd}t| D ]}||}|r.|d|d }|| ||< ||= q| | d S )Nz]^(.*denselayer\d+\.(?:norm|relu|conv))\.((?:[12])\.(?:weight|bias|running_mean|running_var))$T)r   
check_hashr
   r   )recompileget_state_dictrb   keysmatchgroupload_state_dict)r   r   r   pattern
state_dictkeyresnew_keyr:   r:   r;   _load_state_dict   s   
r   r   r   r   kwargsc                 K   sL   |d urt |dt|jd  t| ||fi |}|d ur$t|||d |S )Nr   
categories)r   r   r   )r   r   metar   r   )r   r   r   r   r   r   r   r:   r:   r;   	_densenet   s   r   )   r   z*https://github.com/pytorch/vision/pull/116z'These weights are ported from LuaTorch.)min_sizer   recipe_docsc                	   @   B   e Zd Zedeeddi edddddid	d
ddZeZdS )r   z<https://download.pytorch.org/models/densenet121-a639ec97.pth   	crop_sizeihy ImageNet-1KgƛR@g|?5V@zacc@1zacc@5gy&1@gQ>@
num_params_metrics_ops
_file_sizeurl
transformsr   N	r]   r^   r_   r   r   r   _COMMON_METAIMAGENET1K_V1DEFAULTr:   r:   r:   r;   r     $    
r   c                	   @   r   )r   z<https://download.pytorch.org/models/densenet161-8d451a50.pthr   r   i(r   gFHS@gp=
cW@r   gx@gV-[@r   r   Nr   r:   r:   r:   r;   r     r   r   c                	   @   r   )r   z<https://download.pytorch.org/models/densenet169-b2777c0a.pthr   r   ih r   gfffffR@g$3W@r   gzG
@gvZK@r   r   Nr   r:   r:   r:   r;   r   3  r   r   c                	   @   r   )r   z<https://download.pytorch.org/models/densenet201-c1103571.pthr   r   ihc1r   gMbX9S@gHzWW@r   gDl)@gZd;WS@r   r   Nr   r:   r:   r:   r;   r   G  r   r   
pretrained)r   T)r   r   c                 K   "   t | } tddd| |fi |S )a{  Densenet-121 model from
    `Densely Connected Convolutional Networks <https://arxiv.org/abs/1608.06993>`_.

    Args:
        weights (:class:`~torchvision.models.DenseNet121_Weights`, optional): The
            pretrained weights to use. See
            :class:`~torchvision.models.DenseNet121_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.densenet.DenseNet``
            base class. Please refer to the `source code
            <https://github.com/pytorch/vision/blob/main/torchvision/models/densenet.py>`_
            for more details about this class.

    .. autoclass:: torchvision.models.DenseNet121_Weights
        :members:
    ry   rz   r   )r   verifyr   r   r   r   r:   r:   r;   r   [     
r   c                 K   r   )a{  Densenet-161 model from
    `Densely Connected Convolutional Networks <https://arxiv.org/abs/1608.06993>`_.

    Args:
        weights (:class:`~torchvision.models.DenseNet161_Weights`, optional): The
            pretrained weights to use. See
            :class:`~torchvision.models.DenseNet161_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.densenet.DenseNet``
            base class. Please refer to the `source code
            <https://github.com/pytorch/vision/blob/main/torchvision/models/densenet.py>`_
            for more details about this class.

    .. autoclass:: torchvision.models.DenseNet161_Weights
        :members:
    0   )r{   r|   $   r}   `   )r   r   r   r   r:   r:   r;   r   u  r   r   c                 K   r   )a{  Densenet-169 model from
    `Densely Connected Convolutional Networks <https://arxiv.org/abs/1608.06993>`_.

    Args:
        weights (:class:`~torchvision.models.DenseNet169_Weights`, optional): The
            pretrained weights to use. See
            :class:`~torchvision.models.DenseNet169_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.densenet.DenseNet``
            base class. Please refer to the `source code
            <https://github.com/pytorch/vision/blob/main/torchvision/models/densenet.py>`_
            for more details about this class.

    .. autoclass:: torchvision.models.DenseNet169_Weights
        :members:
    ry   )r{   r|   ry   ry   r   )r   r   r   r   r:   r:   r;   r     r   r   c                 K   r   )a{  Densenet-201 model from
    `Densely Connected Convolutional Networks <https://arxiv.org/abs/1608.06993>`_.

    Args:
        weights (:class:`~torchvision.models.DenseNet201_Weights`, optional): The
            pretrained weights to use. See
            :class:`~torchvision.models.DenseNet201_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.densenet.DenseNet``
            base class. Please refer to the `source code
            <https://github.com/pytorch/vision/blob/main/torchvision/models/densenet.py>`_
            for more details about this class.

    .. autoclass:: torchvision.models.DenseNet201_Weights
        :members:
    ry   )r{   r|   r   ry   r   )r   r   r   r   r:   r:   r;   r     r   r   )6r   collectionsr   	functoolsr   typingr   r   r>   torch.nnr,   torch.nn.functional
functionalrX   torch.utils.checkpointutilsrL   rK   r   transforms._presetsr   r	   _apir   r   r   _metar   _utilsr   r   __all__Moduler   
ModuleDictrf   r   rr   r   ra   r   r`   r   r   r   r   r   r   r   r   r   r   r   r   r:   r:   r:   r;   <module>   sp    A	U
***.