a
    Ad                     @   s  d dl Z 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mZmZ G dd dejZdd Z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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G dd dejZG dd dejZG dd dejZe dkrd Z!d!Z"d"e! e" d# e" Z#d$e! e" d# e" Z$ed%e#e$fe"d&g d'd(g d'd%d)d*	Z%e&e% e&e#e$e%' d+  e(d#d,e#e$fZ)e%e)Z)e&e)j* dS )-    N)DropPath	to_2tupletrunc_normal_c                       s0   e Zd Zddejdf fdd	Zdd Z  ZS )MlpN        c                    sN   t    |p|}|p|}t||| _| | _t||| _t|| _d S N)	super__init__nnLinearfc1actfc2Dropoutdrop)selfin_featureshidden_featuresout_features	act_layerr   	__class__ V/var/www/html/stable-diffusion-webui/extensions-builtin/SwinIR/swinir_model_arch_v2.pyr	      s    
zMlp.__init__c                 C   s6   |  |}| |}| |}| |}| |}|S r   )r   r   r   r   )r   xr   r   r   forward   s    




zMlp.forward)__name__
__module____qualname__r
   GELUr	   r   __classcell__r   r   r   r   r      s   	r   c                 C   sR   | j \}}}}| ||| ||| ||} | dddddd d|||}|S )z
    Args:
        x: (B, H, W, C)
        window_size (int): window size
    Returns:
        windows: (num_windows*B, window_size, window_size, C)
    r                  )shapeviewpermute
contiguous)r   window_sizeBHWCwindowsr   r   r   window_partition"   s    $r1   c                 C   sb   t | jd || | |  }| ||| || ||d}|dddddd |||d}|S )z
    Args:
        windows: (num_windows*B, window_size, window_size, C)
        window_size (int): Window size
        H (int): Height of image
        W (int): Width of image
    Returns:
        x: (B, H, W, C)
    r   r&   r!   r"   r#   r$   r%   )intr'   r(   r)   r*   )r0   r+   r-   r.   r,   r   r   r   r   window_reverse0   s    
$r3   c                       sB   e Zd ZdZd fdd	Zddd	Zed
ddZdd Z  Z	S )WindowAttentiona   Window based multi-head self attention (W-MSA) module with relative position bias.
    It supports both of shifted and non-shifted window.
    Args:
        dim (int): Number of input channels.
        window_size (tuple[int]): The height and width of the window.
        num_heads (int): Number of attention heads.
        qkv_bias (bool, optional):  If True, add a learnable bias to query, key, value. Default: True
        attn_drop (float, optional): Dropout ratio of attention weight. Default: 0.0
        proj_drop (float, optional): Dropout ratio of output. Default: 0.0
        pretrained_window_size (tuple[int]): The height and width of the window in pre-training.
    Tr   r   r   c              	      s~  t    || _|| _|| _|| _tjt	dt
|ddf dd| _ttjddddtjddtjd|d	d| _tj| jd
 d  | jd
 tjd}tj| jd d  | jd tjd}	tt||	gddd
 d
}
|d
 d
krP|
d d d d d d d
f  |d
 d   < |
d d d d d d df  |d d   < n\|
d d d d d d d
f  | jd
 d   < |
d d d d d d df  | jd d   < |
d9 }
t|
tt|
d  td }
| d|
 t| jd
 }t| jd }tt||g}t|d}|d d d d d f |d d d d d f  }|ddd
 }|d d d d d
f  | jd
 d 7  < |d d d d df  | jd d 7  < |d d d d d
f  d| jd  d 9  < |d}| d| tj||d d	d| _|r:tt|| _ tt|| _!nd | _ d | _!t"|| _#t||| _$t"|| _%tj&dd| _'d S )N
   r!   Trequires_gradr#   i   biasinplaceFr   )dtype         ?relative_coords_tabler&   relative_position_indexr"   dim)(r   r	   rC   r+   pretrained_window_size	num_headsr
   	Parametertorchlogoneslogit_scale
