a
    áñhÿ-  ã                   @   s
  d dl 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 g d¢Zdd	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dd„ Zdd„ Zd#dd„Zd$dd„Zd%dd „Zd&d!d"„ZdS )'é    N)ÚOrderedDicté   )Úload_state_dict_from_url)ÚTensor)ÚList)ÚDenseNetÚdensenet121Údensenet169Údensenet201Údensenet161z<https://download.pytorch.org/models/densenet121-a639ec97.pthz<https://download.pytorch.org/models/densenet169-b2777c0a.pthz<https://download.pytorch.org/models/densenet201-c1103571.pthz<https://download.pytorch.org/models/densenet161-8d451a50.pth)r   r	   r
   r   c                       sf   e Zd Zd‡ fdd„	Zdd„ Zdd„ Zejjdd	„ ƒZ	ejj
d
d„ ƒZejj
dd„ ƒZdd„ Z‡  ZS )Ú_DenseLayerFc                    sÀ   t t| ƒ ¡  |  dt |¡¡f |  dtjdd�¡f |  dtj||| dddd�¡f |  d	t || ¡¡f |  d
tjdd�¡f |  dtj|| |ddddd�¡f t|ƒ| _	|| _
d S )NÚnorm1Úrelu1T©ZinplaceÚconv1r   F©Úkernel_sizeÚstrideÚbiasÚnorm2Úrelu2Úconv2é   ©r   r   Úpaddingr   )Úsuperr   Ú__init__Ú
add_moduleÚnnÚBatchNorm2dÚReLUÚConv2dÚfloatÚ	drop_rateÚmemory_efficient)ÚselfÚnum_input_featuresÚgrowth_rateÚbn_sizer#   r$   ©Ú	__class__© ú[/home/yuhw/wc/uboone-dl-vtx/venv/lib/python3.9/site-packages/torchvision/models/densenet.pyr      s"    ÿþ
þ

z_DenseLayer.__init__c                 C   s&   t  |d¡}|  |  |  |¡¡¡}|S ©Nr   )ÚtorchÚcatr   r   r   )r%   ÚinputsZconcated_featuresÚbottleneck_outputr+   r+   r,   Úbn_function&   s    z_DenseLayer.bn_functionc                 C   s   |D ]}|j r dS qdS )NTF)Zrequires_grad)r%   ÚinputZtensorr+   r+   r,   Úany_requires_grad-   s    z_DenseLayer.any_requires_gradc                    s   ‡ fdd„}t j|g|¢R Ž S )Nc                     s
   ˆ   | ¡S ©N)r2   )r0   ©r%   r+   r,   Úclosure7   s    z7_DenseLayer.call_checkpoint_bottleneck.<locals>.closure)ÚcpÚ
checkpoint)r%   r3   r7   r+   r6   r,   Úcall_checkpoint_bottleneck4   s    z&_DenseLayer.call_checkpoint_bottleneckc                 C   s   d S r5   r+   ©r%   r3   r+   r+   r,   Úforward<   s    z_DenseLayer.forwardc                 C   s   d S r5   r+   r;   r+   r+   r,   r<   A   s    c                 C   s†   t |tƒr|g}n|}| jrD|  |¡rDtj ¡ r8tdƒ‚|  |¡}n
|  	|¡}|  
|  |  |¡¡¡}| jdkr‚tj|| j| jd�}|S )Nz%Memory Efficient not supported in JITr   )ÚpÚtraining)Ú
isinstancer   r$   r4   r.   ÚjitZis_scriptingÚ	Exceptionr:   r2   r   r   r   r#   ÚFZdropoutr>   )r%   r3   Zprev_featuresr1   Únew_featuresr+   r+   r,   r<   H   s    




ÿ)F)Ú__name__Ú
__module__Ú__qualname__r   r2   r4   r.   r@   Zunusedr:   Z_overload_methodr<   Ú__classcell__r+   r+   r)   r,   r      s   


r   c                       s*   e Zd ZdZd‡ fdd„	Zdd„ Z‡  ZS )Ú_DenseBlocké   Fc           	         sN   t t| ƒ ¡  t|ƒD ]2}t|||  ||||d�}|  d|d  |¡ qd S )N)r'   r(   r#   r$   zdenselayer%dr   )r   rH   r   Úranger   r   )	r%   Ú
num_layersr&   r(   r'   r#   r$   ÚiÚlayerr)   r+   r,   r   `   s    
ûz_DenseBlock.__init__c                 C   s6   |g}|   ¡ D ]\}}||ƒ}| |¡ qt |d¡S r-   )ÚitemsÚappendr.   r/   )r%   Zinit_featuresÚfeaturesÚnamerM   rC   r+   r+   r,   r<   l   s
    z_DenseBlock.forward)F)rD   rE   rF   Ú_versionr   r<   rG   r+   r+   r)   r,   rH   ]   s   rH   c                       s   e Zd Z‡ fdd„Z‡  ZS )Ú_Transitionc              
      sj   t t| ƒ ¡  |  dt |¡¡ |  dtjdd�¡ |  dtj||dddd�¡ |  d	tjd
