
    khA                        d dl Z d dlmZ 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 d dlmc mZ d dlmc 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ejD                        Z# G d dejH                        Z% G d dejL                        Z' G d dejD                        Z(dejD                  dede)ddfdZ*de+de	e+e+e+e+f   de+dee   de)dede(fdZ,d ed!d"d#Z- G d$ d%e      Z. G d& d'e      Z/ G d( d)e      Z0 G d* d+e      Z1 e        e d,e.jd                  f-      dd.d/dee.   de)dede(fd0              Z3 e        e d,e/jd                  f-      dd.d/dee/   de)dede(fd1              Z4 e        e d,e0jd                  f-      dd.d/dee0   de)dede(fd2              Z5 e        e d,e1jd                  f-      dd.d/dee1   de)dede(fd3              Z6y)4    N)OrderedDict)partial)AnyListOptionalTuple)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                   J    e Zd Z	 ddedededededdf fdZd	ee   defd
Z	dee   defdZ
ej                  j                  dee   defd       Zej                  j                  dee   defd       Zej                  j                  dedefd       ZdedefdZ xZS )_DenseLayernum_input_featuresgrowth_ratebn_size	drop_ratememory_efficientreturnNc                    t         |           t        j                  |      | _        t        j
                  d      | _        t        j                  |||z  ddd      | _        t        j                  ||z        | _	        t        j
                  d      | _
        t        j                  ||z  |dddd      | _        t        |      | _        || _        y )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__s         W/var/www/teggl/fontify/venv/lib/python3.12/site-packages/torchvision/models/densenet.pyr0   z_DenseLayer.__init__    s     	^^$67
WWT*
YY17[3HVW`ahmn
^^Gk$9:
WWT*
YYw4kqYZdelqr
y) 0    inputsc                     t        j                  |d      }| j                  | j                  | j	                  |                  }|S Nr   )torchcatr7   r5   r3   )r<   r@   concated_featuresbottleneck_outputs       r>   bn_functionz_DenseLayer.bn_function/   s;    !IIfa0 JJtzz$**=N2O'PQ  r?   inputc                 .    |D ]  }|j                   s y y)NTF)requires_grad)r<   rH   tensors      r>   any_requires_gradz_DenseLayer.any_requires_grad5   s"     	F##	 r?   c                 @      fd}t        j                  |g|ddiS )Nc                  &    j                  |       S N)rG   )r@   r<   s    r>   closurez7_DenseLayer.call_checkpoint_bottleneck.<locals>.closure=   s    ##F++r?   use_reentrantF)cp
checkpoint)r<   rH   rP   s   `  r>   call_checkpoint_bottleneckz&_DenseLayer.call_checkpoint_bottleneck;   s#    	, }}WBuBEBBr?   c                      y rO    r<   rH   s     r>   forwardz_DenseLayer.forwardB       r?   c                      y rO   rV   rW   s     r>   rX   z_DenseLayer.forwardF   rY   r?   c                    t        |t              r|g}n|}| j                  rL| j                  |      r;t        j
                  j                         rt        d      | j                  |      }n| j                  |      }| j                  | j                  | j                  |                  }| j                  dkD  r,t        j                  || j                  | j                         }|S )Nz%Memory Efficient not supported in JITr   )ptraining)
isinstancer	   r#   rL   rC   jitis_scripting	ExceptionrT   rG   r:   r9   r8   r"   Fdropoutr]   )r<   rH   prev_featuresrF   new_featuress        r>   rX   z_DenseLayer.forwardL   s    eV$"GM!M  T%;%;M%Jyy%%' GHH $ ? ? N $ 0 0 ?zz$**TZZ8I-J"KL>>A99\T^^dmm\Lr?   F)__name__
__module____qualname__intr;   boolr0   r   r	   rG   rL   rC   r_   unusedrT   _overload_methodrX   __classcell__r=   s   @r>   r   r      s   rw1"%1471BE1RW1ko1	1!$v, !6 !tF|   YYCV C C C YYT&\ f    YYV    
V  r?   r   c                   T     e Zd ZdZ	 ddededededededd	f fd
ZdedefdZ	 xZ
S )_DenseBlockr
   
