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Z ddl	m
Z
mZ d3eedœdd	„ZG d
d„ dejƒ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e ¡ G d$d%„ d%ejƒƒZe d&krìd'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/d0	Z%e&e%ƒ e&e#e$e% '¡ d1 ƒ e (dd2e#e$f¡Z)e%e)ƒZ)e&e)j*ƒ dS )4é    N)ÚARCH_REGISTRYé   )Ú	to_2tupleÚtrunc_normal_ç        F)Ú	drop_probÚtrainingc                 C   sd   |dks|s| S d| }| j d fd| jd   }|tj|| j| jd }| ¡  |  |¡| }|S )zÁDrop paths (Stochastic Depth) per sample (when applied in main path of residual blocks).

    From: https://github.com/rwightman/pytorch-image-models/blob/master/timm/models/layers/drop.py
    r   r   r   )r   )ÚdtypeÚdevice)ÚshapeÚndimÚtorchZrandr	   r
   Zfloor_Údiv)Úxr   r   Z	keep_probr   Zrandom_tensorÚoutput© r   úb/var/www/html/stable-diffusion-webui/venv/lib/python3.9/site-packages/basicsr/archs/swinir_arch.pyÚ	drop_path   s    r   c                       s*   e Zd ZdZd‡ fdd„	Zdd„ Z‡  ZS )ÚDropPathzÂDrop paths (Stochastic Depth) per sample  (when applied in main path of residual blocks).

    From: https://github.com/rwightman/pytorch-image-models/blob/master/timm/models/layers/drop.py
    Nc                    s   t t| ƒ ¡  || _d S ©N)Úsuperr   Ú__init__r   )Úselfr   ©Ú	__class__r   r   r   #   s    zDropPath.__init__c                 C   s   t || j| jƒS r   )r   r   r   ©r   r   r   r   r   Úforward'   s    zDropPath.forward)N)Ú__name__Ú
__module__Ú__qualname__Ú__doc__r   r   Ú__classcell__r   r   r   r   r      s   r   c                       s0   e Zd Zddejdf‡ fdd„	Zdd„ Z‡  ZS )ÚMlpNr   c                    sN   t ƒ  ¡  |p|}|p|}t ||¡| _|ƒ | _t ||¡| _t |¡| _d S r   )	r   r   ÚnnÚLinearÚfc1ÚactÚfc2ÚDropoutÚdrop)r   Úin_featuresÚhidden_featuresZout_featuresÚ	act_layerr)   r   r   r   r   -   s    
zMlp.__init__c                 C   s6   |   |¡}|  |¡}|  |¡}|  |¡}|  |¡}|S r   )r%   r&   r)   r'   r   r   r   r   r   6   s    




zMlp.forward)r   r   r   r#   ÚGELUr   r   r!   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   r   é   é   é   é   éÿÿÿÿ)r   ÚviewÚpermuteÚ
contiguous)r   Úwindow_sizeÚbÚhÚwÚcÚwindowsr   r   r   Úwindow_partition?   s    	$r<   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   r2   r   r.   r/   r0   r1   )Úintr   r3   r4   r5   )r;   r6   r8   r9   r7   r   r   r   r   Úwindow_reverseN   s    $r>   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   r2   Úrelative_position_indexr.   ©Úbiasç{®Gáz”?©Zstd)Údim)r   r   rE   r6   Ú	num_headsÚscaler#   Ú	Parameterr   ÚzerosÚrelative_position_bias_tableZarangeÚstackZmeshgridÚflattenr4   r5   ÚsumÚregister_bufferr$   Úqkvr(   Ú	attn_dropÚprojÚ	proj_dropr   ZSoftmaxÚsoftmax)r   rE   r6   rF   Úqkv_biasÚqk_scalerP   rR   Zhead_dimZcoords_hZcoords_wZcoordsZcoords_flattenZrelative_coordsr@   r   r   r   r   m   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   r0   éþÿÿÿr2   N)r   rO   ZreshaperF   r4   rG   Ú	transposerJ   r@   r3   r6   r5   Ú	unsqueezerS   rP   rQ   rR   )r   r   ÚmaskZb_Únr:   rO   ÚqÚkÚvÚattnZrelative_position_biasÚnwr   r   r   r      s*    .
&ÿ

