o
    پi\G                     @   s  d Z ddlZddlmZ ddlZddlmZ ddlm  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	gZd
d ZG dd dejZG dd dejZG dd deZG dd deZG dd deZG dd dejZG dd	 d	ejZd?ddZd@ddZeedd ed!d"d#ed$d ed%d ed&d ed'd ed(d"d#ed)d ed*d d+	Z ed?d,efd-d.Z!ed?d,efd/d0Z"ed?d,efd1d2Z#ed?d,efd3d4Z$ed?d,efd5d6Z%ed?d,efd7d8Z&ed?d,efd9d:Z'ed?d,efd;d<Z(ed?d,efd=d>Z)dS )Aa:  
SEResNet implementation from Cadene's pretrained models
https://github.com/Cadene/pretrained-models.pytorch/blob/master/pretrainedmodels/models/senet.py
Additional credit to https://github.com/creafz

Original model: https://github.com/hujie-frank/SENet

ResNet code gently borrowed from
https://github.com/pytorch/vision/blob/master/torchvision/models/resnet.py

FIXME I'm deprecating this model and moving them to ResNet as I don't want to maintain duplicate
support for extras like dilation, switchable BN/activations, feature extraction, etc that don't exist here.
    N)OrderedDictIMAGENET_DEFAULT_MEANIMAGENET_DEFAULT_STD)create_classifier   )build_model_with_cfg)register_modelgenerate_default_cfgsSENetc                 C   sX   t | tjrtjj| jddd d S t | tjr*tj| jd tj| jd d S d S )Nfan_outrelu)modenonlinearityg      ?        )	
isinstancennConv2dinitkaiming_normal_weightBatchNorm2d	constant_bias)m r   E/home/ubuntu/.local/lib/python3.10/site-packages/timm/models/senet.py_weight_init   s   r   c                       s$   e Zd Z fddZdd Z  ZS )SEModulec                    sV   t t|   tj||| dd| _tjdd| _tj|| |dd| _t	 | _
d S )Nr   )kernel_sizeTinplace)superr   __init__r   r   fc1ReLUr   fc2Sigmoidsigmoid)selfchannels	reduction	__class__r   r   r#   '   s
   zSEModule.__init__c                 C   sB   |}|j ddd}| |}| |}| |}| |}|| S )N)      T)keepdim)meanr$   r   r&   r(   )r)   xmodule_inputr   r   r   forward.   s   



zSEModule.forward)__name__
__module____qualname__r#   r4   __classcell__r   r   r,   r   r   %   s    r   c                   @   s   e Zd ZdZdd ZdS )
BottleneckzH
    Base class for bottlenecks that implements `forward()` method.
    c                 C   s   |}|  |}| |}| |}| |}| |}| |}| |}| |}| jd ur4| |}| || }| |}|S N)	conv1bn1r   conv2bn2conv3bn3
downsample	se_moduler)   r2   shortcutoutr   r   r   r4   =   s   










zBottleneck.forwardN)r5   r6   r7   __doc__r4   r   r   r   r   r9   8   s    r9   c                       &   e Zd ZdZdZd fdd	Z  ZS )SEBottleneckz"
    Bottleneck for SENet154.
       r   Nc              	      s   t t|   tj||d ddd| _t|d | _tj|d |d d|d|dd| _t|d | _	tj|d |d ddd| _
t|d | _tjdd	| _t|d |d
| _|| _|| _d S )Nr.   r   Fr   r   rI   r/   r   stridepaddinggroupsr   Tr    r+   )r"   rH   r#   r   r   r;   r   r<   r=   r>   r?   r@   r%   r   r   rB   rA   rL   r)   inplanesplanesrN   r+   rL   rA   r,   r   r   r#   Z   s   
zSEBottleneck.__init__r   Nr5   r6   r7   rF   	expansionr#   r8   r   r   r,   r   rH   T       rH   c                       rG   )SEResNetBottleneckz
    ResNet bottleneck with a Squeeze-and-Excitation module. It follows Caffe
    implementation and uses `stride=stride` in `conv1` and not in `conv2`
    (the latter is used in the torchvision implementation of ResNet).
    rI   r   Nc                    s   t t|   tj||dd|d| _t|| _tj||dd|dd| _t|| _	tj||d ddd| _
