
    iQ              
           d dl 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 ddlmZ d	d
lm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!m"Z"m#Z#m$Z$m%Z%  G d dee!ee	ee      Z&y)    N)OptionalTupleUnion   )ConfigMixinregister_to_config)PeftAdapterMixin)FromOriginalModelMixin)	deprecate)apply_forward_hook   )AttentionMixin)ADDED_KV_ATTENTION_PROCESSORSCROSS_ATTENTION_PROCESSORS	AttentionAttnAddedKVProcessorAttnProcessorFusedAttnProcessor2_0)AutoencoderKLOutput)
ModelMixin   )AutoencoderMixinDecoderDecoderOutputDiagonalGaussianDistributionEncoderc            &           e Zd ZdZdZddg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
de
de
dededeeef   f" fd       Zd Zdej                  dej                  fdZe	 d0dej                  de
deeee   f   fd       Zd0dej                  de
deeej                  f   fdZe	 d1dej0                  de
deeej0                  f   fd        Zd!ej                  d"ej                  d#edej                  fd$Zd!ej                  d"ej                  d#edej                  fd%Zdej                  dej                  fd&Zd0dej                  de
defd'Zd0dej                  de
deeej                  f   fd(Z	 	 	 d2d)ej                  d*e
de
d+eej@                     deeej                  f   f
d,Z!d- Z"d. Z# xZ$S )3AutoencoderKLFlux2a  
    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.
        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.
        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.
        force_upcast (`bool`, *optional*, default to `True`):
            If enabled it will force the VAE to run in float32 for high image resolution pipelines, such as SD-XL. VAE
            can be fine-tuned / trained to a lower range without losing too much precision in which case `force_upcast`
            can be set to `False` - see: https://huggingface.co/madebyollin/sdxl-vae-fp16-fix
        mid_block_add_attention (`bool`, *optional*, default to `True`):
            If enabled, the mid_block of the Encoder and Decoder will have attention blocks. If set to false, the
            mid_block will only have resnet blocks
    TBasicTransformerBlockResnetBlock2Din_channelsout_channelsdown_block_types.up_block_typesblock_out_channelslayers_per_blockact_fnlatent_channelsnorm_num_groupssample_sizeforce_upcastuse_quant_convuse_post_quant_convmid_block_add_attentionbatch_norm_epsbatch_norm_momentum
patch_sizec                    t         |           t        |||||||	d|	      | _        t	        ||||||	||      | _        |rt        j                  d|z  d|z  d      nd | _        |rt        j                  ||d      nd | _	        t        j                  t        j                  |      |z  ||dd      | _        d| _        d| _        | j                   j"                  | _        t'        | j                   j"                  t(        t*        f      r| j                   j"                  d   n| j                   j"                  }
t-        |
dt/        | j                   j0                        dz
  z  z        | _        d	| _        y )