Sequentialr   ReLUcpb_mlparangefloat32stackmeshgridr)   r*   	unsqueezesignlog2absnpregister_bufferflattensumqkvzerosq_biasv_biasr   	attn_dropproj	proj_dropSoftmaxsoftmax)r   rC   r+   rE   qkv_biasr^   r`   rD   relative_coords_hrelative_coords_wr@   coords_hcoords_wcoordscoords_flattenrelative_coordsrA   r   r   r   r	   L   sl    
&
$$,...,((,
zWindowAttention.__init__Nc                 C   s   |j \}}}d}| jdur:t| jtj| jdd| jf}tj|| jj	|d}|
||d| jddddd	d
}|d |d	 |d   }}	}
tj|ddtj|	dddd }tj| jttd| jjd }|| }| | jd| j}|| jd | jd | jd	  | jd | jd	  d}|ddd	 }dt| }||d }|dur|j d }||| || j|||d	d }|d| j||}| |}n
| |}| |}||
 d	d
|||}|  |}| !|}|S )z
        Args:
            x: input features with shape of (num_windows*B, N, C)
            mask: (0/-inf) mask with shape of (num_windows, Wh*Ww, Wh*Ww) or None
        NFr7   )inputweightr:   r"   r&   r#   r   r!   r$   rB   g      Y@)max   )"r'   r\   rG   cat
zeros_liker]   FlinearrZ   rl   reshaperE   r)   	normalize	transposeclamprJ   rH   tensortodeviceexprM   r@   r(   rA   r+   r*   sigmoidrR   rb   r^   r_   r`   )r   r   maskB_Nr/   rc   rZ   qkvattnrJ   relative_position_bias_tablerelative_position_biasnWr   r   r   r      s8    
 "$*&

(



zWindowAttention.forwardreturnc                 C   s$   d| j  d| j d| j d| j S )Ndim=, window_size=z, pretrained_window_size=, num_heads=)rC   r+   rD   rE   r   r   r   r   
extra_repr   s
    zWindowAttention.extra_reprc                 C   sp   d}||| j  d | j  7 }|| j| | j | j  | 7 }|| j| | | j | j  7 }||| j  | j  7 }|S )Nr   r"   )rC   rE   )r   r   flopsr   r   r   r      s    zWindowAttention.flops)Tr   r   r5   )N)
r   r   r   __doc__r	   r   strr   r   r    r   r   r   r   r4   ?   s     ;
)r4   c                
       s`   e Zd ZdZdddddddejejdf
 fdd	Zd	d
 Zdd Z	e
dddZdd Z  ZS )SwinTransformerBlockaw   Swin Transformer Block.
    Args:
        dim (int): Number of input channels.
        input_resolution (tuple[int]): Input resulotion.
        num_heads (int): Number of attention heads.
        window_size (int): Window size.
        shift_size (int): Shift size for SW-MSA.
        mlp_ratio (float): Ratio of mlp hidden dim to embedding dim.
        qkv_bias (bool, optional): If True, add a learnable bias to query, key, value. Default: True
        drop (float, optional): Dropout rate. Default: 0.0
        attn_drop (float, optional): Attention dropout rate. Default: 0.0
        drop_path (float, optional): Stochastic depth rate. Default: 0.0
        act_layer (nn.Module, optional): Activation layer. Default: nn.GELU
        norm_layer (nn.Module, optional): Normalization layer.  Default: nn.LayerNorm
        pretrained_window_size (int): Window size in pre-training.
       r         @Tr   c              	      s  t    || _|| _|| _|| _|| _|| _t| j| jkrPd| _t| j| _d| j  krh| jk srn J d||| _	t
|t| j|||	|t|d| _|
dkrt|
nt | _||| _t|| }t||||d| _| jdkr| | j}nd }| d| d S )Nr   z shift_size must in 0-window_size)r+   rE   rc   r^   r`   rD   r   )r   r   r   r   	attn_mask)r   r	   rC   input_resolutionrE   r+   
shift_size	mlp_ratiominnorm1r4   r   r   r   r
   Identity	drop_pathnorm2r2   r   mlpcalculate_maskrW   )r   rC   r   rE   r+   r   r   rc   r   r^   r   r   
norm_layerrD   mlp_hidden_dimr   r   r   r   r	      s2    
"