t|d | _tjdd	| _t|d |d
| _|| _|| _d S )Nr   Fr   r   rL   r/   r   rM   rN   r   rI   rJ   Tr    rO   )r"   rW   r#   r   r   r;   r   r<   r=   r>   r?   r@   r%   r   r   rB   rA   rL   rP   r,   r   r   r#   r   s   
zSEResNetBottleneck.__init__rS   rT   r   r   r,   r   rW   j   s    rW   c                       rG   )SEResNeXtBottleneckzI
    ResNeXt bottleneck type C with a Squeeze-and-Excitation module.
    rI   r   Nc           	   	      s   t t|   t||d  | }tj||dddd| _t|| _	tj||d|d|dd| _
t|| _tj||d ddd| _t|d | _tjd	d
| _t|d |d| _|| _|| _d S )N@   r   FrX   r/   rK   rI   rJ   Tr    rO   )r"   rZ   r#   mathfloorr   r   r;   r   r<   r=   r>   r?   r@   r%   r   r   rB   rA   rL   )	r)   rQ   rR   rN   r+   rL   rA   
base_widthwidthr,   r   r   r#      s   
zSEResNeXtBottleneck.__init__)r   NrI   rT   r   r   r,   r   rZ      rV   rZ   c                       s*   e Zd ZdZd fdd	Zdd Z  ZS )SEResNetBlockr   Nc                    s   t t|   tj||dd|dd| _t|| _tj||dd|dd| _t|| _	tj
dd| _t||d| _|| _|| _d S )	Nr/   r   F)r   rM   rL   r   rY   Tr    rO   )r"   r`   r#   r   r   r;   r   r<   r=   r>   r%   r   r   rB   rA   rL   rP   r,   r   r   r#      s   
zSEResNetBlock.__init__c                 C   sp   |}|  |}| |}| |}| |}| |}| |}| jd ur*| |}| || }| |}|S r:   )r;   r<   r   r=   r>   rA   rB   rC   r   r   r   r4      s   








zSEResNetBlock.forwardrS   )r5   r6   r7   rU   r#   r4   r8   r   r   r,   r   r`      s    r`   c                       s   e Zd Z			d  fd	d
	Z		d!ddZejjd"ddZejjd#ddZ	ejjde
