
    biM                        d dl mZmZmZmZ d dlZd dlmZ d dlmc m	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 dd	lmZ dd
lmZ ddlmZ ddlmZmZ  ej<                  e      Z dZ! G d dejD                        Z# G d dejH                        Z% G d dejL                        Z' G d dejH                        Z( G d dejH                        Z) G d dejH                        Z* G d dejH                        Z+ G d dejH                        Z, G d dejH                        Z- G d  d!ejH                        Z. G d" d#eee      Z/y)$    )ListOptionalTupleUnionN   )ConfigMixinregister_to_config)FromOriginalModelMixin)logging)apply_forward_hook   )get_activation)AutoencoderKLOutput)
ModelMixin   )DecoderOutputDiagonalGaussianDistributionc                        e Zd ZdZ	 	 ddededeeeeeef   f   deeeeeef   f   deeeeeef   f   ddf fd	Zd fd
	Z xZ	S )QwenImageCausalConv3dau  
    A custom 3D causal convolution layer with feature caching support.

    This layer extends the standard Conv3D layer by ensuring causality in the time dimension and handling feature
    caching for efficient inference.

    Args:
        in_channels (int): Number of channels in the input image
        out_channels (int): Number of channels produced by the convolution
        kernel_size (int or tuple): Size of the convolving kernel
        stride (int or tuple, optional): Stride of the convolution. Default: 1
        padding (int or tuple, optional): Zero-padding added to all three sides of the input. Default: 0
    in_channelsout_channelskernel_sizestridepaddingreturnNc                     t         |   |||||       | j                  d   | j                  d   | j                  d   | j                  d   d| j                  d   z  df| _        d| _        y )N)r   r   r   r   r   r   r   r   r   r   r   )super__init__r   _padding)selfr   r   r   r   r   	__class__s         q/home/cdr/jupyterlab/.venv/lib/python3.12/site-packages/diffusers/models/autoencoders/autoencoder_kl_qwenimage.pyr   zQwenImageCausalConv3d.__init__:   sx     	#%# 	 	
 a$,,q/4<<?DLLYZO]^aeamamnoap]prst     c                 <   t        | j                        }|`| j                  d   dkD  rN|j                  |j                        }t	        j
                  ||gd      }|dxx   |j                  d   z  cc<   t        j                  ||      }t        | )  |      S )N   r   r   dim)listr    todevicetorchcatshapeFpadr   forward)r!   xcache_xr   r"   s       r#   r1   zQwenImageCausalConv3d.forwardN   s    t}}%4==#3a#7jj*G		7A,A.AAJ'--**JEE!Wwq!!r$   )r   r   N)
__name__
__module____qualname____doc__intr   r   r   r1   __classcell__r"   s   @r#   r   r   +   s    & 4545!! ! 3c3m 445	!
 c5c3//0! sE#sC-001! 
!(" "r$   r   c                   @     e Zd ZdZd
dededededdf
 fdZd	 Z xZS )QwenImageRMS_norma  
    A custom RMS normalization layer.

    Args:
        dim (int): The number of dimensions to normalize over.
        channel_first (bool, optional): Whether the input tensor has channels as the first dimension.
            Default is True.
        images (bool, optional): Whether the input represents image data. Default is True.
        bias (bool, optional): Whether to include a learnable bias term. Default is False.
    r(   channel_firstimagesbiasr   Nc                 .   t         |           |sdnd}|r|g|n|f}|| _        |dz  | _        t	        j
                  t        j                  |            | _        |r.t	        j
                  t        j                  |            | _
        y d| _
        y )N)r   r   r   )r   r   g      ?        )r   r   r>   scalenn	Parameterr,   onesgammazerosr@   )r!   r(   r>   r?   r@   broadcastable_dimsr.   r"   s          r#   r   zQwenImageRMS_norm.__init__d   sy    .4Y&.;*)*#*#X
\\%**U"34
8<BLLU!34	#	r$   c                     t        j                  || j                  rdnd      | j                  z  | j                  z  | j
                  z   S )Nr   r'   )r/   	normalizer>   rC   rG   r@   )r!   r2   s     r#   r1   zQwenImageRMS_norm.forwardn   s>    {{1(:(:1DtzzQTXT^T^^aeajajjjr$   TTF)	r5   r6   r7   r8   r9   boolr   r1   r:   r;   s   @r#   r=   r=   X   s>    	FC F FT FX\ Fim Fkr$   r=   c                   "     e Zd ZdZ fdZ xZS )QwenImageUpsamplea   
    Perform upsampling while ensuring the output tensor has the same data type as the input.

    Args:
        x (torch.Tensor): Input tensor to be upsampled.

    Returns:
        torch.Tensor: Upsampled tensor with the same data type as the input.
    c                 \    t         |   |j                               j                  |      S r4   )r   r1   floattype_as)r!   r2   r"   s     r#   r1   zQwenImageUpsample.forward}   s#    wqwwy)11!44r$   )r5   r6   r7   r8   r1   r:   r;   s   @r#   rP   rP   r   s    5 5r$   rP   c                   >     e Zd ZdZdededdf fdZddgfdZ xZS )	QwenImageResampleax  
    A custom resampling module for 2D and 3D data.

    Args:
        dim (int): The number of input/output channels.
        mode (str): The resampling mode. Must be one of:
            - 'none': No resampling (identity operation).
            - 'upsample2d': 2D upsampling with nearest-exact interpolation and convolution.
            - 'upsample3d': 3D upsampling with nearest-exact interpolation, convolution, and causal 3D convolution.
            - 'downsample2d': 2D downsampling with zero-padding and convolution.
            - 'downsample3d': 3D downsampling with zero-padding, convolution, and causal 3D convolution.
    r(   moder   Nc           	         t         |           || _        || _        |dk(  rAt	        j
                  t        dd      t	        j                  ||dz  dd            | _        y |d	k(  rXt	        j
                  t        dd      t	        j                  ||dz  dd            | _        t        ||dz  d
d      | _
        y |dk(  rFt	        j
                  t	        j                  d      t	        j                  ||dd            | _        y |dk(  r[t	        j
                  t	        j                  d      t	        j                  ||dd            | _        t        ||d
dd      | _
        y t	        j                         | _        y )N
upsample2d)       @rY   znearest-exact)scale_factorrV   r   r   r   r   
upsample3d)r   r   r   )r   r   r   downsample2d)r   r   r   r   )r   r   )r   downsample3d)r   r   r   r   )r   r   )r   r   r(   rV   rD   
SequentialrP   Conv2dresampler   	time_conv	ZeroPad2dIdentity)r!   r(   rV   r"   s      r#   r   zQwenImageResample.__init__   s9   	 <MM!zP		#saxA6DM \!MM!zP		#saxA6DM 33aT]^DN^#MM",,|*DbiiPSUXZ[djFklDM^#MM",,|*DbiiPSUXZ[djFklDM23YybklDN KKMDMr$   r   c                    |j                         \  }}}}}| j                  dk(  r||d   }	||	   d||	<   |dxx   dz  cc<   n|d d d d t         d d d d d f   j                         }
|
j                  d   dk  ra||	   \||	   dk7  rTt        j                  ||	   d d d d dd d d d f   j                  d      j                  |
j                        |
gd      }
|
j                  d   dk  rR||	   M||	   dk(  rEt        j                  t        j                  |
      j                  |
j                        |
gd      }
||	   dk(  r| j                  |      }n| j                  |||	         }|
||	<   |dxx   dz  cc<   |j                  |d||||      }t        j                  |d d dd d d d d d d d f   |d d dd d d d d d d d f   fd      }|j                  |||dz  ||      }|j                  d   }|j                  ddddd	      j                  ||z  |||      }| j                  |      }|j!                  |||j                  d      |j                  d      |j                  d            j                  ddddd	      }| j                  d
k(  r||d   }	||	   "|j                         ||	<   |dxx   dz  cc<   |S |d d d d dd d d d d f   j                         }
| j                  t        j                  ||	   d d d d dd d d d d f   |gd            }|
||	<   |dxx   dz  cc<   |S )Nr\   r   Repr   r   rK   r'   r   r&   r^   )sizerV   CACHE_Tcloner.   r,   r-   	unsqueezer*   r+   
zeros_likerb   reshapestackpermutera   view)r!   r2   
feat_cachefeat_idxbcthwidxr3   s              r#   r1   zQwenImageResample.forward   s5   1aA99$%qkc?*&+JsOQK1$K1whiA 56<<>G}}Q'!+
30KPZ[^P_chPh"'))'_Q2q!^<FFqILLW^^\^eflm# }}Q'!+
30KPZ[^P_chPh"'))U-=-=g-F-I-I'..-Y[b,cij"k!#%/ NN1- NN1jo>&-JsOQK1$K		!Q1a3AQq!Q1a'7%8!Aq!Q1<L:M$NPQRA		!QAq!4AGGAJIIaAq!$,,QUAq!<MM!FF1aAFF1Iqvvay9AA!Q1aP99&%qkc?*&'ggiJsOQK1$K 	  1bc1a0668Guyy*S/!QQPQ/2RTU1VXY'Z[A&-JsOQK1$Kr$   )	r5   r6   r7   r8   r9   strr   r1   r:   r;   s   @r#   rU   rU      s0    *C *s *t *6 %)A3 +r$   rU   c                   L     e Zd ZdZ	 	 ddededededdf
 fdZdd	gfd
Z xZ	S )QwenImageResidualBlockaE  
    A custom residual block module.

    Args:
        in_dim (int): Number of input channels.
        out_dim (int): Number of output channels.
        dropout (float, optional): Dropout rate for the dropout layer. Default is 0.0.
        non_linearity (str, optional): Type of non-linearity to use. Default is "silu".
    in_dimout_dimdropoutnon_linearityr   Nc                    t         |           || _        || _        t	        |      | _        t        |d      | _        t        ||dd      | _	        t        |d      | _
        t        j                  |      | _        t        ||dd      | _        ||k7  rt        ||d      | _        y t        j                         | _        y )NFr?   r   r   r[   )r   r   r{   r|   r   nonlinearityr=   norm1r   conv1norm2rD   Dropoutr}   conv2rd   conv_shortcut)r!   r{   r|   r}   r~   r"   s        r#   r   zQwenImageResidualBlock.__init__   s     	*=9 've<
*67AqI
&wu=
zz'**7GQJ
JPT[J[267AFacalalanr$   r   c           	      (   | j                  |      }| j                  |      }| j                  |      }||d   }|d d d d t         d d d d d f   j	                         }|j
                  d   dk  rY||   Tt        j                  ||   d d d d dd d d d f   j                  d      j                  |j                        |gd      }| j                  |||         }|||<   |dxx   dz  cc<   n| j                  |      }| j                  |      }| j                  |      }| j                  |      }||d   }|d d d d t         d d d d d f   j	                         }|j
                  d   dk  rY||   Tt        j                  ||   d d d d dd d d d f   j                  d      j                  |j                        |gd      }| j                  |||         }|||<   |dxx   dz  cc<   ||z   S | j                  |      }||z   S Nr   r   rK   r'   r   )r   r   r   rh   ri   r.   r,   r-   rj   r*   r+   r   r   r}   r   )r!   r2   rp   rq   ru   rw   r3   s          r#   r1   zQwenImageResidualBlock.forward   s   q! JJqMa !1+C1whiA-.446G}}Q!#
3(C))Z_Q2q!^%D%N%Nq%Q%T%TU\UcUc%dfm$ntuv

1jo.A%JsOQK1K

1A JJqMa  LLO!1+C1whiA-.446G}}Q!#
3(C))Z_Q2q!^%D%N%Nq%Q%T%TU\UcUc%dfm$ntuv

1jo.A%JsOQK1K
 1u 

1A 1ur$   )rB   silu
r5   r6   r7   r8   r9   rR   rx   r   r1   r:   r;   s   @r#   rz   rz      sY     #oo o 	o
 o 
o( %)A3 (r$   rz   c                   (     e Zd ZdZ fdZd Z xZS )QwenImageAttentionBlockz}
    Causal self-attention with a single head.

    Args:
        dim (int): The number of channels in the input tensor.
    c                     t         |           || _        t        |      | _        t        j                  ||dz  d      | _        t        j                  ||d      | _        y )Nr   r   )	r   r   r(   r=   normrD   r`   to_qkvproj)r!   r(   r"   s     r#   r   z QwenImageAttentionBlock.__init__*  sO     &c*	iiS1Wa0IIc3*	r$   c                    |}|j                         \  }}}}}|j                  ddddd      j                  ||z  |||      }| j                  |      }| j	                  |      }|j                  ||z  d|dz  d      }|j                  dddd      j                         }|j                  dd      \  }	}
}t        j                  |	|
|      }|j                  d      j                  ddd      j                  ||z  |||      }| j                  |      }|j                  |||||      }|j                  ddddd      }||z   S )Nr   r   r   r   r&   rK   r'   )rg   rn   rl   r   r   
contiguouschunkr/   scaled_dot_product_attentionsqueezer   ro   )r!   r2   identity
batch_sizechannelstimeheightwidthqkvqkvs               r#   r1   zQwenImageAttentionBlock.forward3  sH   45FFH1
HdFEIIaAq!$,,Z$->&RWXIIaL kk!nkk*t+Q1bAkk!Q1%002))A2)&1a **1a3IIaL  Aq)11*t2CXvW\] IIaL FF:tXvu=IIaAq!$8|r$   )r5   r6   r7   r8   r   r1   r:   r;   s   @r#   r   r   "  s    +r$   r   c            	       D     e Zd ZdZd
dedededef fdZddgfd	Z xZ	S )QwenImageMidBlockz
    Middle block for QwenImageVAE encoder and decoder.

    Args:
        dim (int): Number of input/output channels.
        dropout (float): Dropout rate.
        non_linearity (str): Type of non-linearity to use.
    r(   r}   r~   