(



zWindowAttention.forward©Úreturnc                 C   s   d| j › d| j› d| j› S )Núdim=ú, window_size=ú, num_heads=)rE   r6   rF   ©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.   )rE   rF   )r   rZ   Úflopsr   r   r   rg   ´   s    zWindowAttention.flops)TNr   r   )N)
r   r   r   r    r   r   Ústrrf   rg   r!   r   r   r   r   r?   _   s
   #
!r?   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rªt|ƒnt ¡ | _||ƒ| _t|| ƒ}t||||	d| _| jdkrô|  | j¡}nd }|  d|¡ d S )Nr   z shift_size must in 0-window_size)r6   rF   rT   rU   rP   rR   r   )r*   r+   r,   r)   Ú	attn_mask)r   r   rE   Úinput_resolutionrF   r6   Ú
shift_sizeÚ	mlp_ratioÚminÚnorm1r?   r   r^   r   r#   ZIdentityr   Únorm2r=   r"   ÚmlpÚcalculate_maskrN   )r   rE   rm   rF   r6   rn   ro   rT   rU   r)   rP   r   r,   Ú
norm_layerZmlp_hidden_dimrl   r   r   r   r   Õ   s:    
"
ù	

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 }q‚qzt|| jƒ}| d| j| j ¡}| d¡| d¡ }	|	 |	dkt	dƒ¡ |	dkt	dƒ¡}	|	S )Nr   r   r2   r/   g      YÀr   )
r   rI   Úslicer6   rn   r<   r3   rX   Zmasked_fillÚfloat)
r   Úx_sizer8   r9   Zimg_maskZh_slicesZw_slicesZcntZmask_windowsrl   r   r   r   rt     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/   )ZshiftsÚdimsr2   )rY   )r   rq   r3   rn   r   Zrollr<   r6   rm   r^   rl   rt   Útor
   r>   r   rs   rr   )r   r   rx   r8   r9   r7   Ú_r:   ZshortcutZ	shifted_xZ	x_windowsZ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 )Nrb   ú, input_resolution=rd   rc   z, shift_size=z, mlp_ratio=)rE   rm   rF   r6   rn   ro   re   r   r   r   rf   E  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/   )rm   rE   r6   r^   rg   ro   )r   rg   r8   r9   r_   r   r   r   rg   I  s    
"zSwinTransformerBlock.flops)r   r   r   r    r#   r-   Ú	LayerNormr   rt   r   rh   rf   rg   r!   r   r   r   r   ri   Â   s    ó1*ri   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 )Nr0   r/   FrA   )r   r   rm   rE   r#   r$   Ú	reductionÚnorm)r   rm   rE   ru   r   r   r   r   a  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   r2   r0   )rm   r   r3   r   Úcatr€   r   )r   r   r8   r9   r7   Zseq_lenr:   Zx0Úx1Zx2Zx3r   r   r   r   h  s    
.$$$$

zPatchMerging.forwardr`   c                 C   s   d| j › d| j› S )Nzinput_resolution=z, dim=©rm   rE   re   r   r   r   rf     s    zPatchMerging.extra_reprc                 C   sD   | j \}}|| | j }||d |d  d | j d | j 7 }|S )Nr/   r0   r„   ©r   r8   r9   rg   r   r   r   rg   ‚  s    
(zPatchMerging.flops©r   r   r   r    r#   r}   r   r   rh   rf   rg   r!   r   r   r   r   r~   X  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.
    rk   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   )rE   rm   rF   r6   rn   ro   rT   rU   r)   rP   r   ru   )ri   Ú
isinstanceÚlist)Ú.0Úi©rP   rE   r)   r   rm   ro   ru   rF   rU   rT   r6   r   r   Ú
<listcomp>´  s   ôôz'BasicLayer.__init__.<locals>.<listcomp>)rE   ru   )r   r   rE   rm   ÚdepthÚuse_checkpointr#   Ú
ModuleListÚrangeÚblocksÚ
downsample)r   rE   rm   rŽ   rF   r6   ro   rT   rU   r)   rP   r   ru   r“   r   r   rŒ   r   r     s    
"ó
zBasicLayer.__init__c                 C   sB   | j D ]"}| jrt ||¡}q|||ƒ}q| jd ur>|  |¡}|S r   )r’   r   Ú
checkpointr“   )r   r   rx   Úblkr   r   r   r   Ê  s    


zBasicLayer.forwardr`   c                 C   s   d| j › d| j› d| j› S )Nrb   r|   z, depth=)rE   rm   rŽ   re   r   r   r   rf   Ô  s    zBasicLayer.extra_reprc                 C   s8   d}| j D ]}|| ¡ 7 }q
| jd ur4|| j ¡ 7 }|S ©Nr   )r’   rg   r“   )r   rg   r•   r   r   r   rg   ×  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.
    rk   TNr   Féà   r0   Ú1convc                    sô   t t| ƒ ¡  || _|| _t|||||||||	|
