a
    du                     @   s  d dl Z d dlZd dlZd dlmZ d dlmZ d dlmZm	Z	 d dl
mZ d dlmZ G dd dej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e 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 dS )'    N)nn)
functional)FusedLeakyReLUfused_leaky_relu)	upfirdn2d)ARCH_REGISTRYc                   @   s   e Zd Zdd ZdS )NormStyleCodec                 C   s"   |t t j|d dddd  S )zNormalize the style codes.

        Args:
            x (Tensor): Style codes with shape (b, c).

        Returns:
            Tensor: Normalized tensor.
              T)Zdimkeepdim:0yE>)torchrsqrtmeanselfx r   e/var/www/html/stable-diffusion-webui/venv/lib/python3.9/site-packages/basicsr/archs/stylegan2_arch.pyforward   s    	zNormStyleCode.forwardN)__name__
__module____qualname__r   r   r   r   r   r      s   r   c                 C   sJ   t j| t jd} | jdkr:| dddf | dddf  } | |   } | S )zMake resampling kernel for UpFirDn.

    Args:
        k (list[int]): A list indicating the 1D resample kernel magnitude.

    Returns:
        Tensor: 2D resampled kernel.
    )Zdtyper
   N)r   Ztensorfloat32ndimsum)kr   r   r   make_resample_kernel   s
    	
 r   c                       s2   e Zd ZdZd	 fdd	Zdd Zdd Z  ZS )
UpFirDnUpsamplea  Upsample, FIR filter, and downsample (upsampole version).

    References:
    1. https://docs.scipy.org/doc/scipy/reference/generated/scipy.signal.upfirdn.html  # noqa: E501
    2. http://www.ece.northwestern.edu/local-apps/matlabhelp/toolbox/signal/upfirdn.html  # noqa: E501

    Args:
        resample_kernel (list[int]): A list indicating the 1D resample kernel
            magnitude.
        factor (int): Upsampling scale factor. Default: 2.
    r	   c                    sX   t t|   t||d  | _|| _| jjd | }|d d | d |d f| _d S )Nr	   r   r
   )superr   __init__r   kernelfactorshapepadr   resample_kernelr"   r$   	__class__r   r   r    8   s
    zUpFirDnUpsample.__init__c                 C   s"   t || j|| jd| jd}|S Nr
   )ZupZdownr$   r   r!   type_asr"   r$   r   r   outr   r   r   r   @   s    zUpFirDnUpsample.forwardc                 C   s   | j j d| j dS Nz(factor=)r(   r   r"   r   r   r   r   __repr__D   s    zUpFirDnUpsample.__repr__)r	   r   r   r   __doc__r    r   r2   __classcell__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 )
UpFirDnDownsamplezUpsample, FIR filter, and downsample (downsampole version).

    Args:
        resample_kernel (list[int]): A list indicating the 1D resample kernel
            magnitude.
        factor (int): Downsampling scale factor. Default: 2.
    r	   c                    sH   t t|   t|| _|| _| jjd | }|d d |d f| _d S )Nr   r
   r	   )r   r6   r    r   r!   r"   r#   r$   r%   r'   r   r   r    Q   s
    
zUpFirDnDownsample.__init__c                 C   s"   t || j|d| j| jd}|S r)   r*   r,   r   r   r   r   Y   s    zUpFirDnDownsample.forwardc                 C   s   | j j d| j dS r.   r0   r1   r   r   r   r2   ]   s    zUpFirDnDownsample.__repr__)r	   r3   r   r   r'   r   r6   H   s   r6   c                       s2   e Zd ZdZd	 fdd	Zdd Zdd Z  ZS )
UpFirDnSmoothak  Upsample, FIR filter, and downsample (smooth version).

    Args:
        resample_kernel (list[int]): A list indicating the 1D resample kernel
            magnitude.
        upsample_factor (int): Upsampling scale factor. Default: 1.
        downsample_factor (int): Downsampling scale factor. Default: 1.
        kernel_size (int): Kernel size: Default: 1.
    r
   c                    s   t t|   || _|| _t|| _|dkr<| j|d  | _|dkr| jjd | |d  }|d d | d |d d f| _n<|dkr| jjd | |d  }|d d |d f| _nt	d S )Nr
   r	   r   )