num_layersc           	      V   t         |           || _        t        ||||      g}g }t	        |      D ]9  }|j                  t        |             |j                  t        ||||             ; t        j                  |      | _	        t        j                  |      | _
        d| _        y )NF)r   r   r(   rz   rangeappendr   rD   
ModuleList
attentionsresnetsgradient_checkpointing)	r!   r(   r}   r~   r   r   r   _r"   s	           r#   r   zQwenImageMidBlock.__init__Y  s     *#sG]KL
z" 	UA5c:;NN1#sG]ST	U --
3}}W-&+#r$   Nr   c                      | j                   d   |||      }t        | j                  | j                   dd        D ]  \  }}| ||      } ||||      } |S Nr   r   )r   zipr   )r!   r2   rp   rq   attnresnets         r#   r1   zQwenImageMidBlock.forwardh  si    DLLOAz84  ab1AB 	0LD&Gq*h/A		0 r$   )rB   r   r   r   r;   s   @r#   r   r   O  s8    ,C ,% ,c ,`c , %)A3 r$   r   c                   P     e Zd ZdZddg ddg g dddfd	ef fd
ZddgfdZ xZS )QwenImageEncoder3dao  
    A 3D encoder module.

    Args:
        dim (int): The base number of channels in the first layer.
        z_dim (int): The dimensionality of the latent space.
        dim_mult (list of int): Multipliers for the number of channels in each block.
        num_res_blocks (int): Number of residual blocks in each block.
        attn_scales (list of float): Scales at which to apply attention mechanisms.
        temperal_downsample (list of bool): Whether to downsample temporally in each block.
        dropout (float): Dropout rate for the dropout layers.
        non_linearity (str): Type of non-linearity to use.
       r&   r   r   r&   r&   r   rM   rB   r   r~   c	           	      L   t         |           || _        || _        || _        || _        || _        || _        t        |      | _	        dg|z   D 	cg c]  }	||	z  	 }
}	d}t        d|
d   dd      | _        t        j                  g       | _        t        t!        |
d d |
dd              D ]  \  }\  }}t#        |      D ]R  }| j                  j%                  t'        |||             ||v r$| j                  j%                  t)        |             |}T |t+        |      dz
  k7  s{||   rdnd}| j                  j%                  t-        ||	             |d
