
    bil                         d dl mZmZmZ d dlZd dlmZ ddlmZm	Z	 ddl
mZ ddlmZ ddlmZ d	d
lmZmZmZmZ  G d dee      Zy)    )OptionalTupleUnionN   )ConfigMixinregister_to_config)apply_forward_hook   )AutoencoderKLOutput)
ModelMixin   )DecoderOutputDiagonalGaussianDistributionEncoderMaskConditionDecoderc                       e Zd ZdZdgZe	 	 	 	 	 	 	 	 	 	 	 	 	 d dededeedf   deedf   ded	eedf   d
eedf   dededededede	ddf fd       Z
ed!dej                  dedeeeej                     f   fd       Z	 	 	 d"dej                  deej                     deej                     dedeeeej                     f   f
dZe	 	 	 	 d#dej                  deej*                     deej                     deej                     dedeeeej                     f   fd       Z	 	 	 	 d$dej                  deej                     dededeej*                     deeeej                     f   fdZ xZS )%AsymmetricAutoencoderKLa	  
    Designing a Better Asymmetric VQGAN for StableDiffusion https://huggingface.co/papers/2306.04632 . A VAE model with
    KL loss for encoding images into latents and decoding latent representations into images.

    This model inherits from [`ModelMixin`]. Check the superclass documentation for it's generic methods implemented
    for all models (such as downloading or saving).

    Parameters:
        in_channels (int, *optional*, defaults to 3): Number of channels in the input image.
        out_channels (int,  *optional*, defaults to 3): Number of channels in the output.
        down_block_types (`Tuple[str]`, *optional*, defaults to `("DownEncoderBlock2D",)`):
            Tuple of downsample block types.
        down_block_out_channels (`Tuple[int]`, *optional*, defaults to `(64,)`):
            Tuple of down block output channels.
        layers_per_down_block (`int`, *optional*, defaults to `1`):
            Number layers for down block.
        up_block_types (`Tuple[str]`, *optional*, defaults to `("UpDecoderBlock2D",)`):
            Tuple of upsample block types.
        up_block_out_channels (`Tuple[int]`, *optional*, defaults to `(64,)`):
            Tuple of up block output channels.
        layers_per_up_block (`int`, *optional*, defaults to `1`):
            Number layers for up block.
        act_fn (`str`, *optional*, defaults to `"silu"`): The activation function to use.
        latent_channels (`int`, *optional*, defaults to 4): Number of channels in the latent space.
        sample_size (`int`, *optional*, defaults to `32`): Sample input size.
        norm_num_groups (`int`, *optional*, defaults to `32`):
            Number of groups to use for the first normalization layer in ResNet blocks.
        scaling_factor (`float`, *optional*, defaults to 0.18215):
            The component-wise standard deviation of the trained latent space computed using the first batch of the
            training set. This is used to scale the latent space to have unit variance when training the diffusion
            model. The latents are scaled with the formula `z = z * scaling_factor` before being passed to the
            diffusion model. When decoding, the latents are scaled back to the original scale with the formula: `z = 1
            / scaling_factor * z`. For more details, refer to sections 4.3.2 and D.1 of the [High-Resolution Image
            Synthesis with Latent Diffusion Models](https://huggingface.co/papers/2112.10752) paper.
    decoderin_channelsout_channelsdown_block_types.down_block_out_channelslayers_per_down_blockup_block_typesup_block_out_channelslayers_per_up_blockact_fnlatent_channelsnorm_num_groupssample_sizescaling_factorreturnNc           
      `   t         |           t        ||
||||	|d      | _        t	        |
|||||	|      | _        t        j                  d|
z  d|
z  d      | _        t        j                  |
|
d      | _	        d| _
        d| _        | j                  |       | j                  d       y )	NT)r   r   r   block_out_channelslayers_per_blockr   r   double_z)r   r   r   r$   r%   r   r   r
   r   F)r$   )force_upcast)super__init__r   encoderr   r   nnConv2d
quant_convpost_quant_convuse_slicing
use_tilingr   )selfr   r   r   r   r   r   r   r   r   r   r   r    r!   	__class__s                 l/home/cdr/jupyterlab/.venv/lib/python3.12/site-packages/diffusers/models/autoencoders/autoencoder_asym_kl.pyr)   z AsymmetricAutoencoderKL.__init__A   s    " 	 #(-62+	
 ,'%)40+
 ))A$7_9LaP!yy/1M 3HIU3    xreturn_dictc                 ~    | j                  |      }| j                  |      }t        |      }|s|fS t        |      S )N)latent_dist)r*   r-   r   r   )r1   r5   r6   hmoments	posteriors         r3   encodezAsymmetricAutoencoderKL.encodet   s=    LLO//!$09	<"y99r4   zimagemaskc                 l    | j                  |      }| j                  |||      }|s|fS t        |      S Nsample)r.   r   r   )r1   r=   r>   r?   r6   decs         r3   _decodezAsymmetricAutoencoderKL._decode   s;       #ll1eT*6MC((r4   	generatorc                 ^    | j                  |||      j                  }|s|fS t        |      S rA   )rE   rC   r   )r1   r=   rF   r>   r?   r6   decodeds          r3   decodezAsymmetricAutoencoderKL.decode   s2     ,,q%.55:G,,r4   rC   sample_posteriorc                     |}| j                  |      j                  }|r|j                  |      }n|j                         }| j	                  ||||      j                  }	|s|	fS t        |	      S )a  
        Args:
            sample (`torch.Tensor`): Input sample.
            mask (`torch.Tensor`, *optional*, defaults to `None`): Optional inpainting mask.
            sample_posterior (`bool`, *optional*, defaults to `False`):
                Whether to sample from the posterior.
            return_dict (`bool`, *optional*, defaults to `True`):
                Whether or not to return a [`DecoderOutput`] instead of a plain tuple.
        )rF   rB   )r<   r8   rC   moderI   r   )
r1   rC   r?   rJ   r6   rF   r5   r;   r=   rD   s
             r3   forwardzAsymmetricAutoencoderKL.forward   sm    " KKN..	  9 5A Akk!Y5<<6MC((r4   )r   r   )DownEncoderBlock2D@   r   )UpDecoderBlock2DrO   r   silu       rT   g{P?)T)NNT)NNNT)NFTN)__name__
__module____qualname____doc__ _skip_layerwise_casting_patternsr   intr   strfloatr)   r	   torchTensorboolr   r   r<   r   r   rE   	GeneratorrI   rM   __classcell__)r2   s   @r3   r   r      s   "H )2{$ ,C38%&*?16#$ ! '0404 04  S/	04
 "'sCx04  #04 c3h04  %S#X04 !04 04 04 04 04 04 
04 04d : :4 :5I\^cdidpdp^qIqCr : : )-'+ )<<) %) u||$	)
 ) 
}eELL11	2)  04(,'+ -<<- EOO,- %	-
 u||$- - 
}eELL11	2- -$ (,!& /3)) u||$) 	)
 ) EOO,) 
}eELL11	2)r4   r   )typingr   r   r   r]   torch.nnr+   configuration_utilsr   r   utils.accelerate_utilsr	   modeling_outputsr   modeling_utilsr   vaer   r   r   r   r    r4   r3   <module>rj      s5    * )   B 8 2 ' [ [`)j+ `)r4   