num_layersr   r!   r    r"   r#   r$   Nc                     t         	|           t        |      D ]0  }t        |||z  z   ||||      }| j	                  d|dz   z  |       2 y )N)r    r!   r"   r#   zdenselayer%dr   )r/   r0   ranger   
add_module)
r<   rr   r   r!   r    r"   r#   ilayerr=   s
            r>   r0   z_DenseBlock.__init__c   s_     	z" 	=A"Q_4'#!1E OONa!e4e<	=r?   init_featuresc                     |g}| j                         D ]  \  }} ||      }|j                  |         t        j                  |d      S rB   )itemsappendrC   rD   )r<   rx   featuresnamerw   re   s         r>   rX   z_DenseBlock.forwardw   sJ    !?::< 	*KD% ?LOOL)	* yy1%%r?   rf   )rg   rh   ri   _versionrj   r;   rk   r0   r	   rX   rn   ro   s   @r>   rq   rq   `   si    H "'==  = 	=
 = = = 
=(&V & &r?   rq   c                   ,     e Zd Zdededdf fdZ xZS )_Transitionr   num_output_featuresr$   Nc                    t         |           t        j                  |      | _        t        j
                  d      | _        t        j                  ||ddd      | _        t        j                  dd      | _
        y )NTr&   r   Fr(   r
   )r)   r*   )r/   r0   r1   r2   normr4   relur6   conv	AvgPool2dpool)r<   r   r   r=   s      r>   r0   z_Transition.__init__   s^    NN#56	GGD)	II02EST]^ejk	LLQq9	r?   )rg   rh   ri   rj   r0   rn   ro   s   @r>   r   r      s"    :3 :S :T : :r?   r   c                   r     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Zde	d	e	fdZ
 x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    block_confignum_init_featuresr!   r"   num_classesr#   r$   Nc                 "   t         |           t        |        t        j                  t        dt        j                  d|dddd      fdt        j                  |      fdt        j                  d	
      fdt        j                  ddd      fg            | _
        |}t        |      D ]  \  }	}
t        |
|||||      }| j                  j                  d|	dz   z  |       ||
|z  z   }|	t        |      dz
  k7  sSt        ||dz        }| j                  j                  d|	dz   z  |       |dz  } | j                  j                  dt        j                  |             t        j                   ||      | _        | j%                         D ]  }t'        |t        j                        r*t        j(                  j+                  |j,                         Gt'        |t        j                        rUt        j(                  j/                  |j,                  d       t        j(                  j/                  |j0                  d       t'        |t        j                         st        j(                  j/                  |j0                  d        y )Nconv0r,      r
   Fr-   norm0relu0Tr&   pool0r   )r)   r*   r.   )rr   r   r!   r    r"   r#   zdenseblock%d)r   r   ztransition%dnorm5r   )r/   r0   r   r1   
Sequentialr   r6   r2   r4   	MaxPool2dr|   	enumeraterq   ru   lenr   Linear
classifiermodulesr^   initkaiming_normal_weight	constant_r+   )r<   r    r   r   r!   r"   r   r#   num_featuresrv   rr   blocktransmr=   s                 r>   r0   zDenseNet.__init__   s    	D! bii+<!TU_`glmnbnn->?@bggd34bllqANO		
 )&|4 	1MAz%#/'#!1E MM$$^q1u%=uE'*{*BBLC%))#|YeijYjk((1q5)A5I+q0	1" 	  "..*FG ))L+>  	-A!RYY'''1Ar~~.!!!((A.!!!&&!,Aryy)!!!&&!,	-r?   xc                     | j                  |      }t        j                  |d      }t        j                  |d      }t	        j
                  |d      }| j                  |      }|S )NTr&   )r   r   r   )r|   rb   r   adaptive_avg_pool2drC   flattenr   )r<   r   r|   outs       r>   rX   zDenseNet.forward   sU    ==#ffXt,##C0mmC#ooc"