z  } t/        ||d      | _        t3        |d      | _        t        ||dd      | _        d| _        y c c}	w )Nr         ?r   r   r[   rK   r^   r]   rV   rY   r   Fr   )r   r   r(   z_dimdim_multnum_res_blocksattn_scalestemperal_downsampler   r   r   conv_inrD   r   down_blocks	enumerater   r   r   rz   r   lenrU   r   	mid_blockr=   norm_outconv_outr   )r!   r(   r   r   r   r   r   r}   r~   udimsrC   ir{   r|   r   rV   r"   s                    r#   r   zQwenImageEncoder3d.__init__  s    	
 ,&#6 *=9 #$x0Aa00 -QQAF ==,$-c$s)T!"X.F$G 	 A >* !  ''(>vwPW(XYK'$$++,CG,LM 	! CMA%%)<Q)?~^  ''(9'(MN	 +7G]WXY *'%@-guaK&+#; 1s   F!Nr   c           	         ||d   }|d d d d t          d d d d d f   j                         }|j                  d   dk  rY||   Tt        j                  ||   d d d d dd d d d f   j                  d      j                  |j                        |gd      }| j                  |||         }|||<   |dxx   dz  cc<   n| j                  |      }| j                  D ]  }| ||||      } ||      } | j                  |||      }| j                  |      }| j                  |      }||d   }|d d d d t          d d d d d f   j                         }|j                  d   dk  rY||   Tt        j                  ||   d d d d dd d d d f   j                  d      j                  |j                        |gd      }| j                  |||         }|||<   |dxx   dz  cc<   |S | j                  |      }|S r   )rh   ri   r.   r,   r-   rj   r*   r+   r   r   r   r   r   r   )r!   r2   rp   rq   rw   r3   layers          r#   r1   zQwenImageEncoder3d.forward  s   !1+C1whiA-.446G}}Q!#
3(C))Z_Q2q!^%D%N%Nq%Q%T%TU\UcUc%dfm$ntuvQ
30A%JsOQK1KQA %% 	E%!Z2!H		 NN1j(3 MM!a !1+C1whiA-.446G}}Q!#
3(C))Z_Q2q!^%D%N%Nq%Q%T%TU\UcUc%dfm$ntuvaC1A%JsOQK1K  a Ar$   r5   r6   r7   r8   rx   r   r1   r:   r;   s   @r#   r   r   v  s@      /#2, 2,h %)A3 %r$   r   c                   X     e Zd ZdZ	 	 	 ddededededee   def fd	Zdd
gfdZ	 xZ
S )QwenImageUpBlocka  
    A block that handles upsampling for the QwenImageVAE decoder.

    Args:
        in_dim (int): Input dimension
        out_dim (int): Output dimension
        num_res_blocks (int): Number of residual blocks
        dropout (float): Dropout rate
        upsample_mode (str, optional): Mode for upsampling ('upsample2d' or 'upsample3d')
        non_linearity (str): Type of non-linearity to use
    Nr{   r|   r   r}   upsample_moder~   c           	      J   t         