NT)	r!   r"   r#   r%   r&   r'   r)   double_zr.   )r!   r"   r$   r%   r&   r)   r'   r.   r   r   F)epsmomentumaffinetrack_running_statsr   g      ?)super__init__r   encoderr   decodernnConv2d
quant_convpost_quant_convBatchNorm2dmathprodbnuse_slicing
use_tilingconfigr*   tile_sample_min_size
isinstancelisttupleintlenr%   tile_latent_min_sizetile_overlap_factor)selfr!   r"   r#   r$   r%   r&   r'   r(   r)   r*   r+   r,   r-   r.   r/   r0   r1   	__class__s                     |/home/obispo/Crisostomo_bridge/mision_env/lib/python3.12/site-packages/diffusers/models/autoencoders/autoencoder_kl_flux2.pyr9   zAutoencoderKLFlux2.__init__H   si   H 	 #(-1-+$;

 '%)1-+$;	
 Uc"))A$7_9LaPhlQdryy/1Mjn..IIj!O3( $
 ! %)KK$;$;! $++11D%=A KK##A&(( 	
 %(qSA_A_=`cd=d7e(f$g!#'     c           	      j   t        d | j                  j                         D              rt               }nmt        d | j                  j                         D              rt	               }n8t        dt        t        | j                  j                                            | j                  |       y)ze
        Disables custom attention processors and sets the default attention implementation.
        c              3   @   K   | ]  }|j                   t        v   y wN)rP   r   .0procs     rQ   	<genexpr>z@AutoencoderKLFlux2.set_default_attn_processor.<locals>.<genexpr>   s     i4t~~!>>i   c              3   @   K   | ]  }|j                   t        v   y wrU   )rP   r   rV   s     rQ   rY   z@AutoencoderKLFlux2.set_default_attn_processor.<locals>.<genexpr>   s     h$#==hrZ   zOCannot call `set_default_attn_processor` when attention processors are of type N)	allattn_processorsvaluesr   r   
ValueErrornextiterset_attn_processor)rO   	processors     rQ   set_default_attn_processorz-AutoencoderKLFlux2.set_default_attn_processor   s     i4K_K_KfKfKhii,.Ih$J^J^JeJeJghh%Iabfgklp  mA  mA  mH  mH  mJ  hK  cL  bM  N  		*rR   xreturnc                     |j                   \  }}}}| j                  r/|| j                  kD  s|| j                  kD  r| j                  |      S | j	                  |      }| j
                  | j                  |      }|S rU   )shaperE   rG   _tiled_encoder:   r>   )rO   re   
batch_sizenum_channelsheightwidthencs          rQ   _encodezAutoencoderKLFlux2._encode   sp    23''/
L&%??(A(A AVdNgNgEg%%a((ll1o??&//#&C
rR   return_dictc                 (   | j                   rU|j                  d   dkD  rC|j                  d      D cg c]  }| j                  |       }}t	        j
                  |      }n| j                  |      }t        |      }|s|fS t        |      S c c}w )a  
        Encode a batch of images into latents.

        Args:
            x (`torch.Tensor`): Input batch of images.
            return_dict (`bool`, *optional*, defaults to `True`):
                Whether to return a [`~models.autoencoder_kl.AutoencoderKLOutput`] instead of a plain tuple.

        Returns:
                The latent representations of the encoded images. If `return_dict` is True, a
                [`~models.autoencoder_kl.AutoencoderKLOutput`] is returned, otherwise a plain `tuple` is returned.
        r   r   latent_dist)rD   rh   splitro   torchcatr   r   )rO   re   rp   x_sliceencoded_slicesh	posteriors          rQ   encodezAutoencoderKLFlux2.encode   s      
QCD771:Ndll73NNN		.)AQA03	<"y99 Os   Bzc                 .   | j                   rK|j                  d   | j                  kD  s|j                  d   | j                  kD  r| j                  ||      S | j                  | j	                  |      }| j                  |      }|s|fS t        |      S )N)rp   sample)rE   rh   rM   tiled_decoder?   r;   r   )rO   r|   rp   decs       rQ   _decodezAutoencoderKLFlux2._decode   s    ??d.G.G G177SU;Y]YrYrKr$$QK$@@+$$Q'All1o6MC((rR   c                 :   | j                   r_|j                  d   dkD  rM|j                  d      D cg c]  }| j                  |      j                   }}t        j                  |      }n| j                  |      j                  }|s|fS t        |      S c c}w )a  
        Decode a batch of images.

        Args:
            z (`torch.Tensor`): Input batch of latent vectors.
            return_dict (`bool`, *optional*, defaults to `True`):
                Whether to return a [`~models.vae.DecoderOutput`] instead of a plain tuple.

        Returns:
            [`~models.vae.DecoderOutput`] or `tuple`:
                If return_dict is True, a [`~models.vae.DecoderOutput`] is returned, otherwise a plain `tuple` is
                returned.

        r   r   r   )rD   rh   rt   r   r   ru   rv   r   )rO   r|   rp   	generatorz_slicedecoded_slicesdecodeds          rQ   decodezAutoencoderKLFlux2.decode   s    $ 
QJK''RS*Uwdll73::UNUii/Gll1o,,G:G,, Vs   "Babblend_extentc                     t        |j                  d   |j                  d   |      }t        |      D ]A  }|d d d d | |z   d d f   d||z  z
  z  |d d d d |d d f   ||z  z  z   |d d d d |d d f<   C |S )Nr   r   minrh   range)rO   r   r   r   ys        rQ   blend_vzAutoencoderKLFlux2.blend_v  s    1771:qwwqz<@|$ 	xAa\MA$5q89Q\AQ=QRUVWXZ[]^`aWaUbfgjvfvUwwAaAqjM	xrR   c                     t        |j                  d   |j                  d   |      }t        |      D ]A  }|d d d d d d | |z   f   d||z  z
  z  |d d d d d d |f   ||z  z  z   |d d d d d d |f<   C |S )Nr   r   r   )rO   r   r   r   re   s        rQ   blend_hzAutoencoderKLFlux2.blend_h	  s    1771:qwwqz<@|$ 	xAaA}q'889Q\AQ=QRUVWXZ[]^`aWaUbfgjvfvUwwAaAqjM	xrR   c           
         t        | j                  d| j                  z
  z        }t        | j                  | j                  z        }| j                  |z
  }g }t	        d|j
                  d   |      D ]  }g }t	        d|j
                  d   |      D ]v  }|dddd||| j                  z   ||| j                  z   f   }	| j                  |	      }	| j                  j                  r| j                  |	      }	|j                  |	       x |j                  |        g }
t        |      D ]  \  }}g }t        |      D ]d  \  }}	|dkD  r| j                  ||dz
     |   |	|      }	|dkD  r| j                  ||dz
     |	|      }	|j                  |	ddddd|d|f          f |
