a
    Adʏ                     @   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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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__ S/var/www/html/stable-diffusion-webui/extensions-builtin/SwinIR/swinir_model_arch.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    	$r2   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+   )r1   r,   r.   r/   r-   r   r   r   r   window_reverse0   s    $r4   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
        qk_scale (float | None, optional): Override default qk scale of head_dim ** -0.5 if set
        attn_drop (float, optional): Dropout ratio of attention weight. Default: 0.0
        proj_drop (float, optional): Dropout ratio of output. Default: 0.0
    TNr   c                    s  t    || _|| _|| _|| }|p.|d | _tt	d|d  d d|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| _t|| _t||| _t|| _t| j
d	d
 tjdd| _d S )Ng      r$   r   r"   r'   relative_position_indexr#   bias{Gz?std)dim)r   r	   r<   r,   	num_headsscaler
   	Parametertorchzerosrelative_position_bias_tablearangestackmeshgridflattenr*   r+   sumregister_bufferr   qkvr   	attn_dropproj	proj_dropr   Softmaxsoftmax)r   r<   r,   r=   qkv_biasqk_scalerJ   rL   head_dimcoords_hcoords_wcoordscoords_flattenrelative_coordsr6   r   r   r   r	   O   s4    
&,((,
zWindowAttention.__init__c                 C   sl  |j \}}}| |||d| j|| j ddddd}|d |d |d   }}}	|| j }||dd }
| j| j	d 	| j
d | j
d  | j
d | j
d  d}|ddd }|
|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
        r#   r$   r   r"   r%   r'   N)r(   rI   reshaper=   r*   r>   	transposerB   r6   r)   r,   r+   	unsqueezerN   rJ   rK   rL   )r   r   maskB_Nr0   rI   qkvattnrelative_position_biasnWr   r   r   r   r   s*    .
&

(



zWindowAttention.forwardreturnc                 C   s   d| j  d| j d| j S )Ndim=, window_size=, num_heads=)r<   r,   r=   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#   )r<   r=   )r   r]   flopsr   r   r   rk      s    zWindowAttention.flops)TNr   r   )N)
r   r   r   __doc__r	   r   strrj   rk   r!   r   r   r   r   r5   A   s
   #
