
    bi                         d dl mZ 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mZmZmZ dd
lmZ e G d de             Z G d dee
      Zy)    )	dataclass)OptionalTupleUnionN   )ConfigMixinregister_to_config)
BaseOutput)apply_forward_hook   )DecoderDecoderOutputEncoderVectorQuantizer)
ModelMixinc                   0    e Zd ZU dZej
                  ed<   y)VQEncoderOutputz
    Output of VQModel encoding method.

    Args:
        latents (`torch.Tensor` of shape `(batch_size, num_channels, height, width)`):
            The encoded output sample from the last layer of the model.
    latentsN)__name__
__module____qualname____doc__torchTensor__annotations__     a/home/cdr/jupyterlab/.venv/lib/python3.12/site-packages/diffusers/models/autoencoders/vq_model.pyr   r      s     \\r   r   c                       e Zd ZdZdgZdZe	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 ddededee	df   dee	df   d	eedf   d
ede	dedededede
e   dede	f fd       Zeddej                  dedefd       Ze	 ddej                  dededeeej                  f   fd       Z	 ddej                  dedeeeej                  df   f   fdZ xZS ) VQModelaJ	  
    A VQ-VAE model for decoding latent representations.

    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.
        up_block_types (`Tuple[str]`, *optional*, defaults to `("UpDecoderBlock2D",)`):
            Tuple of upsample block types.
        block_out_channels (`Tuple[int]`, *optional*, defaults to `(64,)`):
            Tuple of block output channels.
        layers_per_block (`int`, *optional*, defaults to `1`): Number of layers per block.
        act_fn (`str`, *optional*, defaults to `"silu"`): The activation function to use.
        latent_channels (`int`, *optional*, defaults to `3`): Number of channels in the latent space.
        sample_size (`int`, *optional*, defaults to `32`): Sample input size.
        num_vq_embeddings (`int`, *optional*, defaults to `256`): Number of codebook vectors in the VQ-VAE.
        norm_num_groups (`int`, *optional*, defaults to `32`): Number of groups for normalization layers.
        vq_embed_dim (`int`, *optional*): Hidden dim of codebook vectors in the VQ-VAE.
        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.
        norm_type (`str`, *optional*, defaults to `"group"`):
            Type of normalization layer to use. Can be one of `"group"` or `"spatial"`.
    quantizeFin_channelsout_channelsdown_block_types.up_block_typesblock_out_channelslayers_per_blockact_fnlatent_channelssample_sizenum_vq_embeddingsnorm_num_groupsvq_embed_dimscaling_factor	norm_typec                 ,   t         |           t        |||||||d|	      | _        ||n|}t	        j
                  ||d      | _        t        |
|dd d      | _        t	        j
                  ||d      | _	        t        |||||||||	      | _        y )NF)	r"   r#   r$   r&   r'   r(   r,   double_zmid_block_add_attention   g      ?)betaremapsane_index_shape)	r"   r#   r%   r&   r'   r(   r,   r/   r2   )super__init__r   encodernnConv2d
quant_convr   r!   post_quant_convr   decoder)selfr"   r#   r$   r%   r&   r'   r(   r)   r*   r+   r,   r-   r.   r/   r2   lookup_from_codebookforce_upcast	__class__s                     r   r8   zVQModel.__init__M   s    * 	 #(-1-+$;

 (4'?|_))O\1E'(9<dZ^qvw!yyJ '%)1-+$;

r   xreturn_dictreturnc                 h    | j                  |      }| j                  |      }|s|fS t        |      S )N)r   )r9   r<   r   )r?   rC   rD   hs       r   encodezVQModel.encode   s2    LLOOOA4Kq))r   rG   force_not_quantizec                 Z   |s| j                  |      \  }}}n| j                  j                  rd| j                   j                  ||      }t	        j
                  |j                  d         j                  |j                  |j                        }nI|}t	        j
                  |j                  d         j                  |j                  |j                        }| j                  |      }| j                  || j                  j                  dk(  r|nd       }	|s|	|fS t        |	|      S )Nr   )dtypespatial)samplecommit_loss)r!   configr@   get_codebook_entryr   zerosshapetodevicerK   r=   r>   r/   r   )
r?   rG   rI   rD   rR   quantrN   _quant2decs
             r   decodezVQModel.decode   s    
 "$(MM!$4!E;[[--MM44Q>E++qwwqz366qxxqww6OKE++qwwqz366qxxqww6OK%%e,ll6DKK,A,AY,N5TXY##C[AAr   rM   c                     | j                  |      j                  }| j                  |      }|s|j                  |j                  fS |S )a'  
        The [`VQModel`] forward method.

        Args:
            sample (`torch.Tensor`): Input sample.
            return_dict (`bool`, *optional*, defaults to `True`):
                Whether or not to return a [`models.autoencoders.vq_model.VQEncoderOutput`] instead of a plain tuple.

        Returns:
            [`~models.autoencoders.vq_model.VQEncoderOutput`] or `tuple`:
                If return_dict is True, a [`~models.autoencoders.vq_model.VQEncoderOutput`] is returned, otherwise a
                plain `tuple` is returned.
        )rH   r   rY   rM   rN   )r?   rM   rD   rG   rX   s        r   forwardzVQModel.forward   s@    " KK''kk!n::s..
r   )r   r   )DownEncoderBlock2D)UpDecoderBlock2D)@   r3   silur          r`   Ng{P?groupTFF)T)FTN)r   r   r   r    _skip_layerwise_casting_patterns_supports_group_offloadingr	   intr   strr   floatr8   r   r   r   boolr   rH   r   r   rY   r[   __classcell__)rB   s   @r   r    r    (   s   B )3|$!& ,C*?.3 ! !$!&* '  $"%4
4
 4
  S/	4

 c3h4
 "#s(O4
 4
 4
 4
 4
 4
 4
 sm4
 4
 4
 4
l * *4 *? * * aeBB37BNRB	}ell*	+B B* 9=ll15	}eELL#$566	7r   r    )dataclassesr   typingr   r   r   r   torch.nnr:   configuration_utilsr   r	   utilsr
   utils.accelerate_utilsr   autoencoders.vaer   r   r   r   modeling_utilsr   r   r    r   r   r   <module>rr      sS    " ) )   B  8 O O ' 	j 	 	Qj+ Qr   