a
    dG                     @   s   d dl Z d dlZd dlZd dlmZmZmZmZmZm	Z	 d dl
mZ d dlmZ d dlmZ d dlmZ G dd de	ZG d	d
 d
ejZG dd dejZe G dd dejZe G dd dejZdS )    N)	ConvLayerEqualConv2dEqualLinearResBlockScaledLeakyReLUStyleGAN2Generator)FusedLeakyReLU)ARCH_REGISTRY)nn)
functionalc                       s,   e Zd ZdZd fd	d
	ZdddZ  ZS )StyleGAN2GeneratorSFTaA  StyleGAN2 Generator with SFT modulation (Spatial Feature Transform).

    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): The narrow ratio for channels. Default: 1.
        sft_half (bool): Whether to apply SFT on half of the input channels. Default: False.
                   r   r   {Gz?r   Fc	           	   	      s(   t t| j|||||||d || _d S )N)num_style_featnum_mlpchannel_multiplierresample_kernellr_mlpnarrow)superr   __init__sft_half)	selfout_sizer   r   r   r   r   r   r   	__class__ c/var/www/html/stable-diffusion-webui/venv/lib/python3.9/site-packages/gfpgan/archs/gfpganv1_arch.pyr      s    	
zStyleGAN2GeneratorSFT.__init__NTc
                    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 ]\}}}}}|||dd|f |d	}|t|k rX jr@t
j|t|dd dd
\}}|||d   ||  }t
j||gdd
}n|||d   ||  }|||dd|d f |d	}|||dd|d f |}|d7 }q|}|	r||fS |dfS dS )a  Forward function for StyleGAN2GeneratorSFT.

        Args:
            styles (list[Tensor]): Sample codes of styles.
            conditions (list[Tensor]): SFT conditions to generators.
            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): The truncation ratio. Default: 1.
            truncation_latent (Tensor | None): The truncation latent tensor. 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!   )Z	style_mlp).0sr   r!   r"   
<listcomp>G       z1StyleGAN2GeneratorSFT.forward.<locals>.<listcomp>Nc                    s   g | ]}t  jd | qS noise)getattrZnoises)r#   ir%   r!   r"   r&   M   r'   r   r   r   r   r(   )Zdim)Z
num_layersrangeappendlenZ
num_latentndimZ	unsqueezerepeatrandomrandinttorchcatZconstant_inputshapeZstyle_conv1Zto_rgb1zipZstyle_convsZto_rgbsr   splitintsize)r   Zstyles
conditionsinput_is_latentr)   randomize_noiseZ
truncationZtruncation_latentZinject_indexreturn_latentsZstyle_truncationstyleZlatentZlatent1Zlatent2outskipr+   conv1conv2Znoise1Znoise2Zto_rgbZout_sameZout_sftimager!   r%   r"   forward.   sV    
 *"zStyleGAN2GeneratorSFT.forward)r   r   r   r   r   r   F)FNTr   NNF__name__
__module____qualname____doc__r   rD   __classcell__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 )
ConvUpLayeraj  Convolutional upsampling layer. It uses bilinear upsampler + 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.
        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.
        activate (bool): Whether use activateion. Default: True.
    r   r   Tc	           	         s   t t|   || _|| _|| _|| _|| _dt	||d   | _
tt||||| _|r~|s~tt||| _n| dd  |r|rt|| _qtd| _nd | _d S )Nr   r   bias皙?)r   rK   r   in_channelsout_channelskernel_sizestridepaddingmathsqrtscaler
   	Parameterr3   ZrandnweightzerosZfill_rL   Zregister_parameterr   
activationr   )	r   rN   rO   rP   rQ   rR   rL   bias_init_valactivater   r!   r"   r      s     	zConvUpLayer.__init__c                 C   sL   t j|dddd}t j|| j| j | j| j| jd}| jd urH| |}|S )Nr   ZbilinearF)Zscale_factormodeZalign_corners)rL   rQ   rR   )	FZinterpolateZconv2drW   rU   rL   rQ   rR   rY   )r   xr?   r!   r!   r"   rD      s    


zConvUpLayer.forward)r   r   Tr   TrE   r!   r!   r   r"   rK      s        "rK   c                       s(   e Zd ZdZ fddZdd Z  ZS )
ResUpBlockzResidual block with upsampling.

    Args:
        in_channels (int): Channel number of the input.
        out_channels (int): Channel number of the output.
    c              	      sR   t t|   t||dddd| _t||dddddd| _t||dddd| _d S )Nr   TrL   r[   r   )rQ   rR   rL   r[   F)r   r_   r   r   rA   rK   rB   r@   )r   rN   rO   r   r!   r"   r      s    zResUpBlock.__init__c                 C   s4   |  |}| |}| |}|| td }|S )Nr   )rA   rB   r@   rS   rT   )r   r^   r?   r@   r!   r!   r"   rD      s
    