|           || _        || _        g }|}t	        |dz         D ]!  }	|j                  t        ||||             |}# t        j                  |      | _	        d | _
        |&t        j                  t        ||      g      | _
        d| _        y )Nr   r   F)r   r   r{   r|   r   r   rz   rD   r   r   
upsamplersrU   r   )r!   r{   r|   r   r}   r   r~   r   current_dimr   r"   s             r#   r   zQwenImageUpBlock.__init__  s     	 ~)* 	"ANN1+wQ^_`!K	" }}W- $ mm->w]-[,\]DO&+#r$   r   c                     | j                   D ]  }| ||||      } ||      } | j                  0| | j                  d   |||      }|S  | j                  d   |      }|S )aI  
        Forward pass through the upsampling block.

        Args:
            x (torch.Tensor): Input tensor
            feat_cache (list, optional): Feature cache for causal convolutions
            feat_idx (list, optional): Feature index for cache management

        Returns:
            torch.Tensor: Output tensor
        r   )r   r   )r!   r2   rp   rq   r   s        r#   r1   zQwenImageUpBlock.forward  s     ll 	F%1j(31I		 ??&%&DOOA&q*h?  'DOOA&q)r$   )rB   Nr   )r5   r6   r7   r8   r9   rR   r   rx   r   r1   r:   r;   s   @r#   r   r     sd    
" '+#,, , 	,
 ,  }, ,< %)A3 r$   r   c                   P     e Zd ZdZddg ddg g dddfd	ef fd
ZddgfdZ xZS )QwenImageDecoder3dak  
    A 3D decoder module.

    Args:
        dim (int): The base number of channels in the first layer.
        z_dim (int): The dimensionality of the latent space.
        dim_mult (list of int): Multipliers for the number of channels in each block.
        num_res_blocks (int): Number of residual blocks in each block.
        attn_scales (list of float): Scales at which to apply attention mechanisms.
        temperal_upsample (list of bool): Whether to upsample temporally in each block.
        dropout (float): Dropout rate for the dropout layers.
        non_linearity (str): Type of non-linearity to use.
    r   r&   r   r   FTTrB   r   r~   c	           	         t         |           || _        || _        || _        || _        || _        || _        t        |      | _	        |d   g|d d d   z   D 	cg c]  }	||	z  	 }
}	ddt        |      dz
  z  z  }t        ||
d   dd      | _        t        |
d   ||d      | _        t        j                   g       | _        t%        t'        |
d d |
dd              D ]b  \  }\  }}|dkD  r|dz  }d }|t        |      dz
  k7  r	||   rd	nd
}t)        ||||||      }| j"                  j+                  |       |^|dz  }d t-        d      | _        t        |ddd      | _        d| _        y c c}	w )NrK   r   r   r   r   r   r[   r   r\   rX   )r{   r|   r   r}   r   r~   rY   Fr   )r   r   r(   r   r   r   r   temperal_upsampler   r   r   r   r   r   r   rD   r   	up_blocksr   r   r   r   r=   r   r   r   )r!   r(   r   r   r   r   r   r}   r~   r   r   rC   r   r{   r|   r   up_blockr"   s                    r#   r   zQwenImageDecoder3d.__init__5  s    	
 ,&!2*=9 #+2,(4R4.!@AAaAAaCMA-.. -UDGQJ +47G]WXY r*$-c$s)T!"X.F$G 	 A 1u1 !MCMA%%0A!0D, (-++H NN!!(+ (/	4 *'%@-gq!QG&+#Q Bs   E3Nr   c           	         ||d   }|d d d d t          d d d d d f   j                         }|j                  d   dk  rY||   Tt        j                  ||   d d d d dd d d d f   j                  d      j                  |j                        |gd      }| j                  |||         }|||<   |dxx   dz  cc<   n| j                  |      }| j                  |||      }| j                  D ]  } ||||      } | j                  |      }| j                  |      }||d   }|d d d d t          d d d d d f   j                         }|j                  d   dk  rY||   Tt        j                  ||   d d d d dd d d d f   j                  d      j                  |j                        |gd      }| j                  |||         }|||<   |dxx   dz  cc<   |S | j                  |      }|S r   )rh   ri   r.   r,   r-   rj   r*   r+   r   r   r   r   r   r   )r!   r2   rp   rq   rw   r3   r   s          r#   r1   zQwenImageDecoder3d.forwardu  s   !1+C1whiA-.446G}}Q!#
3(C))Z_Q2q!^%D%N%Nq%Q%T%TU\UcUc%dfm$ntuvQ
30A%JsOQK1KQA NN1j(3  	2HJ1A	2 MM!a !1+C1whiA-.446G}}Q!#
3(C))Z_Q2q!^%D%N%Nq%Q%T%TU\UcUc%dfm$ntuvaC1A%JsOQK1K  a Ar$   r   r;   s   @r#   r   r   &  s@      -#>, >,@ %)A3 #r$   r   c                   Z    e Zd ZdZdZeddg ddg g ddg d	g d
f	dededee   dedee	   dee
   de	dee	   dee	   ddf fd       Z	 	 	 	 d2dee   dee   dee	   dee	   ddf
dZd3dZd3dZd3dZd Zd ej&                  fd!Ze	 d4d ej&                  d"e
deeee   f   fd#       Zd4d$ej&                  d"e
fd%Zed4d$ej&                  d"e
deeej&                  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fd,Zd4d$ej&                  d"e
deeej&                  f   fd-Z 	 	 	 d5d.ej&                  d/e
d"e
d0eejB                     deeej&                  f   f
d1Z" xZ#S )6AutoencoderKLQwenImagea  
    A VAE model with KL loss for encoding videos into latents and decoding latent representations into videos.

    This model inherits from [`ModelMixin`]. Check the superclass documentation for it's generic methods implemented
    for all models (such as downloading or saving).
    F`      r   r   r   rB   )gy):gMOg^)gQ?gtVƿgZӼ?gBfjÿgU0*?gL