r?   )                @      r   i  F)rg   rh   ri   __doc__rj   r   r;   rk   r0   r	   rX   rn   ro   s   @r>   r   r      s    " 2A!#!&:-:- Cc3./:- 	:-
 :- :- :- :- 
:-x F r?   r   modelweightsprogressr$   c                 6   t        j                  d      }|j                  |d      }t        |j	                               D ]D  }|j                  |      }|s|j                  d      |j                  d      z   }||   ||<   ||= F | j                  |       y )Nz]^(.*denselayer\d+\.(?:norm|relu|conv))\.((?:[12])\.(?:weight|bias|running_mean|running_var))$T)r   
check_hashr   r
   )recompileget_state_dictlistkeysmatchgroupload_state_dict)r   r   r   pattern
state_dictkeyresnew_keys           r>   _load_state_dictr      s    
 jjhG ''d'KJJOO%&  mmC iilSYYq\1G",S/Jw3  
*%r?   r    r   r   kwargsc                     |#t        |dt        |j                  d                t        | ||fi |}|t	        |||       |S )Nr   
categories)r   r   r   )r   r   metar   r   )r    r   r   r   r   r   r   s          r>   	_densenetr      sO     fmSl9S5TU[,0ALVLEugILr?   )   r   z*https://github.com/pytorch/vision/pull/116z'These weights are ported from LuaTorch.)min_sizer   recipe_docsc            
       R    e Zd Z ed eed      i edddddid	d
d      ZeZy)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	rg   rh   ri   r   r   r   _COMMON_METAIMAGENET1K_V1DEFAULTrV   r?   r>   r   r     sQ    J.#>

!##   
M  Gr?   r   c            
       R    e Zd Z ed eed      i edddddid	d
d      ZeZy)r   z<https://download.pytorch.org/models/densenet161-8d451a50.pthr   r   i(r   gFHS@gp=
cW@r   gx@gV-[@r   r   Nr   rV   r?   r>   r   r     sQ    J.#>

"##  !
M  Gr?   r   c            
       R    e Zd Z ed eed      i edddddid	d
d      ZeZy)r   z<https://download.pytorch.org/models/densenet169-b2777c0a.pthr   r   ih r   gfffffR@g$3W@r   gzG
@gvZK@r   r   Nr   rV   r?   r>   r   r   3  sQ    J.#>

"##   
M  Gr?   r   c            
       R    e Zd Z ed eed      i edddddid	d
d      ZeZy)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   rV   r?   r>   r   r   G  sQ    J.#>

"##   
M  Gr?   r   
pretrained)r   T)r   r   c                 L    t         j                  |       } 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:
    r   r   r   )r   verifyr   r   r   r   s      r>   r   r   [  ,    * "((1GR"gxJ6JJr?   c                 L    t         j                  |       } t        ddd| |fi |S )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   s      r>   r   r   u  r   r?   c                 L    t         j                  |       } t        ddd| |fi |S )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:
    r   )r   r   r   r   r   )r   r   r   r   s      r>   r   r     r   r?   c                 L    t         j                  |       } t        ddd| |fi |S )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:
    r   )r   r   r   r   r   )r   r   r   r   s      r>   r   r     r   r?   )7r   collectionsr   	functoolsr   typingr   r   r   r   rC   torch.nnr1   torch.nn.functional
functionalrb   torch.utils.checkpointutilsrS   rR   r	   transforms._presetsr   r   _apir   r   r   _metar   _utilsr   r   __all__Moduler   
ModuleDictrq   r   r   r   rk   r   rj   r   r   r   r   r   r   r   r   r   r   r   rV   r?   r>   <module>r      s   	 #  - -     # #  5 ' 6 6 ' B
>")) >B&"-- &>:"-- :Rryy Rj&BII & &t &PT &&S#s*+  k"	
   ( &::	+ (+ (+ (+ ( ,0C0Q0Q!RS<@SW KH%89 KD Kcf Kks K T K0 ,0C0Q0Q!RS<@SW KH%89 KD Kcf Kks K T K0 ,0C0Q0Q!RS<@SW KH%89 KD Kcf Kks K T K0 ,0C0Q0Q!RS<@SW KH%89 KD Kcf Kks K T Kr?   