j                  t        j                  |d              t        j                  |
d      }|S )a  Encode a batch of images using a tiled encoder.

        When this option is enabled, the VAE will split the input tensor into tiles to compute encoding in several
        steps. This is useful to keep memory use constant regardless of image size. The end result of tiled encoding is
        different from non-tiled encoding because each tile uses a different encoder. To avoid tiling artifacts, the
        tiles overlap and are blended together to form a smooth output. You may still see tile-sized changes in the
        output, but they should be much less noticeable.

        Args:
            x (`torch.Tensor`): Input batch of images.

        Returns:
            `torch.Tensor`:
                The latent representation of the encoded videos.
        r   r   r   r   Ndim)rK   rG   rN   rM   r   rh   r:   rF   r,   r>   append	enumerater   r   ru   rv   )rO   re   overlap_sizer   	row_limitrowsirowjtileresult_rows
result_rowrn   s                rQ   ri   z AutoencoderKLFlux2._tiled_encode  s   " 444D<T<T8TUV444t7O7OOP--<	 q!''!*l3 	AC1aggaj,7 !Aq1t'@'@#@@!a$JcJcFcBccd||D);;--??40D

4 ! KK	 o 
	=FAsJ$S> F4 q5<<QUAlKDq5<<AE
D,GD!!$q!ZiZ)'C"DEF uyy;<
	= ii+
rR   c           
      "   d}t        dd|d       t        | j                  d| j                  z
  z        }t        | j                  | j                  z        }| j                  |z
  }g }t        d|j                  d   |      D ]  }g }	t        d|j                  d	   |      D ]v  }
|d
d
d
d
||| j                  z   |
|
| j                  z   f   }| j                  |      }| j                  j                  r| j                  |      }|	j                  |       x |j                  |	        g }t        |      D ]  \  }}	g }t        |	      D ]d  \  }
}|dkD  r| j                  ||dz
     |
   ||      }|
dkD  r| j                  |	|
dz
     ||      }|j                  |d
d
d
d
d
|d
|f          f |j                  t        j                   |d	              t        j                   |d      }t#        |      }|s|fS t%        |      S )a8  Encode a batch of images using a tiled encoder.

        When this option is enabled, the VAE will split the input tensor into tiles to compute encoding in several
        steps. This is useful to keep memory use constant regardless of image size. The end result of tiled encoding is
        different from non-tiled encoding because each tile uses a different encoder. To avoid tiling artifacts, the
        tiles overlap and are blended together to form a smooth output. You may still see tile-sized changes in the
        output, but they should be much less noticeable.

        Args:
            x (`torch.Tensor`): Input batch of images.
            return_dict (`bool`, *optional*, defaults to `True`):
                Whether or not to return a [`~models.autoencoder_kl.AutoencoderKLOutput`] instead of a plain tuple.

        Returns:
            [`~models.autoencoder_kl.AutoencoderKLOutput`] or `tuple`:
                If return_dict is True, a [`~models.autoencoder_kl.AutoencoderKLOutput`] is returned, otherwise a plain
                `tuple` is returned.
        aC  The tiled_encode implementation supporting the `return_dict` parameter is deprecated. In the future, the implementation of this method will be replaced with that of `_tiled_encode` and you will no longer be able to pass `return_dict`. You will also have to create a `DiagonalGaussianDistribution()` from the returned value.tiled_encodez1.0.0F)standard_warnr   r   r   r   Nr   rr   )r   rK   rG   rN   rM   r   rh   r:   rF   r,   r>   r   r   r   r   ru   rv   r   r   )rO   re   rp   deprecation_messager   r   r   r   r   r   r   r   r   r   momentsrz   s                   rQ   r   zAutoencoderKLFlux2.tiled_encode?  s    (~ 	
 	.'+>eT444D<T<T8TUV444t7O7OOP--<	 q!''!*l3 	AC1aggaj,7 !Aq1t'@'@#@@!a$JcJcFcBccd||D);;--??40D

4 ! KK	 o 
	=FAsJ$S> F4 q5<<QUAlKDq5<<AE
D,GD!!$q!ZiZ)'C"DEF uyy;<
	= ))KQ/09	<"y99rR   c           
         t        | j                  d| j                  z
  z        }t        | j                  | j                  z        }| j                  |z
  }g }t	        d|j
                  d   |      D ]  }g }t	        d|j
                  d   |      D ]v  }	|dddd||| j                  z   |	|	| j                  z   f   }
| j                  j                  r| j                  |
      }
| j                  |
      }|j                  |       x |j                  |        g }t        |      D ]  \  }}g }t        |      D ]d  \  }	}
|dkD  r| j                  ||dz
     |	   |
|      }
|	dkD  r| j                  ||	dz
     |