F%u?gMg&?gz6>׿gF%uȿg[ AcgMJ?gW2ıҿ)g_L@gNё\C?gQ@g?@g9#J{?g|a2U?gHPs@g0* @gJ{/L&
@gJY8@g]C@g(?gK46?gS:?go_Ι@g-?base_dimr   r   r   r   r   r}   latents_meanlatents_stdr   Nc
           	         t         
|           || _        || _        |d d d   | _        t        ||dz  |||| j                  |      | _        t        |dz  |dz  d      | _        t        ||d      | _	        t        |||||| j                  |      | _        dt        | j                        z  | _        d| _        d| _        d| _        d| _        d| _        d| _        | j                  *t)        d | j                  j+                         D              nd| j                  *t)        d	 | j                  j+                         D              ndd
| _        y )NrK   r   r   F      c              3   <   K   | ]  }t        |t                y wr4   
isinstancer   .0ms     r#   	<genexpr>z2AutoencoderKLQwenImage.__init__.<locals>.<genexpr>       `A:a)>?`   r   c              3   <   K   | ]  }t        |t                y wr4   r   r   s     r#   r   z2AutoencoderKLQwenImage.__init__.<locals>.<genexpr>  r   r   )decoderencoder)r   r   r   r   r   r   r   r   
quant_convpost_quant_convr   r   r   spatial_compression_ratiouse_slicing
use_tilingtile_sample_min_heighttile_sample_min_widthtile_sample_stride_heighttile_sample_stride_widthsummodules_cached_conv_counts)r!   r   r   r   r   r   r   r}   r   r   r"   s             r#   r   zAutoencoderKLQwenImage.__init__  sT    	
#6 !4TrT!:)eai>;H`H`bi
 0	519aH4UE1E)eX~{DDZDZ\c
 *+c$2J2J.K)K& !
   '*#%(" *-&(+%
 ||' `I]I]I_``||' `I]I]I_``$
 r$   r   r   r   r   c                     d| _         |xs | j                  | _        |xs | j                  | _        |xs | j                  | _        |xs | j                  | _        y)aX  
        Enable tiled VAE decoding. When this option is enabled, the VAE will split the input tensor into tiles to
        compute decoding and encoding in several steps. This is useful for saving a large amount of memory and to allow
        processing larger images.

        Args:
            tile_sample_min_height (`int`, *optional*):
                The minimum height required for a sample to be separated into tiles across the height dimension.
            tile_sample_min_width (`int`, *optional*):
                The minimum width required for a sample to be separated into tiles across the width dimension.
            tile_sample_stride_height (`int`, *optional*):
                The minimum amount of overlap between two consecutive vertical tiles. This is to ensure that there are
                no tiling artifacts produced across the height dimension.
            tile_sample_stride_width (`int`, *optional*):
                The stride between two consecutive horizontal tiles. This is to ensure that there are no tiling
                artifacts produced across the width dimension.
        TN)r   r   r   r   r   )r!   r   r   r   r   s        r#   enable_tilingz$AutoencoderKLQwenImage.enable_tiling  sW    0 &<&[@[@[#%:%Xd>X>X")B)ddFdFd&(@(aDDaDa%r$   c                     d| _         y)z
        Disable tiled VAE decoding. If `enable_tiling` was previously enabled, this method will go back to computing
        decoding in one step.
        FN)r   r!   s    r#   disable_tilingz%AutoencoderKLQwenImage.disable_tiling  s    
  r$   c                     d| _         y)z
        Enable sliced VAE decoding. When this option is enabled, the VAE will split the input tensor in slices to
        compute decoding in several steps. This is useful to save some memory and allow larger batch sizes.
        TNr   r   s    r#   enable_slicingz%AutoencoderKLQwenImage.enable_slicing  s    
  r$   c                     d| _         y)z
        Disable sliced VAE decoding. If `enable_slicing` was previously enabled, this method will go back to computing
        decoding in one step.
        FNr  r   s    r#   disable_slicingz&AutoencoderKLQwenImage.disable_slicing  s    
 !r$   c                     d } || j                         | _        dg| _        d g| j                  z  | _         || j                        | _        dg| _        d g| j
                  z  | _        y )Nc                 `    d}| j                         D ]  }t        |t              s|dz  } |S r   )r   r   r   )modelcountr   s      r#   _count_conv3dz9AutoencoderKLQwenImage.clear_cache.<locals>._count_conv3d  s7    E]]_ a!67QJE Lr$   r   )r   	_conv_num	_conv_idx	_feat_mapr   _enc_conv_num_enc_conv_idx_enc_feat_map)r!   r
  s     r#   clear_cachez"AutoencoderKLQwenImage.clear_cache  sd    	 't||4$..0*4<<8S"Vd&8&88r$   r2   c           
         |j                   \  }}}}}| j                  r/|| j                  kD  s|| j                  kD  r| j	                  |      S | j                          d|dz
  dz  z   }t        |      D ]  }dg| _        |dk(  r;| j                  |d d d d d dd d d d f   | j                  | j                        }K| j                  |d d d d dd|dz
  z  z   dd|z  z   d d d d f   | j                  | j                        }	t        j                  |	gd      } | j                        }