zSwinTransformerBlock.__init__c              	   C   s  |\}}t d||df}td| j t| j | j t| j d f}td| j t| j | j t| j d f}d}|D ].}|D ]$}	||d d ||	d d f< |d7 }qqzt|| j}
|
d| j| j }
|
d|
d }||dkt	d|dkt	d}|S )Nr!   r   r&   r#   g      Yr   )
rG   r[   slicer+   r   r1   r(   rR   masked_fillfloat)r   x_sizer-   r.   img_maskh_slicesw_slicescnthwmask_windowsr   r   r   r   r      s(    $z#SwinTransformerBlock.calculate_maskc                 C   s>  |\}}|j \}}}|}|||||}| jdkrPtj|| j | j fdd}	n|}	t|	| j}
|
d| j| j |}
| j|kr| j|
| j	d}n| j|
| 
||jd}|d| j| j|}t|| j||}	| jdkrtj|	| j| jfdd}n|	}|||| |}|| | | }|| | | | }|S )Nr   )r!   r#   )shiftsdimsr&   )r}   )r'   r(   r   rG   rollr1   r+   r   r   r   r   ry   rz   r3   r   r   r   r   )r   r   r   r-   r.   r,   Lr/   shortcut	shifted_x	x_windowsattn_windowsr   r   r   r     s*    


zSwinTransformerBlock.forwardr   c                 C   s4   d| j  d| j d| j d| j d| j d| j S )Nr   , input_resolution=r   r   z, shift_size=z, mlp_ratio=)rC   r   rE   r+   r   r   r   r   r   r   r   5  s    zSwinTransformerBlock.extra_reprc                 C   s   d}| j \}}|| j| | 7 }|| | j | j }||| j| j| j  7 }|d| | | j | j | j 7 }|| j| | 7 }|S )Nr   r#   )r   rC   r+   r   r   r   )r   r   r-   r.   r   r   r   r   r   9  s    
"zSwinTransformerBlock.flops)r   r   r   r   r
   r   	LayerNormr	   r   r   r   r   r   r    r   r   r   r   r      s   

")r   c                       sD   e Zd ZdZejf fdd	Zdd ZedddZ	d	d
 Z
  ZS )PatchMergingz Patch Merging Layer.
    Args:
        input_resolution (tuple[int]): Resolution of input feature.
        dim (int): Number of input channels.
        norm_layer (nn.Module, optional): Normalization layer.  Default: nn.LayerNorm
    c                    sB   t    || _|| _tjd| d| dd| _|d| | _d S )Nr$   r#   Fr9   )r   r	   r   rC   r
   r   	reductionnorm)r   r   rC   r   r   r   r   r	   O  s
    
zPatchMerging.__init__c                 C   s6  | j \}}|j\}}}||| ks*J d|d dkrB|d dksXJ d| d| d|||||}|ddddddddddf }|ddddddddddf }|ddddddddddf }	|ddddddddddf }
t|||	|
gd	}||d	d
| }| |}| |}|S )z
        x: B, H*W, C
        zinput feature has wrong sizer#   r   zx size (*z) are not even.Nr!   r&   r$   )r   r'   r(   rG   rp   r   r   )r   r   r-   r.   r,   r   r/   x0x1x2x3r   r   r   r   V  s    
.$$$$

zPatchMerging.forwardr   c                 C   s   d| j  d| j S )Nzinput_resolution=z, dim=r   rC   r   r   r   r   r   m  s    zPatchMerging.extra_reprc                 C   sH   | j \}}|d |d  d | j d | j }||| | j d 7 }|S )Nr#   r$   r   r   r-   r.   r   r   r   r   r   p  s    
$zPatchMerging.flops)r   r   r   r   r
   r   r	   r   r   r   r   r    r   r   r   r   r   G  s
   r   c                	       s\   e Zd ZdZdddddejdddf	 fdd		Zd
d ZedddZ	dd Z
dd Z  ZS )
BasicLayera   A basic Swin Transformer layer for one stage.
    Args:
        dim (int): Number of input channels.
        input_resolution (tuple[int]): Input resolution.
        depth (int): Number of blocks.
        num_heads (int): Number of attention heads.
        window_size (int): Local window size.
        mlp_ratio (float): Ratio of mlp hidden dim to embedding dim.
        qkv_bias (bool, optional): If True, add a learnable bias to query, key, value. Default: True
        drop (float, optional): Dropout rate. Default: 0.0
        attn_drop (float, optional): Attention dropout rate. Default: 0.0
        drop_path (float | tuple[float], optional): Stochastic depth rate. Default: 0.0
        norm_layer (nn.Module, optional): Normalization layer. Default: nn.LayerNorm
        downsample (nn.Module | None, optional): Downsample layer at the end of the layer. Default: None
        use_checkpoint (bool): Whether to use checkpointing to save memory. Default: False.
        pretrained_window_size (int): Local window size in pre-training.
    r   Tr   NFr   c                    sx   t    | _| _|| _|| _t 	
