a
    d%W                     @   s  d dl Z d dlZd dlZd dlmZmZ d dlmZ d dlmZ d dl	m
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dS )    N)FusedLeakyReLUfused_leaky_relu)ARCH_REGISTRY)nn)
functionalc                   @   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   m/var/www/html/stable-diffusion-webui/venv/lib/python3.9/site-packages/gfpgan/archs/stylegan2_bilinear_arch.pyforward   s    	zNormStyleCode.forwardN)__name__
__module____qualname__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 )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)superr   __init__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_valr   r    	__class__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   r   r    FZlinearr'   r$   r   )r   r   r   outr   r   r   r   7   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   r   r   r   __repr__C   s
    zEqualLinear.__repr__)Tr   r	   Nr   r   r   __doc__r   r   r5   __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 )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.
        eps (float): A value added to the denominator for numerical stability.
            Default: 1e-8.
    TNr   bilinearc	           	   	      s   t t|   || _|| _|| _|| _|| _|| _|| _	| j	dkrJd | _
nd| _
dt||d   | _t||dddd d| _ttd||||| _|d | _d S )NnearestFr	   r   Tr   r+   r   r    )r   r9   r   r   r   kernel_size
demodulatesample_modeepsinterpolation_modealign_cornersr"   r#   r$   r   
modulationr   r%   r   r&   r'   padding)	r   r   r   r=   num_style_featr>   r?   r@   rA   r,   r   r   r   Z   s"    	
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rtj|d| j| jd}n | jdkrtj|d| j| jd}|j \}}}}|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         upsampleZscale_factormoderB   
downsample      ?)rD   groupsrG   )shaperC   viewr$   r'   r>   r   r   powsumr@   r   r=   r?   r.   interpolaterA   rB   conv2drD   )
r   r   stylebchwr'   Zdemodr/   r   r   r   r   x   s     
 

 zModulatedConv2d.forwardc                 C   s6   | j j d| j d| j d| j d| j d| j dS )Nr0   r1   , kernel_size=z, demodulate=z, sample_mode=r3   )r-   r   r   r   r=   r>   r?   r4   r   r   r   r5      s    zModulatedConv2d.__repr__)TNr   r:   r6   r   r   r,   r   r9   H   s       #r9   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.
    TNr:   c              	      sF   t t|   t|||||||d| _ttd| _	t
|| _d S )N)r>   r?   rA   r	   )r   rZ   r   r9   modulated_convr   r%   r   r(   r'   r   activate)r   r   r   r=   rE   r>   r?   rA   r,   r   r   r      s    zStyleConv.__init__c           	      C   sR   |  ||}|d u r6|j\}}}}||d|| }|| j|  }| |}|S Nr	   )r[   rN   Z	new_emptyZnormal_r'   r\   )	r   r   rT   noiser/   rU   _rW   rX   r   r   r   r      s    
zStyleConv.forward)TNr:   )Nr   r   r   r7   r   r   r8   r   r   r,   r   rZ      s      rZ   c                       s,   e Zd ZdZd	 fdd	Zd
ddZ  ZS )ToRGBzTo 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.
    Tr:   c              	      sf   t t|   || _|| _| jdkr,d | _nd| _t|dd|dd |d| _t	t
dddd| _d S )Nr;   FrF   r	   r=   rE   r>   r?   rA   )r   ra   r   rH   rA   rB   r9   r[   r   r%   r   r(   r   )r   r   rE   rH   rA   r,   r   r   r      s     
zToRGB.__init__Nc                 C   sF   |  ||}|| j }|durB| jr:tj|d| j| jd}|| }|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.
        Nr   rI   )r[   r   rH   r.   rR   rA   rB   )r   r   rT   skipr/   r   r   r   r      s    
zToRGB.forward)Tr:   )Nr`   r   r   r,   r   ra      s   ra   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 r]   )r   rd   r   r   r%   r   r&   r'   )r   Znum_channelsizer,   r   r   r     s    zConstantInput.__init__c                 C   s   | j |ddd}|S r]   )r'   repeat)r   batchr/   r   r   r   r     s    zConstantInput.forwardr`   r   r   r,   r   rd      s   rd   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 )StyleGAN2GeneratorBilineara  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.
        lr_mlp (float): Learning rate multiplier for mlp layers. Default: 0.01.
        narrow (float): Narrow ratio for channels. Default: 1.0.
          r   {Gz?r	   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   r<   ri         @          )	48Z16Z32Z64Z128Z256Z512Z1024rq   rG   )re   rF   rb   F)rH   rA   r   r	      r^   rH   ) r   rh   r   rE   r   rangeappendr   r   