r   r7   r    upsample_factordownsample_factorr   r!   r#   r$   NotImplementedError)r   r&   r8   r9   kernel_sizer$   r'   r   r   r    l   s    
$zUpFirDnSmooth.__init__c                 C   s    t || j|dd| jd}|S r)   )r   r!   r+   r$   r,   r   r   r   r   }   s    zUpFirDnSmooth.forwardc                 C   s   | j j d| j d| j dS )Nz(upsample_factor=z, downsample_factor=r/   )r(   r   r8   r9   r1   r   r   r   r2      s    zUpFirDnSmooth.__repr__)r
   r
   r
   r3   r   r   r'   r   r7   a   s   
r7   c                       s2   e Zd ZdZd fdd	Zdd	 Zd
d Z  ZS )EqualLineara  Equalized Linear as StyleGAN2.

    Args:
        in_channels (int): Size of each sample.
        out_channels (int): Size of each output sample.
        bias (bool): If set to ``False``, the layer will not learn an additive
            bias. Default: ``True``.
        bias_init_val (float): Bias initialized value. Default: 0.
        lr_mul (float): Learning rate multiplier. Default: 1.
        activation (None | str): The activation after ``linear`` operation.
            Supported: 'fused_lrelu', None. Default: None.
    Tr   r
   Nc                    s   t t|   || _|| _|| _|| _| jdvr@td| ddt	| | | _
tt|||| _|rtt||| _n| dd  d S )N)fused_lreluNz'Wrong activation value in EqualLinear: z*Supported ones are: ['fused_lrelu', None].r
   bias)r   r<   r    in_channelsout_channelslr_mul
activation
ValueErrormathsqrtscaler   	Parameterr   randnZdiv_weightzerosfill_r>   register_parameter)r   r?   r@   r>   bias_init_valrA   rB   r'   r   r   r       s    
zEqualLinear.__init__c                 C   sb   | j d u rd }n| j | j }| jdkrFt|| j| j }t||}ntj|| j| j |d}|S )Nr=   )r>   )r>   rA   rB   FZlinearrI   rF   r   )r   r   r>   r-   r   r   r   r      s    

zEqualLinear.forwardc                 C   s*   | j j d| j d| j d| jd u dS )N(in_channels=, out_channels=, bias=r/   )r(   r   r?   r@   r>   r1   r   r   r   r2      s
    zEqualLinear.__repr__)Tr   r
   Nr3   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 )ModulatedConv2da  Modulated Conv2d used in StyleGAN2.

    There is no bias in ModulatedConv2d.

    Args:
        in_channels (int): Channel number of the input.
        out_channels (int): Channel number of the output.
        kernel_size (int): Size of the convolving kernel.
        num_style_feat (int): Channel number of style features.
        demodulate (bool): Whether to demodulate in the conv layer.
            Default: True.
        sample_mode (str | None): Indicating 'upsample', 'downsample' or None.
            Default: None.
        resample_kernel (list[int]): A list indicating the 1D resample kernel
            magnitude. Default: (1, 3, 3, 1).
        eps (float): A value added to the denominator for numerical stability.
            Default: 1e-8.
    TNr
      rT   r
   r   c	           	   	      s   t t|   || _|| _|| _|| _|| _|| _| jdkrPt	|dd|d| _
n<| jdkrnt	|dd|d| _
n| jd u rzntd| j ddt||d   | _t||dddd d	| _ttd||||| _|d | _d S )
Nupsampler	   r
   r8   r9   r;   
downsamplezWrong sample mode z6, supported ones are ['upsample', 'downsample', None].Tr>   rM   rA   rB   )r   rR   r    r?   r@   r;   
demodulatesample_modeepsr7   smoothrC   rD   rE   rF   r<   
modulationr   rG   r   rH   rI   padding)	r   r?   r@   r;   num_style_featrY   rZ   r&   r[   r'   r   r   r       s0    	




zModulatedConv2d.__init__c           
      C   s  |j \}}}}| ||d|dd}| j| j | }| jrtt|d	g d| j
 }|||| jddd }||| j || j| j}| jdkr(|d|| ||}||| j|| j| j}|dd|| | j| j| j}tj||dd|d}	|	j|| jg|	j dd R  }	| |	}	n| jdkr| |}|jd|| g|j dd R  }tj||dd|d}	|	j|| jg|	j dd R  }	nH|d|| ||}tj||| j|d	}	|	j|| jg|	j dd R  }	|	S )