fddt|D | _	|d urn|d| _
nd | _
d S )Nc                    sR   g | ]J}t 
|d  dkr"dn
d  	 ttrB| ndqS )r#   r   )rC   r   rE   r+   r   r   rc   r   r^   r   r   rD   )r   
isinstancelist).0ir^   rC   r   r   r   r   r   rE   rD   rc   r+   r   r   
<listcomp>  s   
z'BasicLayer.__init__.<locals>.<listcomp>)rC   r   )r   r	   rC   r   depthuse_checkpointr
   
ModuleListrangeblocks
downsample)r   rC   r   r   rE   r+   r   rc   r   r^   r   r   r   r   rD   r   r   r   r	     s    
"

zBasicLayer.__init__c                 C   sD   | j D ]$}| jr t|||}q|||}q| jd ur@| |}|S r   )r   r   
checkpointr   )r   r   r   blkr   r   r   r     s    


zBasicLayer.forwardr   c                 C   s   d| j  d| j d| j S )Nr   r   z, depth=)rC   r   r   r   r   r   r   r     s    zBasicLayer.extra_reprc                 C   s8   d}| j D ]}|| 7 }q
| jd ur4|| j 7 }|S Nr   )r   r   r   )r   r   r   r   r   r   r     s    

zBasicLayer.flopsc                 C   sX   | j D ]L}tj|jjd tj|jjd tj|jjd tj|jjd qd S r   )r   r
   init	constant_r   r:   rl   r   )r   r   r   r   r   _init_respostnorm  s
    
zBasicLayer._init_respostnorm)r   r   r   r   r
   r   r	   r   r   r   r   r   r    r   r   r   r   r   v  s   

r   c                       s2   e Zd ZdZd fdd	Zd	d
 Zdd Z  ZS )
PatchEmbedaw   Image to Patch Embedding
    Args:
        img_size (int): Image size.  Default: 224.
        patch_size (int): Patch token size. Default: 4.
        in_chans (int): Number of input image channels. Default: 3.
        embed_dim (int): Number of linear projection output channels. Default: 96.
        norm_layer (nn.Module, optional): Normalization layer. Default: None
       r$   r"   `   Nc                    s   t    t|}t|}|d |d  |d |d  g}|| _|| _|| _|d |d  | _|| _|| _t	j
||||d| _|d ur||| _nd | _d S )Nr   r!   )kernel_sizestride)r   r	   r   img_size
patch_sizepatches_resolutionnum_patchesin_chans	embed_dimr
   Conv2dr_   r   r   r   r   r   r   r   r   r   r   r   r	     s    
 zPatchEmbed.__init__c                 C   s>   |j \}}}}| |ddd}| jd ur:| |}|S )Nr#   r!   )r'   r_   rX   rv   r   )r   r   r,   r/   r-   r.   r   r   r   r     s
    

zPatchEmbed.forwardc                 C   sR   | j \}}|| | j | j | jd | jd   }| jd urN||| | j 7 }|S Nr   r!   )r   r   r   r   r   )r   ZHoZWor   r   r   r   r     s
    
(
zPatchEmbed.flops)r   r$   r"   r   Nr   r   r   r   r	   r   r   r    r   r   r   r   r     s   	
r   c                       sJ   e Zd ZdZdddddejddddd	f fd
d	Zdd Zdd Z  Z	S )RSTBaX  Residual Swin Transformer Block (RSTB).

    Args:
        dim (int): Number of input channels.
        input_resolution (tuple[int]): Input resolution.
        depth (int): Number of blocks.
        num_heads (int): Number of attention heads.
        window_size (int): Local window size.
        mlp_ratio (float): Ratio of mlp hidden dim to embedding dim.
        qkv_bias (bool, optional): If True, add a learnable bias to query, key, value. Default: True
        drop (float, optional): Dropout rate. Default: 0.0
        attn_drop (float, optional): Attention dropout rate. Default: 0.0
        drop_path (float | tuple[float], optional): Stochastic depth rate. Default: 0.0
        norm_layer (nn.Module, optional): Normalization layer. Default: nn.LayerNorm
        downsample (nn.Module | None, optional): Downsample layer at the end of the layer. Default: None
        use_checkpoint (bool): Whether to use checkpointing to save memory. Default: False.
        img_size: Input image size.
        patch_size: Patch size.
        resi_connection: The convolutional block before residual connection.
    r   Tr   NFr   r$   1convc                    s   t t|   || _|| _t|||||||||	|