||||d| _|dkr^t ||ddd¡| _	nj|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¡¡| _	t||d
|d d| _t||d
|d d| _d S )N)rE   rm   rŽ   rF   r6   ro   rT   rU   r)   rP   r   ru   r“   r   r™   r.   r   Ú3convr0   çš™™™™™É?T©Znegative_slopeÚinplacer   ©Úimg_sizeÚ
patch_sizeÚin_chansÚ	embed_dimru   )r   r—   r   rE   rm   r‡   Úresidual_groupr#   ÚConv2dÚconvÚ
SequentialÚ	LeakyReLUÚ
PatchEmbedÚpatch_embedÚPatchUnEmbedÚpatch_unembed)r   rE   rm   rŽ   rF   r6   ro   rT   rU   r)   rP   r   ru   r“   r   rŸ   r    Úresi_connectionr   r   r   r   ÷  sB    ò $ý
ÿ
ÿzRSTB.__init__c              
   C   s$   |   |  |  |  ||¡|¡¡¡| S r   )r©   r¥   r«   r£   ©r   r   rx   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£   rg   rm   rE   r©   r«   ©r   rg   r8   r9   r   r   r   rg   0  s    
z
RSTB.flops)
r   r   r   r    r#   r}   r   r   rg   r!   r   r   r   r   r—   à  s    ï6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˜   r0   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¢   ru   r²   r   r   r   r   F  s    
 zPatchEmbed.__init__c                 C   s*   |  d¡ dd¡}| jd ur&|  |¡}|S )Nr/   r   )rL   rW   r€   r   r   r   r   r   X  s    

zPatchEmbed.forwardc                 C   s.   d}| j \}}| jd ur*||| | j 7 }|S r–   )rŸ   r€   r¢   r¯   r   r   r   rg   ^  s
    

zPatchEmbed.flops)r˜   r0   r.   r°   N©r   r   r   r    r   r   rg   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˜   r0   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   q  s    
 zPatchUnEmbed.__init__c                 C   s,   |  dd¡ |jd | j|d |d ¡}|S )Nr   r/   r   )rW   r3   r   r¢   r­   r   r   r   r   ~  s    (zPatchUnEmbed.forwardc                 C   s   d}|S r–   r   )r   rg   r   r   r   rg   ‚  s    zPatchUnEmbed.flops)r˜   r0   r.   r°   Nrµ   r   r   r   r   rª   f  s   