zForward function.

        Args:
            x (Tensor): Tensor with shape (b, c, h, w).
            style (Tensor): Tensor with shape (b, num_style_feat).

        Returns:
            Tensor: Modulated tensor after convolution.
        r
   r	   r	   rT      rU   r   )r^   stridegroupsra   rW   )r^   rc   )r#   r]   viewrF   rI   rY   r   r   powr   r[   r@   r;   rZ   Z	transposeZreshaperN   Zconv_transpose2dr\   conv2dr^   )
r   r   stylebchwrI   Zdemodr-   r   r   r   r      s.    
 " 
"" zModulatedConv2d.forwardc                 C   s6   | j j d| j d| j d| j d| j d| j dS )NrO   rP   , kernel_size=z, demodulate=z, sample_mode=r/   )r(   r   r?   r@   r;   rY   rZ   r1   r   r   r   r2     s    zModulatedConv2d.__repr__)TNrS   r   r3   r   r   r'   r   rR      s       %*rR   c                       s,   e Zd ZdZd	 fdd	Zd
ddZ  ZS )	StyleConva=  Style conv.

    Args:
        in_channels (int): Channel number of the input.
        out_channels (int): Channel number of the output.
        kernel_size (int): Size of the convolving kernel.
        num_style_feat (int): Channel number of style features.
        demodulate (bool): Whether demodulate in the conv layer. Default: True.
        sample_mode (str | None): Indicating 'upsample', 'downsample' or None.
            Default: None.
        resample_kernel (list[int]): A list indicating the 1D resample kernel
            magnitude. Default: (1, 3, 3, 1).
    TNrS   c              	      sF   t t|   t|||||||d| _ttd| _	t
|| _d S )N)rY   rZ   r&   r
   )r   rm   r    rR   modulated_convr   rG   r   rJ   rI   r   activate)r   r?   r@   r;   r_   rY   rZ   r&   r'   r   r   r    /  s    zStyleConv.__init__c           	      C   sR   |  ||}|d u r6|j\}}}}||d|| }|| j|  }| |}|S Nr
   )rn   r#   Z	new_emptyZnormal_rI   ro   )	r   r   rg   noiser-   rh   _rj   rk   r   r   r   r   C  s    
zStyleConv.forward)TNrS   )Nr   r   r   r4   r    r   r5   r   r   r'   r   rm      s      rm   c                       s,   e Zd ZdZd	 fdd	Zd
ddZ  ZS )ToRGBaR  To RGB from features.

    Args:
        in_channels (int): Channel number of input.
        num_style_feat (int): Channel number of style features.
        upsample (bool): Whether to upsample. Default: True.
        resample_kernel (list[int]): A list indicating the 1D resample kernel
            magnitude. Default: (1, 3, 3, 1).
    TrS   c                    sZ   t t|   |r"t|dd| _nd | _t|dd|dd d| _tt	
dddd| _d S )Nr	   )r"   rT   r
   F)r;   r_   rY   rZ   )r   rt   r    r   rU   rR   rn   r   rG   r   rJ   r>   )r   r?   r_   rU   r&   r'   r   r   r    [  s    zToRGB.__init__Nc                 C   s:   |  ||}|| j }|dur6| jr.| |}|| }|S )a  Forward function.

        Args:
            x (Tensor): Feature tensor with shape (b, c, h, w).
            style (Tensor): Tensor with shape (b, num_style_feat).
            skip (Tensor): Base/skip tensor. Default: None.

        Returns:
            Tensor: RGB images.
        N)rn   r>   rU   )r   r   rg   skipr-   r   r   r   r   e  s    