Sequential	style_mlpintchannelsrd   constant_inputrZ   style_conv1ra   to_rgb1r"   loglog_size
num_layers
num_latentZ
ModuleListstyle_convsto_rgbsModulenoisesZregister_bufferr   r&   )r   Zout_sizerE   Znum_mlpZchannel_multiplierZlr_mlpZnarrowrA   Zstyle_mlp_layersiry   r   Z	layer_idx
resolutionrN   r   r,   r   r   r     s    







		z#StyleGAN2GeneratorBilinear.__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	   rG   devicerF   r   )rz   r'   r   r   r&   rt   r~   ru   )r   r   r   r   r_   r   r   r   
make_noiseq  s    
&z%StyleGAN2GeneratorBilinear.make_noisec                 C   s
   |  |S Nrw   r   r   r   r   
get_latent|  s    z%StyleGAN2GeneratorBilinear.get_latentc                 C   s0   t j|| j| jjjd}| |jddd}|S )Nr   r   T)r
   )r   r&   rE   rz   r'   r   rw   r   )r   r   Z	latent_inlatentr   r   r   mean_latent  s    z&StyleGAN2GeneratorBilinear.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sr4   r   r   
<listcomp>      z6StyleGAN2GeneratorBilinear.forward.<locals>.<listcomp>Nc                    s   g | ]}t  jd | qS r^   )getattrr   )r   r   r4   r   r   r     r   r	   r   rF   r   r   )r   rt   ru   lenr   ndimZ	unsqueezerf   randomrandintr   catrz   rN   r{   r|   zipr   r   )r   ZstylesZinput_is_latentr^   Zrandomize_noiseZ
truncationZtruncation_latentZinject_indexZreturn_latentsZstyle_truncationrT   r   Zlatent1Zlatent2r/   rc   r   conv1conv2Znoise1Znoise2Zto_rgbimager   r4   r   r     sJ    
 *z"StyleGAN2GeneratorBilinear.forward)ri   rj   r   rk   r	   r:   )FNTr	   NNF)
r   r   r   r7   r   r   r   r   r   r8   r   r   r,   r   rh     s&         R       rh   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     s    zScaledLeakyReLU.__init__c                 C   s   t j|| jd}|td S )N)r   r   )r.   Z
leaky_relur   r"   r#   r   r   r/   r   r   r   r     s    zScaledLeakyReLU.forward)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 )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=   striderD   r"   r#   r$   r   r%   r   r&   r'   r(   r)   r   r*   )r   r   r   r=   r   rD   r   r+   r,   r   r   r     s    zEqualConv2d.__init__c                 C   s&   t j|| j| j | j| j| jd}|S )N)r   r   rD   )r.   rS   r'   r$   r   r   rD   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 )Nr0   r1   rY   z	, stride=z
, padding=r2   r3   )r-   r   r   r   r=   r   rD   r   r4   r   r   r   r5   
  s    zEqualConv2d.__repr__)r	   r   Tr   r6   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.
        bias (bool): Whether with bias. Default: True.
        activate (bool): Whether use activateion. Default: True.
    FTr:   c           
   
      s   g }|| _ |r@| j dkr d | _nd| _|tjjd|| jd d}	|d | _|t||||	| j|oh| d |r|r|t| n|t	d t
t| j|  d S )	Nr;   FrL   rI   r	   r   )r   rD   r   r   )rA   rB   ru   r   r   ZUpsamplerD   r   r   r   r   r   r   )
r   r   r   r=   rK   r   r\   rA   Zlayersr   r,   r   r   r     s,    

zConvLayer.__init__)FTTr:   )r   r   r   r7   r   r8   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 )ResBlockzResidual block used in StyleGAN2 Discriminator.

    Args:
        in_channels (int): Channel number of the input.
        out_channels (int): Channel number of the output.
    r:   c              	      sV   t t|   t||dddd| _t||dd|ddd| _t||dd|ddd| _d S )NrF   T)r   r\   )rK   rA   r   r\   r	   F)r   r   r   r   r   r   rc   )r   r   r   rA   r,   r   r   r   K  s(    zResBlock.__init__c                 C   s4   |  |}| |}| |}|| td }|S )Nr   )r   r   rc   r"   r#   )r   r   r/   rc   r   r   r   r   `  s
    


zResBlock.forward)r:   r`   r   r   r,   r   r   C  s   r   )r"   r   r   Zbasicsr.ops.fused_actr   r   Zbasicsr.utils.registryr   r   Ztorch.nnr   r.   r   r   r   r9   rZ   ra   rd   registerrh   r   r   rv   r   r   r   r   r   r   <module>   s&   0Z.0 @11