!r5   c                
       s`   e Zd ZdZddddddddejejf
 fdd		Zd
d Zdd Z	e
dddZdd Z  ZS )SwinTransformerBlocka   Swin Transformer Block.

    Args:
        dim (int): Number of input channels.
        input_resolution (tuple[int]): Input resolution.
        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
        qk_scale (float | None, optional): Override default qk scale of head_dim ** -0.5 if set.
        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
       r         @TNr   c              	      s  t    || _|| _|| _|| _|| _|| _t| j| jkrPd| _t| j| _d| j  krh| jk srn J d||| _	t
|t| j||||
|	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,   r=   rO   rP   rJ   rL   r   )r   r   r   r   	attn_mask)r   r	   r<   input_resolutionr=   r,   
shift_size	mlp_ratiominnorm1r5   r   ra   r   r
   Identity	drop_pathnorm2r3   r   mlpcalculate_maskrH   )r   r<   rr   r=   r,   rs   rt   rO   rP   r   rJ   rx   r   
norm_layermlp_hidden_dimrq   r   r   r   r	      s0    
"


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   )
r@   rA   slicer,   rs   r2   r)   rZ   masked_fillfloat)r   x_sizer.   r/   img_maskh_slicesw_slicescnthwmask_windowsrq   r   r   r   r{      s(    $z#SwinTransformerBlock.calculate_maskc                 C   sD  |\}}|j \}}}|}| |}|||||}| jdkrZt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rtj|	| j| jfdd}n|	}|||| |}|| | }|| | | | }|S )Nr   )r"   r$   )shiftsdimsr'   )r[   )r(   rv   r)   rs   r@   rollr2   r,   rr   ra   rq   r{   todevicer4   rx   rz   ry   )r   r   r   r.   r/   r-   Lr0   shortcut	shifted_x	x_windowsattn_windowsr   r   r   r      s,    


zSwinTransformerBlock.forwardrd   c                 C   s4   d| j  d| j d| j d| j d| j d| j S )Nrf   , input_resolution=rh   rg   z, shift_size=z, mlp_ratio=)r<   rr   r=   r,   rs   rt   ri   r   r   r   rj     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$   )rr   r<   r,   ra   rk   rt   )r   rk   r.   r/   rc   r   r   r   rk     s    
"zSwinTransformerBlock.flops)r   r   r   rl   r
   r    	LayerNormr	   r{   r   rm   rj   rk   r!   r   r   r   r   rn      s   !*rn   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$   Fr7   )r   r	   rr   r<   r
   r   	reductionnorm)r   rr   r<   r|   r   r   r   r	   5  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%   )rr   r(   r)   r@   catr   r   )r   r   r.   r/   r-   r   r0   x0x1x2x3r   r   r   r   <  s    
.$$$$

zPatchMerging.forwardrd   c                 C   s   d| j  d| j S )Nzinput_resolution=z, dim=rr   r<   ri   r   r   r   rj   S  s    zPatchMerging.extra_reprc                 C   sD   | j \}}|| | j }||d |d  d | j d | j 7 }|S )Nr$   r%   r   r   r.   r/   rk   r   r   r   rk   V  s    
(zPatchMerging.flopsr   r   r   rl   r
   r   r	   r   rm   rj   rk   r!   r   r   r   r   r   ,  s
   r   c                	       sT   e Zd ZdZddddddejddf	 fdd	Zd	d
 Zed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
        qk_scale (float | None, optional): Override default qk scale of head_dim ** -0.5 if set.
        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.
    rp   TNr   Fc                    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rD| ndqS )r$   r   )r<   rr   r=   r,   rs   rt   rO   rP   r   rJ   rx   r|   )rn   
isinstancelist).0irJ   r<   r   rx   rr   rt   r|   r=   rP   rO   r,   r   r   
<listcomp>|  s   	z'BasicLayer.__init__.<locals>.<listcomp>)r<   r|   )r   r	   r<   rr   depthuse_checkpointr
   
ModuleListrangeblocks
downsample)r   r<   rr   r   r=   r,   rt   rO   rP   r   rJ   rx   r|   r   r   r   r   r   r	   q  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.forwardrd   c                 C   s   d| j  d| j d| j S )Nrf   r   z, depth=)r<   rr   r   ri   r   r   r   rj     s    zBasicLayer.extra_reprc                 C   s8   d}| j D ]}|| 7 }q
| jd ur4|| j 7 }|S Nr   )r   rk   r   )r   rk   r   r   r   r   rk     s    

zBasicLayer.flopsr   r   r   r   r   r   ]  s   


r   c                       sL   e Zd ZdZd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 )RSTBa  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
        qk_scale (float | None, optional): Override default qk scale of head_dim ** -0.5 if set.
        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.
    rp   TNr   F   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 d| _t||d
|d d| _d S )N)r<   rr   r   r=   r,   rt   rO   rP   r   rJ   rx   r|   r   r   r   r#   r"   3convr%   皙?Tnegative_slopeinplacer   img_size
patch_sizein_chans	embed_dimr|   )r   r   r	   r<   rr   r   residual_groupr
   Conv2dconv
Sequential	LeakyReLU
PatchEmbedpatch_embedPatchUnEmbedpatch_unembed)r   r<   rr   r   r=   r,   rt   rO   rP   r   rJ   rx   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   rk   rr   r<   r   r   r   rk   r.   r/   r   r   r   rk     s    
z
RSTB.flops)
r   r   r   rl   r
   r   r	   r   rk   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   ax   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%   r#   `   Nc                    s   t    t|}t|}|d |d  |d |d  g}|| _|| _|| _|d |d  | _|| _|| _|d ur~||| _	nd | _	d S Nr   r"   )
r   r	   r   r   r   patches_resolutionnum_patchesr   r   r   r   r   r   r   r   r|   r   r   r   r   r	     s    
 zPatchEmbed.__init__c                 C   s*   | ddd}| jd ur&| |}|S )Nr$   r"   )rF   rY   r   r   r   r   r   r     s    

zPatchEmbed.forwardc                 C   s.   d}| j \}}| jd ur*||| | j 7 }|S r   )r   r   r   r   r   r   r   rk     s
    

zPatchEmbed.flops)r   r%   r#   r   Nr   r   r   rl   r	   r   rk   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	   %  s    
 zPatchUnEmbed.__init__c                 C   s2   |j \}}}|dd|| j|d |d }|S )Nr"   r$   r   )r(   rY   r)   r   )r   r   r   r-   HWr0   r   r   r   r   2  s    "zPatchUnEmbed.forwardc                 C   s   d}|S r   r   )r   rk   r   r   r   rk   7  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 )UpsamplezUpsample 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   r3   mathlogappendr
   r   PixelShuffle