zToRGB.forward)TrS   )Nrs   r   r   r'   r   rt   P  s   

rt   c                       s(   e Zd ZdZ fddZdd Z  ZS )ConstantInputzConstant input.

    Args:
        num_channel (int): Channel number of constant input.
        size (int): Spatial size of constant input.
    c                    s*   t t|   ttd|||| _d S rp   )r   rv   r    r   rG   r   rH   rI   )r   Znum_channelsizer'   r   r   r      s    zConstantInput.__init__c                 C   s   | j |ddd}|S rp   )rI   repeat)r   batchr-   r   r   r   r     s    zConstantInput.forwardrs   r   r   r'   r   rv   y  s   rv   c                       sD   e Zd ZdZd fdd		Zd
d Zdd Zdd ZdddZ  Z	S )StyleGAN2Generatora  StyleGAN2 Generator.

    Args:
        out_size (int): The spatial size of outputs.
        num_style_feat (int): Channel number of style features. Default: 512.
        num_mlp (int): Layer number of MLP style layers. Default: 8.
        channel_multiplier (int): Channel multiplier for large networks of
            StyleGAN2. Default: 2.
        resample_kernel (list[int]): A list indicating the 1D resample kernel
            magnitude. A cross production will be applied to extent 1D resample
            kernel to 2D resample kernel. Default: (1, 3, 3, 1).
        lr_mlp (float): Learning rate multiplier for mlp layers. Default: 0.01.
        narrow (float): Narrow ratio for channels. Default: 1.0.
          r	   rS   {Gz?r
   c                    s8  t t|   || _t g}t|D ]}	|t||dd|dd q$tj	| | _
td| td| td| td| td| | td| | td| | td	| | td
| | d	}
|
| _t|
d dd| _t|
d |
d d|dd |d| _t|
d |d|d| _tt|d| _| jd d d | _| jd d | _t | _t | _t | _|
d }t| jD ]<}d|d d  }dd||g}| jd| tj|  qxtd| jd D ]l}	|
d|	   }| jt||d|dd|d | jt||d|dd |d | jt||d|d |}qd S )NTr   r=   rX   r{         @          	48Z16Z32Z64Z128Z256Z512Z1024r   ra   )rw   rT   )r;   r_   rY   rZ   r&   F)rU   r&   r	   r
      rq   rU   ) r   rz   r    r_   r   rangeappendr<   r   
Sequential	style_mlpintchannelsrv   constant_inputrm   style_conv1rt   to_rgb1rD   loglog_size
num_layers
num_latentZ
ModuleListstyle_convsto_rgbsModulenoisesZregister_bufferr   rH   )r   out_sizer_   Znum_mlpchannel_multiplierr&   Zlr_mlpnarrowZstyle_mlp_layersir   r?   Z	layer_idx
resolutionr#   r@   r'   r   r   r      s    








	zStyleGAN2Generator.__init__c                 C   sj   | j jj}tjdddd|dg}td| jd D ]4}tdD ]&}|tjddd| d| |d q<q0|S )zMake noise for noise injection.r
   ra   devicerT   r	   )r   rI   r   r   rH   r   r   r   )r   r   r   r   rr   r   r   r   
make_noise  s    
&zStyleGAN2Generator.make_noisec                 C   s
   |  |S Nr   r   r   r   r   
get_latent  s    zStyleGAN2Generator.get_latentc                 C   s0   t j|| j| jjjd}| |jddd}|S )Nr   r   T)r   )r   rH   r_   r   rI   r   r   r   )r   r   Z	latent_inlatentr   r   r   mean_latent  s    zStyleGAN2Generator.mean_latentFNTc	                    s@  |s fdd|D }|du rH|r0dg j  }n fddt j D }|dk rxg }	|D ]}
|	|||
|    qX|	}t|dkr j}|d jdk r|d dd|d}n|d }nnt|dkr*|du rt	d jd }|d dd|d}|d dd j| d}t
||gd} |jd } j||dddf |d d	} ||dddf }d}t jddd  jddd |ddd |ddd  jD ]l\}}}}}|||dd|f |d	}|||dd|d f |d	}|||dd|d f |}|d7 }q|}|r4||fS |dfS dS )
a  Forward function for StyleGAN2Generator.

        Args:
            styles (list[Tensor]): Sample codes of styles.
            input_is_latent (bool): Whether input is latent style.
                Default: False.
            noise (Tensor | None): Input noise or None. Default: None.
            randomize_noise (bool): Randomize noise, used when 'noise' is
                False. Default: True.
            truncation (float): TODO. Default: 1.
            truncation_latent (Tensor | None): TODO. Default: None.
            inject_index (int | None): The injection index for mixing noise.
                Default: None.
            return_latents (bool): Whether to return style latents.
                Default: False.
        c                    s   g | ]}  |qS r   r   ).0sr1   r   r   