jfddZd$dedefddZdd Zd"defddZdd Z  ZS )%r   皙?r/   r[   Fr   r     avgc                    sp  t t|   || _|| _|| _|r`dtj|ddddddfdtdfd	tj	d
dfdtjdddddddfdtdfdtj	d
dfdtjd|dddddfdt|fdtj	d
dfg	}ndtj||dddddfdt|fd	tj	d
dfg}t
t|| _tjddd
d| _t|dddg| _| j|d|d ||ddd| _|  jtd|j dddg7  _| j|d|d d|||	|
d| _|  jtd|j dddg7  _| j|d|d d|||	|
d| _|  jtd|j d d!dg7  _| j|d"|d d|||	|
d| _|  jtd"|j d#d$dg7  _d"|j  | _| _t| j| j|d%\| _| _|  D ]}t| q.d&S )'af  
        Parameters
        ----------
        block (nn.Module): Bottleneck class.
            - For SENet154: SEBottleneck
            - For SE-ResNet models: SEResNetBottleneck
            - For SE-ResNeXt models:  SEResNeXtBottleneck
        layers (list of ints): Number of residual blocks for 4 layers of the
            network (layer1...layer4).
        groups (int): Number of groups for the 3x3 convolution in each
            bottleneck block.
            - For SENet154: 64
            - For SE-ResNet models: 1
            - For SE-ResNeXt models:  32
        reduction (int): Reduction ratio for Squeeze-and-Excitation modules.
            - For all models: 16
        dropout_p (float or None): Drop probability for the Dropout layer.
            If `None` the Dropout layer is not used.
            - For SENet154: 0.2
            - For SE-ResNet models: None
            - For SE-ResNeXt models: None
        inplanes (int):  Number of input channels for layer1.
            - For SENet154: 128
            - For SE-ResNet models: 64
            - For SE-ResNeXt models: 64
        input_3x3 (bool): If `True`, use three 3x3 convolutions instead of
            a single 7x7 convolution in layer0.
            - For SENet154: True
            - For SE-ResNet models: False
            - For SE-ResNeXt models: False
        downsample_kernel_size (int): Kernel size for downsampling convolutions
            in layer2, layer3 and layer4.
            - For SENet154: 3
            - For SE-ResNet models: 1
            - For SE-ResNeXt models: 1
        downsample_padding (int): Padding for downsampling convolutions in
            layer2, layer3 and layer4.
            - For SENet154: 1
            - For SE-ResNet models: 0
            - For SE-ResNeXt models: 0
        num_classes (int): Number of outputs in `last_linear` layer.
            - For all models: 1000
        r;   r[   r/   r.   r   F)rL   rM   r   r<   relu1Tr    r=   r>   relu2r?   r@   relu3   r   rL   rM   r   )rL   	ceil_modelayer0)num_chsr+   moduler   )rR   blocksrN   r+   downsample_kernel_sizedownsample_paddingrI   layer1   )rR   rm   rL   rN   r+   rn   ro      layer2      layer3i       layer4	pool_typeN)r"   r   r#   rQ   num_classes	drop_rater   r   r   r%   
Sequentialr   rj   	MaxPool2dpool0dictfeature_info_make_layerrp   rU   rs   rv   rx   num_featureshead_hidden_sizer   global_poollast_linearmodulesr   )r)   blocklayersrN   r+   r|   in_chansrQ   	input_3x3rn   ro   r{   r   layer0_modulesr   r,   r   r   r#      s   / 	 
 
 

zSENet.__init__c	              
   C   s   d }	|dks| j ||j kr'ttj| j ||j |||ddt||j }	|| j |||||	g}
||j | _ td|D ]}|
|| j ||| q=tj|
 S )Nr   Frh   )rQ   rU   r   r}   r   r   rangeappend)r)   r   rR   rm   rN   r+   rL   rn   ro   rA   r   ir   r   r   r   5  s   
zSENet._make_layerc                 C   s   t d|rdndd}|S )Nz^layer0z^layer(\d+)z^layer(\d+)\.(\d+))stemrm   )r   )r)   coarsematcherr   r   r   group_matcherG  s   zSENet.group_matcherTc                 C   s   |rJ dd S )Nz$gradient checkpointing not supportedr   )r)   enabler   r   r   set_grad_checkpointingL  s   zSENet.set_grad_checkpointingreturnc                 C   s   | j S r:   )r   )r)   r   r   r   get_classifierP  s   zSENet.get_classifierr{   r   c                 C   s$   || _ t| j| j |d\| _| _d S )Nry   )r{   r   r   r   r   )r)   r{   r   r   r   r   reset_classifierT  s   
zSENet.reset_classifierc                 C   s@   |  |}| |}| |}| |}| |}| |}|S r:   )rj   r   rp   rs   rv   rx   r)   r2   r   r   r   forward_featuresY  s   





zSENet.forward_features
pre_logitsc                 C   s:   |  |}| jdkrtj|| j| jd}|r|S | |S )Nr   )ptraining)r   r|   Fdropoutr   r   )r)   r2   r   r   r   r   forward_headb  s   

zSENet.forward_headc                 C   s   |  |}| |}|S r:   )r   r   r   r   r   r   r4   h  s   

zSENet.forward)ra   r/   r[   Fr   r   rb   rc   )r   r   r   F)T)rc   )r5   r6   r7   r#   r   torchjitignorer   r   r   Moduler   intstrr   r   boolr   r4   r8   r   r   r,   r   r      s$    |
	Fc                 K   s   t t| |fi |S r:   )r   r   )variant