ValueErrorr   r   r	   )r   r>   num_featm_r   r   r   r	   D  s    zUpsample.__init__)r   r   r   rl   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   rr   r   r
   r   r   r   r   r	   )r   r>   r   
num_out_chrr   r   r   r   r   r	   \  s     zUpsampleOneStep.__init__c                 C   s$   | j \}}|| | j d d }|S )Nr#   r   )rr   r   r   r   r   r   rk   d  s    
zUpsampleOneStep.flops)N)r   r   r   rl   r	   rk   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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  ZS )"SwinIRa   SwinIR
        A PyTorch impl of : `SwinIR: Image Restoration Using Swin Transformer`, based on Swin Transformer.

    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
        qk_scale (float): Override default qk scale of head_dim ** -0.5 if set. Default: None
        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   ro   rp   TNr   g?Fr$         ? 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 ]v}t&||d |d f|| || || j|	|
|||t"|d | t"|d |d   |d ||||d}| j$'| qb|| j| _(|dkrt||ddd| _)nl|dkrrt*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rt*t||dddtj+dd| _,t-||| _.t||ddd| _/n| j
dkrt0||||d |d f| _.n| j
dkrt*t||dddtj+dd| _,t||ddd| _1| j	dkrRt||ddd| _2t||ddd| _3t||ddd| _/tj+ddd| _4nt||ddd| _/| 5| j6 d S )Nr   r#   )gw#?g8EGr?gB`"?r"   r   r9   r:   )pc                 S   s   g | ]}|  qS r   )item)r   r   r   r   r   r         z#SwinIR.__init__.<locals>.<listcomp>r   )r<   rr   r   r=   r,   rt   rO   rP   r   rJ   rx   r|   r   r   r   r   r   r   r   r%   r   Tr   pixelshuffle)r   pixelshuffledirectnearest+conv)7r   r   r	   	img_ranger@   Tensorr)   meanrA   upscale	upsamplerr,   r
   r   
conv_firstlen
num_layersr   ape
patch_normnum_featuresrt   r   r   r   r   r   r   r?   absolute_pos_embedr   r   pos_droplinspacerG   r   layersr   r   r   r   conv_after_bodyr   r   conv_before_upsampler   upsample	conv_lastr   conv_up1conv_up2conv_hrlreluapply_init_weights) r   r   r   r   r   depthsr=   r,   rt   rO   rP   	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SwinIR.__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 )Nr9   r:   r   r   )	r   r
   r   r   weightr8   init	constant_r   )r   r   r   r   r   r     s    zSwinIR._init_weightsc                 C   s   dhS )Nr   r   ri   r   r   r   no_weight_decay  s    zSwinIR.no_weight_decayc                 C   s   dhS )NrB   r   ri   r   r   r   no_weight_decay_keywords  s    zSwinIR.no_weight_decay_keywordsc                 C   sV   |  \}}}}| j|| j  | j }| j|| j  | j }t|d|d|fd}|S )Nr   reflect)sizer,   Fpad)r   r   r   r   r   	mod_pad_h	mod_pad_wr   r   r   check_image_size  s
    zSwinIR.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SwinIR.forward_featuresc              	   C   s  |j dd  \}}| |}| j|| _|| j | j }| jdkr~| |}| | || }| 	|}| 
| |}n| jdkr| |}| | || }| |}n| jdkrJ| |}| | || }| 	|}| | tjjj|ddd}| jdkr2| | tjjj|ddd}| 
| | |}n,| |}| | || }|| 
| }|| j | j }|d d d d d || j d || j f S )Nr$   r   r   r   nearest)scale_factormoder%   )r(   r  r   type_asr   r   r   r   r  r   r   r   r   r   r@   r
   
functionalinterpolater   r   r   )r   r   r.   r/   x_firstresr   r   r   r   %  s4    







  
zSwinIR.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   rk   r   r   )r   rk   r.   r/   r
  r   r   r   rk   J  s    

zSwinIR.flops)r   r   r   rl   r
   r   r	   r   r@   jitignorer  r  r  r  r   rk   r!   r   r   r   r   r   j  s"   
x	

%r   __main__r%      i   r"   i  r$   r   r   <   r   )	r   r   r,   r   r  r   r=   rt   r   g    eAr#   )(r   r@   torch.nnr
   Ztorch.nn.functionalr  r  torch.utils.checkpointutilsr   timm.models.layersr   r   r   Moduler   r2   r4   r5   rn   r   r   r   r   r   r   r   r   r   r   r   r,   heightwidthmodelprintrk   randnr   r(   r   r   r   r   <module>   sD   c 	1FL+" m