<listcomp>      z.StyleGAN2Generator.forward.<locals>.<listcomp>Nc                    s   g | ]}t  jd | qS rq   )getattrr   )r   r   r1   r   r   r   !  r   r
   r   rT   r	   r   )r   r   r   lenr   r   Z	unsqueezerx   randomrandintr   catr   r#   r   r   zipr   r   )r   ZstylesZinput_is_latentrq   Zrandomize_noiseZ
truncationZtruncation_latentZinject_indexZreturn_latentsZstyle_truncationrg   r   Zlatent1Zlatent2r-   ru   r   conv1conv2Znoise1Znoise2Zto_rgbimager   r1   r   r      sJ    
 *zStyleGAN2Generator.forward)r{   r|   r	   rS   r}   r
   )FNTr
   NNF)
r   r   r   r4   r    r   r   r   r   r5   r   r   r'   r   rz     s&         R       rz   c                       s*   e Zd ZdZd fdd	Zdd Z  ZS )ScaledLeakyReLUz_Scaled LeakyReLU.

    Args:
        negative_slope (float): Negative slope. Default: 0.2.
    皙?c                    s   t t|   || _d S r   )r   r   r    negative_slope)r   r   r'   r   r   r    T  s    zScaledLeakyReLU.__init__c                 C   s   t j|| jd}|td S )N)r   r	   )rN   Z
leaky_relur   rD   rE   r,   r   r   r   r   X  s    zScaledLeakyReLU.forward)r   rs   r   r   r'   r   r   M  s   r   c                       s2   e Zd ZdZd fdd	Zdd Zd	d
 Z  ZS )EqualConv2da  Equalized Linear as StyleGAN2.

    Args:
        in_channels (int): Channel number of the input.
        out_channels (int): Channel number of the output.
        kernel_size (int): Size of the convolving kernel.
        stride (int): Stride of the convolution. Default: 1
        padding (int): Zero-padding added to both sides of the input.
            Default: 0.
        bias (bool): If ``True``, adds a learnable bias to the output.
            Default: ``True``.
        bias_init_val (float): Bias initialized value. Default: 0.
    r
   r   Tc                    s   t t|   || _|| _|| _|| _|| _dt	||d   | _
tt||||| _|rztt||| _n| dd  d S )Nr
   r	   r>   )r   r   r    r?   r@   r;   rb   r^   rD   rE   rF   r   rG   r   rH   rI   rJ   rK   r>   rL   )r   r?   r@   r;   rb   r^   r>   rM   r'   r   r   r    l  s    zEqualConv2d.__init__c                 C   s&   t j|| j| j | j| j| jd}|S )N)r>   rb   r^   )rN   rf   rI   rF   r>   rb   r^   r,   r   r   r   r   {  s    