d
d�¡ d S )NZnormÚreluTr   Úconvr   Fr   ÚpoolrI   )r   r   )	r   rS   r   r   r   r   r    r!   Z	AvgPool2d)r%   r&   Únum_output_featuresr)   r+   r,   r   u   s    ÿz_Transition.__init__)rD   rE   rF   r   rG   r+   r+   r)   r,   rS   t   s   rS   c                       s*   e Zd ZdZd‡ fd	d
„	Zdd„ Z‡  ZS )r   aI  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   éè  Fc                    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rnt||d d�}| j
 d|	d  |¡ |d }qn| j
 dt |¡¡ t ||¡| _|  ¡ D ]r}t|tjƒ�r8tj |j¡ nNt|tjƒ�rhtj |jd¡ tj |jd¡ nt|tjƒ�rtj |jd¡ �qd S )NZconv0r   é   rI   Fr   Znorm0Zrelu0Tr   Zpool0r   )r   r   r   )rK   r&   r(   r'   r#   r$   zdenseblock%d)r&   rW   ztransition%dZnorm5r   )r   r   r   r   Ú
Sequentialr   r!   r   r    Z	MaxPool2drP   Ú	enumeraterH   r   ÚlenrS   ZLinearÚ
classifierÚmodulesr?   ÚinitZkaiming_normal_ZweightZ	constant_r   )r%   r'   Úblock_configÚnum_init_featuresr(   r#   Znum_classesr$   Znum_featuresrL   rK   ÚblockZtransÚmr)   r+   r,   r   Ž   sJ    ÿû
	úÿ
zDenseNet.__init__c                 C   s>   |   |¡}tj|dd�}t |d¡}t |d¡}|  |¡}|S )NTr   )r   r   r   )rP   rB   rT   Zadaptive_avg_pool2dr.   Úflattenre   )r%   ÚxrP   Úoutr+   r+   r,   r<   ¿   s    

zDenseNet.forward)rX   rY   r^   r_   r   r`   F)rD   rE   rF   Ú__doc__r   r<   rG   r+   r+   r)   r,   r   ~   s
     ÿ1r   c                 C   sj   t  d¡}t||d�}t| ¡ ƒD ]8}| |¡}|r"| d¡| d¡ }|| ||< ||= q"|  |¡ d S )Nz]^(.*denselayer\d+\.(?:norm|relu|conv))\.((?:[12])\.(?:weight|bias|running_mean|running_var))$)Úprogressr   rI   )ÚreÚcompiler   ÚlistÚkeysÚmatchÚgroupZload_state_dict)ÚmodelZ	model_urlrp   ÚpatternZ
state_dictÚkeyÚresZnew_keyr+   r+   r,   Ú_load_state_dictÈ   s    ÿ
r{   c                 K   s,   t |||fi |¤Ž}|r(t|t|  |ƒ |S r5   )r   r{   Ú
model_urls)Úarchr'   rh   ri   Ú
pretrainedrp   Úkwargsrw   r+   r+   r,   Ú	_densenetÚ   s    r€   FTc                 K   s   t dddd| |fi |¤ŽS )aÙ  Densenet-121 model from
    `"Densely Connected Convolutional Networks" <https://arxiv.org/pdf/1608.06993.pdf>`_

    Args:
        pretrained (bool): If True, returns a model pre-trained on ImageNet
        progress (bool): If True, displays a progress bar of the download to stderr
        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   rX   rY   r^   ©r€   ©r~   rp   r   r+   r+   r,   r   â   s    
ÿr   c                 K   s   t dddd| |fi |¤ŽS )aÙ  Densenet-161 model from
    `"Densely Connected Convolutional Networks" <https://arxiv.org/pdf/1608.06993.pdf>`_

    Args:
        pretrained (bool): If True, returns a model pre-trained on ImageNet
        progress (bool): If True, displays a progress bar of the download to stderr
        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   é0   )rZ   r[   é$   r\   é`   r�   r‚   r+   r+   r,   r   ð   s    
ÿr   c                 K   s   t dddd| |fi |¤ŽS )aÙ  Densenet-169 model from
    `"Densely Connected Convolutional Networks" <https://arxiv.org/pdf/1608.06993.pdf>`_

    Args:
        pretrained (bool): If True, returns a model pre-trained on ImageNet
        progress (bool): If True, displays a progress bar of the download to stderr
        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	   rX   )rZ   r[   rX   rX   r^   r�   r‚   r+   r+   r,   r	   þ   s    
ÿr	   c                 K   s   t dddd| |fi |¤ŽS )aÙ  Densenet-201 model from
    `"Densely Connected Convolutional Networks" <https://arxiv.org/pdf/1608.06993.pdf>`_

    Args:
        pretrained (bool): If True, returns a model pre-trained on ImageNet
        progress (bool): If True, displays a progress bar of the download to stderr
        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
   rX   )rZ   r[   rƒ   rX   r^   r�   r‚   r+   r+   r,   r
     s    
ÿr
   )FT)FT)FT)FT) rq   r.   Ztorch.nnr   Ztorch.nn.functionalZ
functionalrB   Ztorch.utils.checkpointÚutilsr9   r8   Úcollectionsr   r   r   Ztorch.jit.annotationsr   Ú__all__r|   ÚModuler   Z
ModuleDictrH   rb   rS   r   r{   r€   r   r   r	   r
   r+   r+   r+   r,   Ú<module>   s0   üG
J