zResUpBlock.forwardrE   r!   r!   r   r"   r_      s   r_   c                       s,   e Zd ZdZd fd
d	ZdddZ  ZS )GFPGANv1a  The GFPGAN architecture: Unet + StyleGAN2 decoder with SFT.

    Ref: GFP-GAN: Towards Real-World Blind Face Restoration with Generative Facial Prior.

    Args:
        out_size (int): The spatial size of outputs.
        num_style_feat (int): Channel number of style features. Default: 512.
        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).
        decoder_load_path (str): The path to the pre-trained decoder model (usually, the StyleGAN2). Default: None.
        fix_decoder (bool): Whether to fix the decoder. Default: True.

        num_mlp (int): Layer number of MLP style layers. Default: 8.
        lr_mlp (float): Learning rate multiplier for mlp layers. Default: 0.01.
        input_is_latent (bool): Whether input is latent style. Default: False.
        different_w (bool): Whether to use different latent w for different layers. Default: False.
        narrow (float): The narrow ratio for channels. Default: 1.
        sft_half (bool): Whether to apply SFT on half of the input channels. Default: False.
    r   r   r   NTr   r   Fc                    sV  t t|   |	| _|
| _|| _|d }td| td| td| td| td| | td| | td| | td| | td| | d	}tt|d	| _	d	tt|d	 }t
d
||  dddd| _||  }t | _t| j	d	dD ].}|d	|d    }| jt||| |}qt
||d d
ddd| _|d }t | _td
| j	d D ]*}|d	|   }| jt|| |}qht | _td
| j	d D ].}| jt|d	|   d
dddddd q|
rtt|d	d	 d	 | }n|}t|d d d |dddd d| _t||||||||d| _|rf| jtj|dd dd  |r| j D ]\}}d|_qvt | _ t | _!td
| j	d D ]}|d	|   }|r|}n|d	 }| j t"t||d
dddddt#dt||d
ddddd | j!t"t||d
dddddt#dt||d
ddddd qd S )Ng      ?r         @          )	48Z16Z32Z64Z128Z256Z512Z1024r   r   r   Tr`   rg   r   )rQ   rR   rL   rZ      )rL   rZ   Zlr_mulrY   )r   r   r   r   r   r   r   r   c                 S   s   | S )Nr!   )Zstoragelocr!   r!   r"   <lambda>G  r'   z#GFPGANv1.__init__.<locals>.<lambda>)Zmap_locationZ
params_emaFrM   )$r   ra   r   r;   different_wr   r8   rS   loglog_sizer   conv_body_firstr
   Z
ModuleListconv_body_downr,   r-   r   
final_convconv_body_upr_   toRGBr   r   final_linearr   stylegan_decoderZload_state_dictr3   loadZnamed_parametersZrequires_gradcondition_scalecondition_shiftZ
Sequentialr   )r   r   r   r   r   Zdecoder_load_pathZfix_decoderr   r   r;   rm   r   r   Zunet_narrowZchannelsZfirst_out_sizerN   r+   rO   Zlinear_out_channel_paramZsft_out_channelsr   r!   r"   r      s    







,


zGFPGANv1.__init__c                 K   s$  g }g }g }|  |}	t| jd D ]}
| j|
 |	}	|d|	 q$| |	}	| |	|	dd}| j	r||dd| j
}t| jd D ]n}
|	||
  }	| j|
 |	}	| j|
 |	}||  | j|
 |	}||  |r|| j|
 |	 q| j|g||| j|d\}}||fS )af  Forward function for GFPGANv1.

        Args:
            x (Tensor): Input images.
            return_latents (bool): Whether to return style latents. Default: False.
            return_rgb (bool): Whether return intermediate rgb images. Default: True.
            randomize_noise (bool): Randomize noise, used when 'noise' is False. Default: True.
        r   r   ri   )r=   r;   r<   )rp   r,   ro   rq   insertrr   ru   viewr9   rm   r   rs   rx   r-   clonery   rt   rv   r;   )r   r^   r=   Z
return_rgbr<   kwargsr:   Z
unet_skipsZout_rgbsfeatr+   Z
style_coderU   shiftrC   rz   r!   r!   r"   rD   a  s6    	


zGFPGANv1.forward)r   r   r   NTr   r   FFr   F)FTTrE   r!   r!   r   r"   ra      s              nra   c                       s*   e Zd ZdZ fddZdddZ  ZS )FacialComponentDiscriminatorzHFacial component (eyes, mouth, noise) discriminator used in GFPGAN.
    c              	      s   t t|   tdddddddd| _tdddddddd| _tdddddddd| _tdddddddd| _tdddddddd| _tdd	dddd
| _	d S )Nr   rd   Fr   T)Z
downsampler   rL   r[   rc   rb   r   r`   )
r   r   r   r   rA   rB   conv3conv4conv5rr   r%   r   r!   r"   r     s    z%FacialComponentDiscriminator.__init__Fc                 K   st   |  |}| | |}g }|r0||  | | |}|rR||  | |}|rh||fS |dfS dS )zForward function for FacialComponentDiscriminator.

        Args:
            x (Tensor): Input images.
            return_feats (bool): Whether to return intermediate features. Default: False.
        N)rA   r   rB   r-   r~   r   r   rr   )r   r^   Zreturn_featsr   r   Z	rlt_featsr?   r!   r!   r"   rD     s    

z$FacialComponentDiscriminator.forward)FrE   r!   r!   r   r"   r     s   
r   )rS   r1   r3   Zbasicsr.archs.stylegan2_archr   r   r   r   r   r   Zbasicsr.ops.fused_actr   Zbasicsr.utils.registryr	   r
   Ztorch.nnr   r]   r   ModulerK   r_   registerra   r   r!   r!   r!   r"   <module>   s    xA 8