zEqualConv2d.forwardc                 C   sB   | j j d| j d| j d| j d| j d| j d| jd u dS )NrO   rP   rl   z	, stride=z
, padding=rQ   r/   )r(   r   r?   r@   r;   rb   r^   r>   r1   r   r   r   r2     s    zEqualConv2d.__repr__)r
   r   Tr   r3   r   r   r'   r   r   ]  s   r   c                       s"   e Zd ZdZd fdd	Z  ZS )	ConvLayera  Conv Layer used in StyleGAN2 Discriminator.

    Args:
        in_channels (int): Channel number of the input.
        out_channels (int): Channel number of the output.
        kernel_size (int): Kernel size.
        downsample (bool): Whether downsample by a factor of 2.
            Default: False.
        resample_kernel (list[int]): A list indicating the 1D resample
            kernel magnitude. A cross production will be applied to
            extent 1D resample kernel to 2D resample kernel.
            Default: (1, 3, 3, 1).
        bias (bool): Whether with bias. Default: True.
        activate (bool): Whether use activateion. Default: True.
    FrS   Tc           
   
      s   g }|r*| t|dd|d d}	d| _nd}	|d | _| t||||	| j|oR| d |r|rr| t| n| td tt| j|  d S )Nr
   r	   rV   r   )rb   r^   r>   r   )	r   r7   r^   r   r   r   r   r   r    )
r   r?   r@   r;   rW   r&   r>   ro   Zlayersrb   r'   r   r   r      s(    
zConvLayer.__init__)FrS   TT)r   r   r   r4   r    r5   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 )ResBlocka  Residual block used in StyleGAN2 Discriminator.

    Args:
        in_channels (int): Channel number of the input.
        out_channels (int): Channel number of the output.
        resample_kernel (list[int]): A list indicating the 1D resample
            kernel magnitude. A cross production will be applied to
            extent 1D resample kernel to 2D resample kernel.
            Default: (1, 3, 3, 1).
    rS   c              	      sV   t t|   t||dddd| _t||dd|ddd| _t||dd|ddd| _d S )NrT   Tr>   ro   )rW   r&   r>   ro   r
   F)r   r   r    r   r   r   ru   )r   r?   r@   r&   r'   r   r   r      s    zResBlock.__init__c                 C   s4   |  |}| |}| |}|| td }|S )Nr	   )r   r   ru   rD   rE   )r   r   r-   ru   r   r   r   r     s
    


zResBlock.forward)rS   rs   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 )StyleGAN2Discriminatora0  StyleGAN2 Discriminator.

    Args:
        out_size (int): The spatial size of outputs.
        channel_multiplier (int): Channel multiplier for large networks of
            StyleGAN2. Default: 2.
        resample_kernel (list[int]): A list indicating the 1D resample kernel
            magnitude. A cross production will be applied to extent 1D resample
            kernel to 2D resample kernel. Default: (1, 3, 3, 1).
        stddev_group (int): For group stddev statistics. Default: 4.
        narrow (float): Narrow ratio for channels. Default: 1.0.
    r	   rS   ra   r
   c                    sj  t t|   td| td| td| td| td| | td| | td| | td| | td| | d	}tt|d}td	||  d
dddg}||  }	t|ddD ],}
|d|
d
    }|t	|	|| |}	qt
j| | _t|	d
 |d d	ddd| _t
t|d d d |d ddd
ddt|d d
ddd
d d| _|| _d
| _d S )Nr{   r~   r   r   r   r   r   r	   rT   r
   Tr   r   ra   r   r=   rX   )r   r   r    r   rD   r   r   r   r   r   r   r   	conv_body
final_convr<   final_linearstddev_groupstddev_feat)r   r   r   r&   r   r   r   r   r   r?   r   r@   r'   r   r   r      s8    




zStyleGAN2Discriminator.__init__c           	      C   s   |  |}|j\}}}}t|| j}||d| j|| j ||}t|jdddd }|j	g ddd
d	}||d
||}t||gd
}| |}||d}| |}|S )Nr   r   F)Zunbiasedr   r`   T)Zkeepdimsr	   r
   )r   r#   minr   rd   r   r   rE   varr   Zsqueezerx   r   r   r   )	r   r   r-   rh   ri   rj   rk   groupZstddevr   r   r   r     s    


zStyleGAN2Discriminator.forward)r	   rS   ra   r
   rs   r   r   r'   r   r     s   #r   )!rD   r   r   r   Ztorch.nnr   rN   Zbasicsr.ops.fused_actr   r   Zbasicsr.ops.upfirdn2dr   Zbasicsr.utils.registryr   r   r   r   r   r6   r7   r<   rR   rm   rt   rv   registerrz   r   r   r   r   r   r   r   r   r   r   <module>   s4   %0j0) C12