|||d| _|dkr\t||ddd| _	nj|dkrt
t||d dddtjddd	t|d |d ddd
tjddd	t|d |ddd| _	t||||d d| _t||||d d| _d S )N)rC   r   r   rE   r+   r   rc   r   r^   r   r   r   r   r   r"   r!   3convr$   皙?Tnegative_sloper<   r   r   r   r   r   r   )r   r   r	   rC   r   r   residual_groupr
   r   convrK   	LeakyReLUr   patch_embedPatchUnEmbedpatch_unembed)r   rC   r   r   rE   r+   r   rc   r   r^   r   r   r   r   r   r   resi_connectionr   r   r   r	     s@    $zRSTB.__init__c              
   C   s$   |  | | | |||| S r   )r   r   r   r   )r   r   r   r   r   r   r   .  s    zRSTB.forwardc                 C   sX   d}|| j  7 }| j\}}||| | j | j d 7 }|| j 7 }|| j 7 }|S )Nr   	   )r   r   r   rC   r   r   )r   r   r-   r.   r   r   r   r   1  s    
z
RSTB.flops)
r   r   r   r   r
   r   r	   r   r   r    r   r   r   r   r     s   
'r   c                       s2   e Zd ZdZd fdd	Zd	d
 Zdd Z  ZS )r   az   Image to Patch Unembedding

    Args:
        img_size (int): Image size.  Default: 224.
        patch_size (int): Patch token size. Default: 4.
        in_chans (int): Number of input image channels. Default: 3.
        embed_dim (int): Number of linear projection output channels. Default: 96.
        norm_layer (nn.Module, optional): Normalization layer. Default: None
    r   r$   r"   r   Nc                    sn   t    t|}t|}|d |d  |d |d  g}|| _|| _|| _|d |d  | _|| _|| _d S r   )	r   r	   r   r   r   r   r   r   r   r   r   r   r   r	   F  s    
 zPatchUnEmbed.__init__c                 C   s2   |j \}}}|dd|| j|d |d }|S )Nr!   r#   r   )r'   rv   r(   r   )r   r   r   r,   HWr/   r   r   r   r   S  s    "zPatchUnEmbed.forwardc                 C   s   d}|S r   r   )r   r   r   r   r   r   X  s    zPatchUnEmbed.flops)r   r$   r"   r   Nr   r   r   r   r   r   ;  s   
r   c                       s    e Zd ZdZ fddZ  ZS )UpsampleUpsample module.

    Args:
        scale (int): Scale factor. Supported scales: 2^n and 3.
        num_feat (int): Channel number of intermediate features.
    c              
      s   g }||d @ dkr\t tt|dD ]0}|t|d| ddd |td q(nF|dkr|t|d| ddd |td ntd| dt	t
| j|  d S 	Nr!   r   r#   r$   r"   r   zscale z/ is not supported. Supported scales: 2^n and 3.)r   r2   mathrH   appendr
   r   PixelShuffle
ValueErrorr   r   r	   r   scalenum_featm_r   r   r   r	   e  s    zUpsample.__init__r   r   r   r   r	   r    r   r   r   r   r   ]  s   r   c                       s    e Zd ZdZ fddZ  ZS )Upsample_hfr   c              
      s   g }||d @ dkr\t tt|dD ]0}|t|d| ddd |td q(nF|dkr|t|d| ddd |td ntd| dt	t
| j|  d S r   )r   r2   r   rH   r   r
   r   r   r   r   r   r	   r   r   r   r   r	   z  s    zUpsample_hf.__init__r   r   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 )UpsampleOneStepa*  UpsampleOneStep module (the difference with Upsample is that it always only has 1conv + 1pixelshuffle)
       Used in lightweight SR to save parameters.

    Args:
        scale (int): Scale factor. Supported scales: 2^n and 3.
        num_feat (int): Channel number of intermediate features.

    Nc              	      sT   || _ || _g }|t||d | ddd |t| tt| j|  d S )Nr#   r"   r!   )	r   r   r   r
   r   r   r   r   r	   )r   r   r   