| j                          |
S )Nr   r&   r   rp   rq   r   )r.   r   r   r   tiled_encoder  r   r  r   r  r,   r-   r   )r!   r2   r   	num_framer   r   iter_r   outout_encs              r#   _encodezAutoencoderKLQwenImage._encode$  sG   )*&1i??(B(B BftOjOjFj$$Q''Y]q((u 
	0A"#DAvll1Q2A2q!^#4ASAS^b^p^plq||aAQUOa!a%i7A=>#11!// $ 
 iidQ/
	0 ooc"
r$   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 videos. If `return_dict` is True, a
                [`~models.autoencoder_kl.AutoencoderKLOutput`] is returned, otherwise a plain `tuple` is returned.
        r   r   )latent_dist)r   r.   splitr  r,   r-   r   r   )r!   r2   r  x_sliceencoded_slicesru   	posteriors          r#   encodezAutoencoderKLQwenImage.encode<  s      
QCD771:Ndll73NNN		.)AQA03	<"y99 Os   Bzc           
         |j                   \  }}}}}| j                  | j                  z  }| j                  | j                  z  }| j                  r||kD  s||kD  r| j                  ||      S | j                          | j                  |      }	t        |      D ]  }
dg| _	        |
dk(  r>| j                  |	d d d d |
|
dz   d d d d f   | j                  | j                        }N| j                  |	d d d d |
|
dz   d d d d f   | j                  | j                        }t        j                  |gd      } t        j                  dd      }| j                          |s|fS t        |	      S )
Nr  r   r   r  r   g      r   )minmaxsample)r.   r   r   r   r   tiled_decoder  r   r   r  r   r  r,   r-   clampr   )r!   r#  r  r   r  r   r   tile_latent_min_heighttile_latent_min_widthr2   r   r  r  s                r#   _decodezAutoencoderKLQwenImage._decodeW  sh   )*&1i!%!<!<@^@^!^ $ : :d>\>\ \??(= =J`A`$$QK$@@  #y! 	0ASDNAvll1Q1q1u9a%:#;aeaoaolp||AaAAIq!&;$<bfbpbp|qiidQ/	0 kk#4S16MC((r$   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(  )r   r.   r  r.  r)  r,   r-   r   )r!   r#  r  z_slicedecoded_slicesdecodeds         r#   decodezAutoencoderKLQwenImage.decodep  s     
QJK''RS*Uwdll73::UNUii/Gll1o,,G:G,, Vs   "Barr   blend_extentc           	         t        |j                  d   |j                  d   |      }t        |      D ]J  }|d d d d d d | |z   d d f   d||z  z
  z  |d d d d d d |d d f   ||z  z  z   |d d d d d d |d d f<   L |S )Nr   r&  r.   r   )r!   r4  rr   r5  ys        r#   blend_vzAutoencoderKLQwenImage.blend_v  s    1772;\B|$ 	A Aq<-!*;Q!>?1q<GWCWX[\]^`acdfgij]j[kL \  AaAq!m	 r$   c                    t        |j                  d   |j                  d   |      }t        |      D ]J  }|d d d d d d d d | |z   f   d||z  z
  z  |d d d d d d d d |f   ||z  z  z   |d d d d d d d d |f<   L |S )NrK   r   r8  )r!   r4  rr   r5  r2   s        r#   blend_hzAutoencoderKLQwenImage.blend_h  s    1772;\B|$ 	A Aq!l]Q->!>?1q<GWCWX[\]^`acdfgij]j[kL \  AaAq!m	 r$   c                    |j                   \  }}}}}|| j                  z  }|| j                  z  }| j                  | j                  z  }| j                  | j                  z  }	| j                  | j                  z  }