pretrainedkwargsr   r   r   _create_senetn  s   r    c                 K   s   | dddddt tddd
|S )	Nrb   )r/      r   )rg   rg   g      ?bilinearzlayer0.conv1r   )
urlr{   
input_size	pool_sizecrop_pctinterpolationr1   std
first_conv
classifierr   )r   r   r   r   r   _cfgr  s   r   zmhttps://github.com/rwightman/pytorch-image-models/releases/download/v0.1-weights/legacy_senet154-e9eb9fe6.pth)r   zhhttps://github.com/rwightman/pytorch-image-models/releases/download/v0.1-weights/seresnet18-4bb0ce65.pthbicubic)r   r   zhhttps://github.com/rwightman/pytorch-image-models/releases/download/v0.1-weights/seresnet34-a4004e63.pthzhhttps://github.com/rwightman/pytorch-image-models/releases/download/v0.1-cadene/se_resnet50-ce0d4300.pthzihttps://github.com/rwightman/pytorch-image-models/releases/download/v0.1-cadene/se_resnet101-7e38fcc6.pthzihttps://github.com/rwightman/pytorch-image-models/releases/download/v0.1-cadene/se_resnet152-d17c99b7.pthzphttps://github.com/rwightman/pytorch-image-models/releases/download/v0.1-weights/seresnext26_32x4d-65ebdb501.pthzwhttps://github.com/rwightman/pytorch-image-models/releases/download/v0.1-weights/legacy_se_resnext50_32x4d-f3651bad.pthzxhttps://github.com/rwightman/pytorch-image-models/releases/download/v0.1-weights/legacy_se_resnext101_32x4d-37725eac.pth)	zlegacy_senet154.in1kzlegacy_seresnet18.in1kzlegacy_seresnet34.in1kzlegacy_seresnet50.in1kzlegacy_seresnet101.in1kzlegacy_seresnet152.in1kzlegacy_seresnext26_32x4d.in1kzlegacy_seresnext50_32x4d.in1kzlegacy_seresnext101_32x4d.in1kr   c                 K   2   t tg dddd}td| fi t |fi |S )Nr.   r.   r.   r.   r   ru   r   r   rN   r+   legacy_seresnet18r   r`   r   r   r   
model_argsr   r   r   r        r   c                 K   r   )Nr/   rI      r/   r   ru   r   legacy_seresnet34r   r   r   r   r   r     r   r   c                 K   r   )Nr   r   ru   r   legacy_seresnet50r   rW   r   r   r   r   r   r     r   r   c                 K   r   )Nr/   rI      r/   r   ru   r   legacy_seresnet101r   r   r   r   r   r     r   r   c                 K   r   )Nr/   rr   $   r/   r   ru   r   legacy_seresnet152r   r   r   r   r   r     r   r   c              
   K   s:   t tg dddddddd}td	| fi t |fi |S )
Nr   r[   ru   r/   r   rq   T)r   r   rN   r+   rn   ro   rQ   r   legacy_senet154)r   rH   r   r   r   r   r   r     s
   r   c                 K   r   )Nr   rw   ru   r   legacy_seresnext26_32x4dr   rZ   r   r   r   r   r   r     r   r   c                 K   r   )Nr   rw   ru   r   legacy_seresnext50_32x4dr   r   r   r   r   r     r   r   c                 K   r   )Nr   rw   ru   r   legacy_seresnext101_32x4dr   r   r   r   r   r     r   r   r   )r   )*rF   r\   collectionsr   r   torch.nnr   torch.nn.functional
functionalr   	timm.datar   r   timm.layersr   _builderr   	_registryr	   r
   __all__r   r   r   r9   rH   rW   rZ   r`   r   r   r   default_cfgsr   r   r   r   r   r   r   r   r   r   r   r   r   <module>   s    " 
8