num_out_chr   r   r   r   r   r	     s     zUpsampleOneStep.__init__c                 C   s$   | j \}}|| | j d d }|S )Nr"   r   )r   r   r   r   r   r   r     s    
zUpsampleOneStep.flops)N)r   r   r   r   r	   r   r    r   r   r   r   r     s   	r   c                       s   e Zd ZdZddddddddd	d
d
dejdd	dddddf fdd	Zdd Zej	j
dd Zej	j
dd Zdd Zdd Zdd Zdd  Zd!d" Z  ZS )#Swin2SRa   Swin2SR
        A PyTorch impl of : `Swin2SR: SwinV2 Transformer for Compressed Image Super-Resolution and Restoration`.

    Args:
        img_size (int | tuple(int)): Input image size. Default 64
        patch_size (int | tuple(int)): Patch size. Default: 1
        in_chans (int): Number of input image channels. Default: 3
        embed_dim (int): Patch embedding dimension. Default: 96
        depths (tuple(int)): Depth of each Swin Transformer layer.
        num_heads (tuple(int)): Number of attention heads in different layers.
        window_size (int): Window size. Default: 7
        mlp_ratio (float): Ratio of mlp hidden dim to embedding dim. Default: 4
        qkv_bias (bool): If True, add a learnable bias to query, key, value. Default: True
        drop_rate (float): Dropout rate. Default: 0
        attn_drop_rate (float): Attention dropout rate. Default: 0
        drop_path_rate (float): Stochastic depth rate. Default: 0.1
        norm_layer (nn.Module): Normalization layer. Default: nn.LayerNorm.
        ape (bool): If True, add absolute position embedding to the patch embedding. Default: False
        patch_norm (bool): If True, add normalization after patch embedding. Default: True
        use_checkpoint (bool): Whether to use checkpointing to save memory. Default: False
        upscale: Upscale factor. 2/3/4/8 for image SR, 1 for denoising and compress artifact reduction
        img_range: Image range. 1. or 255.
        upsampler: The reconstruction reconstruction module. 'pixelshuffle'/'pixelshuffledirect'/'nearest+conv'/None
        resi_connection: The convolutional block before residual connection. '1conv'/'3conv'
    @   r!   r"   r      r  r  r  r   r   Tr   g?Fr#   r?    r   c                    s  t t|   |}|}d}|| _|dkrFd}t|dddd| _ntdddd| _|| _	|| _
|| _t||ddd| _t|| _|| _|| _|| _|| _|| _t||||| jr|nd d| _| jj}| jj}|| _t||||| jr|nd d| _| jr$ttd||| _t| jdd tj|
d| _ d	d
 t!d|t"|D }t# | _$t%| jD ]t}t&||d |d f|| || || j|	|
||t"|d | t"|d |d   |d ||||d}| j$'| qb| j
dkrnt# | _(t%| jD ]t}t&||d |d f|| || || j|	|
||t"|d | t"|d |d   |d ||||d}| j('| q|| j| _)|dkrt||ddd| _*nl|dkrt+t||d dddtj,dddt|d |d dddtj,dddt|d |ddd| _*| j
dkrZt+t||dddtj,dd| _-t.||| _/t||ddd| _0nR| j
dkrt||ddd| _1t+t||dddtj,dd| _-t||ddd| _2t+td|dddtj,dd| _3t.||| _/t||ddd| _0n| j
dkrt+t||dddtj,dd| _-t.||| _/t4||| _5t||ddd| _0t+t||dddtj,dd| _6t||ddd| _7t+t||dddtj,dd| _8t||ddd| _9n| j
dkrt:||||d |d f| _/n| j
dkr| j	dksJ dt+t||dddtj,dd| _-t||ddd| _;t||ddd| _<t||ddd| _=t||ddd| _0tj,ddd| _>nt||ddd| _0| ?| j@ d S )Nr  r"   )gw#?g8EGr?gB`"?r!   r   {Gz?std)pc                 S   s   g | ]}|  qS r   )item)r   r   r   r   r   r         z$Swin2SR.__init__.<locals>.<listcomp>r   )rC   r   r   rE   r+   r   rc   r   r^   r   r   r   r   r   r   r   pixelshuffle_hfr   r   r$   r   Tr   pixelshuffler;   pixelshuffle_auxpixelshuffledirectnearest+convzonly support x4 now.)Ar   r  r	   	img_rangerG   Tensorr(   meanr[   upscale	upsamplerr+   r
   r   
conv_firstlen
num_layersr   ape
patch_normnum_featuresr   r   r   r   r   r   r   rF   absolute_pos_embedr   r   pos_droplinspacerY   r   layersr   r   r   	layers_hfr   conv_after_bodyrK   r   conv_before_upsampler   upsample	conv_lastconv_bicubicconv_auxconv_after_auxr   upsample_hfconv_first_hfconv_after_body_hfconv_before_upsample_hfconv_last_hfr   conv_up1conv_up2conv_hrlreluapply_init_weights)r   r   r   r   r   depthsrE   r+   r   rc   	drop_rateattn_drop_ratedrop_path_rater   r  r  r   r  r  r  r   kwargs	num_in_chr  r   rgb_meanr   r   dpri_layerlayerr   r   r   r	     s   

&
&








zSwin2SR.__init__c                 C   sr   t |tjrBt|jdd t |tjrn|jd urntj|jd n,t |tjrntj|jd tj|jd d S )Nr  r  r   r?   )	r   r
   r   r   rl   r:   r   r   r   )r   r   r   r   r   r3  f  s    zSwin2SR._init_weightsc                 C   s   dhS )Nr  r   r   r   r   r   no_weight_decayo  s    zSwin2SR.no_weight_decayc                 C   s   dhS )Nr   r   r   r   r   r   no_weight_decay_keywordss  s    z Swin2SR.no_weight_decay_keywordsc                 C   sV   |  \}}}}| j|| j  | j }| j|| j  | j }t|d|d|fd}|S )Nr   reflect)sizer+   rr   pad)r   r   r   r   r   	mod_pad_h	mod_pad_wr   r   r   check_image_sizew  s
    zSwin2SR.check_image_sizec                 C   sh   |j d |j d f}| |}| jr.|| j }| |}| jD ]}|||}q>| |}| ||}|S Nr#   r"   )r'   r   r  r  r  r   r   r   r   r   r   r=  r   r   r   forward_features~  s    