|      }
|j                  |
ddddd|d|f          f |j                  t        j                  |d              t        j                  |d      }|s|fS t!        |      S )a  
        Decode a batch of images using a tiled decoder.

        Args:
            z (`torch.Tensor`): Input batch of latent vectors.
            return_dict (`bool`, *optional*, defaults to `True`):
                Whether or not to return a [`~models.vae.DecoderOutput`] instead of a plain tuple.

        Returns:
            [`~models.vae.DecoderOutput`] or `tuple`:
                If return_dict is True, a [`~models.vae.DecoderOutput`] is returned, otherwise a plain `tuple` is
                returned.
        r   r   r   r   Nr   r   )rK   rM   rN   rG   r   rh   rF   r-   r?   r;   r   r   r   r   ru   rv   r   )rO   r|   rp   r   r   r   r   r   r   r   r   r   r   r   r   s                  rQ   r   zAutoencoderKLFlux2.tiled_decode}  s    444D<T<T8TUV444t7O7OOP--<	 q!''!*l3 	AC1aggaj,7 $Aq1t'@'@#@@!a$JcJcFcBccd;;22//5D,,t,

7#$ KK	 o 
	=FAsJ$S> F4 q5<<QUAlKDq5<<AE
D,GD!!$q!ZiZ)'C"DEF uyy;<
	= ii+6MC((rR   r   sample_posteriorr   c                     |}| j                  |      j                  }|r|j                  |      }n|j                         }| j	                  |      j                  }|s|fS t        |      S )aa  
        Args:
            sample (`torch.Tensor`): Input sample.
            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.
        )r   r   )r{   rs   r   moder   r   )	rO   r   r   rp   r   re   rz   r|   r   s	            rQ   forwardzAutoencoderKLFlux2.forward  sf     KKN..	  9 5A Akk!n##6MC((rR   c                 r   d| _         | j                  j                         D ]1  \  }}dt        |j                  j
                        v s(t        d       | j                  | _         | j                         D ]%  }t        |t              s|j                  d       ' | j                  t                      y)u  
        Enables fused QKV projections. For self-attention modules, all projection matrices (i.e., query, key, value)
        are fused. For cross-attention modules, key and value projection matrices are fused.

        > [!WARNING] > This API is 🧪 experimental.
        NAddedzQ`fuse_qkv_projections()` is not supported for models having added KV projections.T)fuse)original_attn_processorsr]   itemsstrrP   __name__r_   modulesrH   r   fuse_projectionsrb   r   )rO   _attn_processormodules       rQ   fuse_qkv_projectionsz'AutoencoderKLFlux2.fuse_qkv_projections  s     )-%!%!5!5!;!;!= 	vA~#n66??@@ !tuu	v )-(<(<%lln 	3F&),''T'2	3 	 5 78rR   c                 T    | j                   | j                  | j                          yy)un   Disables the fused QKV projection if enabled.

        > [!WARNING] > This API is 🧪 experimental.

        N)r   rb   )rO   s    rQ   unfuse_qkv_projectionsz)AutoencoderKLFlux2.unfuse_qkv_projections  s)     ((4##D$A$AB 5rR   )r   r   )DownEncoderBlock2Dr   r   r   )UpDecoderBlock2Dr   r   r   )         r   r   silu    r   i   TTTTg-C6?g?)r   r   )T)TN)FTN)%r   
__module____qualname____doc__ _supports_gradient_checkpointing_no_split_modulesr   rK   r   r   boolfloatr9   rd   ru   Tensorro   r   r   r   r   r{   r   r   FloatTensorr   r   r   ri   r   r   r   	Generatorr   r   r   __classcell__)rP   s   @rQ   r   r   '   sO   6 (,$0/B -
+
/
 !"!!!#$((, $%(&,CT(T( T(  S/	T( c3hT(  "#s(O!T(, -T(. /T(0 1T(2 3T(4 5T(6 7T(8 9T(: ";T(< "&=T(> ?T(@ #AT(B #s(OCT( T(n+
 
%,, 
 37::,0:	"E*F$GG	H: :8) )D )E-Y^YeYeJeDf ) HL-""-15-	}e///	0- -8 %,, c ell  %,, c ell .u|| . .`<:ell <: <:I\ <:|/)ell /) /)}^c^j^jOjIk /)h "' /3)) ) 	)
 EOO,) 
}ell*	+):9,CrR   r   )'rA   typingr   r   r   ru   torch.nnr<   configuration_utilsr   r   loadersr	   loaders.single_file_modelr
   utilsr   utils.accelerate_utilsr   	attentionr   attention_processorr   r   r   r   r   r   modeling_outputsr   modeling_utilsr   vaer   r   r   r   r   r    rR   rQ   <module>r      s^     ) )   B ' ?  8 &  3 ' ` `AC .+?UWgACrR   