rª   c                       s    e Zd ZdZ‡ fdd„Z‡  ZS )ÚUpsamplez¡Upsample 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/   r0   r.   r®   zscale z/ is not supported. Supported scales: 2^n and 3.)r‘   r=   ÚmathÚlogÚappendr#   r¤   ÚPixelShuffleÚ
ValueErrorr   r¶   r   )r   rG   Únum_featÚmr{   r   r   r   r     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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¼   rm   r¹   r#   r¤   rº   r   r¾   r   )r   rG   r¼   Ú
num_out_chrm   r½   r   r   r   r   §  s     zUpsampleOneStep.__init__c                 C   s$   | j \}}|| | j d d }|S )Nr.   r®   )rm   r¼   r…   r   r   r   rg   ¯  s    
zUpsampleOneStep.flops)N)r   r   r   r    r   rg   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‡  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Ã   rj   rk   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# &|¡ q\|| jƒ| _'|dkr t ||ddd¡| _(nl|dkrlt )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r¾t )t ||ddd¡tj*dd¡| _+t,||ƒ| _-t ||ddd¡| _.nä| j
dkrèt/||||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¡| _0t ||ddd¡| _1t ||ddd¡| _2t ||ddd¡| _.tj*ddd| _3nt ||ddd¡| _.|  4| j5¡ d S )NrÁ   r.   )gšwœ¢#¹Ü?gï8EGrùÛ?gB`åÐ"ÛÙ?r   rž   rC   rD   )Úpc                 S   s   g | ]}|  ¡ ‘qS r   )Úitem)rŠ   r   r   r   r   r     ó    z#SwinIR.__init__.<locals>.<listcomp>r   )rE   rm   rŽ   rF   r6   ro   rT   rU   r)   rP   r   ru   r“   r   rŸ   r    r¬   r™   rš   r0   r›   Trœ   Úpixelshuffle)r   Úpixelshuffledirectúnearest+convzonly support x4 now.)6r   rÀ   r   Ú	img_ranger   ZTensorr3   ÚmeanrI   ÚupscaleÚ	upsamplerr#   r¤   Ú
conv_firstÚlenZ
num_layersr¢   ÚapeÚ
patch_normZnum_featuresro   r¨   r©   r³   r²   rª   r«   rH   Úabsolute_pos_embedr   r(   Úpos_dropZlinspacerM   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¢   ÚdepthsrF   r6   ro   rT   rU   Z	drop_rateZattn_drop_rateZdrop_path_rateru   rÒ   rÓ   r   rÎ   rÌ   rÏ   r¬   ÚkwargsZ	num_in_chr¿   r¼   Zrgb_meanr³   r²   ZdprZ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 )NrC   rD   r   rÄ   )	rˆ   r#   r$   r   ZweightrB   ÚinitZ	constant_r}   )r   r½   r   r   r   rà   [  s    zSwinIR._init_weightsc                 C   s   dhS )NrÔ   r   re   r   r   r   Úno_weight_decayd  s    zSwinIR.no_weight_decayc                 C   s   dhS )NrJ   r   re   r   r   r   Úno_weight_decay_keywordsh  s    zSwinIR.no_weight_decay_keywordsc                 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   rx   rã   r   r   r   Úforward_featuresl  s    




zSwinIR.forward_featuresc              	   C   sb  | j  |¡| _ || j  | j }| jdkrb|  |¡}|  |  |¡¡| }|  |¡}|  |  	|¡¡}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  }|S )NrÉ   rÊ   rË   r/   Znearest)Zscale_factorÚmode)rÍ   Ztype_asrÌ   rÏ   rÐ   r×   rç   rØ   rÚ   rÙ   rÞ   rÛ   r   r#   Z
functionalZinterpolaterÜ   rÝ   )r   r   Zx_firstÚresr   r   r   r   {  s.    






  
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©   rg   rÖ   rÙ   )r   rg   r8   r9   rã   r   r   r   rg   œ  s    

zSwinIR.flops)r   r   r   r    r#   r}   r   rà   r   ZjitÚignorerå   ræ   rç   r   rg   r!   r   r   r   r   rÀ   µ  s@   ë 
	

!rÀ   Ú__main__r0   é   i   iÐ  r/   rÄ   rÂ   é<   rÊ   )	rÎ   rŸ   r6   rÌ   rá   r¢   rF   ro   rÏ   g    eÍÍAr.   )r   F)+r·   r   Ztorch.nnr#   Ztorch.utils.checkpointÚutilsr”   Zbasicsr.utils.registryr   Z	arch_utilr   r   rw   Úboolr   ÚModuler   r"   r<   r>   r?   ri   r~   r‡   r—   r¨   rª   r¦   r¶   r¾   ÚregisterrÀ   r   rÎ   r6   ÚheightÚwidthÚmodelÚprintrg   Zrandnr   r   r   r   r   r   Ú<module>   sX   c 1W[+! s
÷