zSwin2SR.forward_featuresc                 C   sh   |j d |j d f}| |}| jr.|| j }| |}| jD ]}|||}q>| |}| ||}|S rF  )r'   r   r  r  r  r!  r   r   rG  r   r   r   forward_features_hf  s    




zSwin2SR.forward_features_hfc              	   C   s  |j dd  \}}| |}| j|| _|| j | j }| jdkr| |}| | || }| 	|}| 
| |}nt| jdkrptj||| j || j fddd}| |}| |}| | || }| 	|}| |}| |}| |d d d d d || j d || j f |d d d d d || j d || j f  }| 
|}|| j | j }n| jdkr| |}| | || }| 	|}| 
| |}| |}| | || }| |}| | |}|| }|| j | j }n| jdkr<| |}| | || }| |}n| jd	kr| |}| | || }| 	|}| | tjjj|dd
d}| | tjjj|dd
d}| 
| | |}n,| |}	| | |	|	 }
|| 
|
 }|| j | j }| jdkr@|d d d d d || j d || j f |fS | jdkr|| j | j }|d d d d d || j d || j f |d d d d d || j d || j f |d d d d d || j d || j f fS |d d d d d || j d || j f S d S )Nr#   r  r  bicubicF)rA  modealign_cornersr  r  r  nearest)scale_factorrK  )r'   rE  r  type_asr  r  r  r"  rH  r#  r%  r$  rr   interpolater  r&  r'  r(  r*  r+  rI  r,  r-  r)  r1  r.  rG   r
   
functionalr/  r0  )r   r   r-   r.   rJ  auxZx_beforex_outZx_hfx_firstresr   r   r   r     sh    



"




^







  
0zSwin2SR.forwardc                 C   s|   d}| j \}}||| d | j d 7 }|| j 7 }| jD ]}|| 7 }q<||| d | j | j 7 }|| j 7 }|S )Nr   r"   r   )r   r   r   r   r   r$  )r   r   r-   r.   r=  r   r   r   r     s    

zSwin2SR.flops)r   r   r   r   r
   r   r	   r3  rG   jitignorer>  r?  rE  rH  rI  r   r   r    r   r   r   r   r    s&   
 +	

Dr  __main__r$   r>   i   r!   i  r#   r?   r  <   r  )	r  r   r+   r  r4  r   rE   r   r  g    eAr"   )+r   numpyrV   rG   torch.nnr
   Ztorch.nn.functionalrQ  rr   torch.utils.checkpointutilsr   timm.models.layersr   r   r   Moduler   r1   r3   r4   r   r   r   r   r   r   rK   r   r   r   r  r   r  r+   heightwidthmodelprintr   randnr   r'   r   r   r   r   <module>   sL     /M.J"  M