| j
                  | j                  z  }||
z
  }|	|z
  }g }t        d|| j                        D ]J  }g }t        d|| j
                        D ]  }| j                          g }d|dz
  dz  z   }t        |      D ]  }dg| _        |dk(  r/|dddddd||| j                  z   ||| j                  z   f   }n=|dddddd|dz
  z  z   dd|z  z   ||| j                  z   ||| j                  z   f   }| j                  || j                  | j                        }| j                  |      }|j                  |        |j                  t        j                  |d              |j                  |       M | j                          g }t        |      D ]  \  }}g }t        |      D ]g  \  }}|dkD  r| j!                  ||dz
     |   ||      }|dkD  r| j#                  ||dz
     ||      }|j                  |ddddddd|
d|f          i |j                  t        j                  |d              t        j                  |d	      ddddddd|d|f   }|S )
zEncode a batch of images using a tiled encoder.

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

        Returns:
            `torch.Tensor`:
                The latent representation of the encoded videos.
        r   r   r&   Nr  r   r'   rK   r   )r.   r   r   r   r   r   r   r  r  r   r  r   r   r,   r-   r   r:  r<  )r!   r2   r   
num_framesr   r   latent_heightlatent_widthr,  r-  tile_latent_stride_heighttile_latent_stride_widthblend_heightblend_widthrowsr   rowjr   frame_ranger   tileresult_rows
result_rowr  s                            r#   r  z#AutoencoderKLQwenImage.tiled_encode  s9    +,'''1j&%$"@"@@ > >>!%!<!<@^@^!^ $ : :d>\>\ \$($B$BdFdFd$d!#'#@#@DDbDb#b -0II+.FF q&$"@"@A 	AC1eT%B%BC 3  ":>a"77{+ &A*+D&Av Arr1q43N3N/N+NPQTUX\XrXrTrPr!rs QUOa!a%i7D$?$? ??D$>$> >>	@   <<9K9KVZVhVh<iD??40DKK%& 

599Tq12'3( KK-	. 	o 
	>FAsJ$S> h4 q5<<QUAlKDq5<<AE
D+FD!!$q!Q0J1J0JLeMeLe'e"fgh uyy<=
	> ii+Aq!^m^]l],RS
r$   c                    |j                   \  }}}}}|| j                  z  }|| j                  z  }| j                  | j                  z  }	| j                  | j                  z  }
| j                  | j                  z  }| j
                  | j                  z  }| j                  | j                  z
  }| j                  | j
                  z
  }g }t        d||      D ]  }g }t        d||      D ]  }| j                          g }t        |      D ]q  }dg| _        |dddd||dz   |||	z   |||
z   f   }| j                  |      }| j                  || j                  | j                        }|j                  |       s |j                  t        j                  |d              |j                  |        | j                          g }t        |      D ]  \  }}g }t        |      D ]{  \  }}|dkD  r| j!                  ||dz
     |   ||      }|dkD  r| j#                  ||dz
     ||      }|j                  |ddddddd| j                  d| j
                  f          } |j                  t        j                  |d              t        j                  |d      ddddddd|d|f   }|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   Nr   r  r   r'   rK   r   r(  )r.   r   r   r   r   r   r   r  r  r   r   r  r   r,   r-   r   r:  r<  r   )r!   r#  r  r   r>  r   r   sample_heightsample_widthr,  r-  rA  rB  rC  rD  rE  r   rF  rG  r   r   rI  r2  rJ  rK  decs                             r#   r*  z#AutoencoderKLQwenImage.tiled_decode  s    +,'''1j&%!?!??t===!%!<!<@^@^!^ $ : :d>\>\ \$($B$BdFdFd$d!#'#@#@DDbDb#b 22T5S5SS0043P3PP q&";< 	AC1e%=> 	3  "z* )A&'SDNQ1q1u9a!6L2L.LaRSVkRkNkklD//5D"ll4DNNUYUcUcldGKK() 

599Tq12	3 KK	 	o 
	>FAsJ$S> t4 q5<<QUAlKDq5<<AE
D+FD!!$q!Q0P$2P2P0PRqTXTqTqRq'q"rst uyy<=
	> ii+Aq!^m^]l],RS6MC((r$   r)  sample_posterior	generatorc                     |}| j                  |      j                  }|r|j                  |      }n|j                         }| j	                  ||      }|S )z
        Args:
            sample (`torch.Tensor`): Input sample.
            return_dict (`bool`, *optional*, defaults to `True`):
                Whether or not to return a [`DecoderOutput`] instead of a plain tuple.
        )rQ  r%  )r"  r  r)  rV   r3  )	r!   r)  rP  r  rQ  r2   r!  r#  rO  s	            r#   r1   zAutoencoderKLQwenImage.forward  sU     KKN..	  9 5A Akk!k5
r$   )NNNN)r   N)T)FTN)$r5   r6   r7   r8    _supports_gradient_checkpointingr	   r9   r   r   rR   rN   r   r   r   r   r  r  r  r,   Tensorr  r   r   r   r   r"  r.  r   r3  r:  r<  r  r*  	Generatorr1   r:   r;   s   @r#   r   r     s    (-$  +#%*= %o $d8
8
 8
 *	8

 8
 %[8
 "$Z8
 8
 5k8
 %[8
 
8
 8
x 15/35948b (b  (}b $,E?	b
 #+5/b 
b<  !9  0 37::,0:	"E*F$GG	H: :4) )D )2 - -4 -5X]XdXdIdCe - -0 %,, c ell  %,, c ell @ell @/B @D=)ell =) =)}^c^j^jOjIk =)D "' /3  	
 EOO, 
}ell*	+r$   r   )0typingr   r   r   r   r,   torch.nnrD   torch.nn.functional
functionalr/   torch.utils.checkpointconfiguration_utilsr   r	   loadersr
   utilsr   utils.accelerate_utilsr   activationsr   modeling_outputsr   modeling_utilsr   vaer   r   
get_loggerr5   loggerrh   Conv3dr   Moduler=   UpsamplerP   rU   rz   r   r   r   r   r   r    r$   r#   <module>ri     s  * 0 /      B -  8 ( 2 ' < 
		H	%
*"BII *"Zk		 k45 5T		 TnGRYY GT*bii *Z$		 $Nh hVBryy BJr rjSZ6L Sr$   