
    bi                     L   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jD                        Z$ G d dejJ                        Z& G d dejD                        Z' G d dejP                        Z) G d dejD                        Z* G d dejD                        Z+ G d dejD                        Z, G d dejD                        Z- G d  d!ejD                        Z. G d" d#ejD                        Z/ G d$ d%ejD                        Z0 G d& d'ejD                        Z1 G d( d)ejD                        Z2d* Z3d+ Z4 G d, d-eee      Z5y).    )ListOptionalTupleUnionN   )ConfigMixinregister_to_config)FromOriginalModelMixin)logging)apply_forward_hook   )get_activation)AutoencoderKLOutput)
ModelMixin   )DecoderOutputDiagonalGaussianDistributionc                   Z     e Zd Z	 d fd	Zdej
                  dej
                  fdZ xZS )	AvgDown3Dc                    t         |           || _        || _        || _        || _        | j                  | j
                  z  | j
                  z  | _        || j                  z  |z  dk(  sJ || j                  z  |z  | _        y Nr   )super__init__in_channelsout_channelsfactor_tfactor_sfactor
group_sizeselfr   r   r   r   	__class__s        k/home/cdr/jupyterlab/.venv/lib/python3.12/site-packages/diffusers/models/autoencoders/autoencoder_kl_wan.pyr   zAvgDown3D.__init__&   s|     	&(  mmdmm3dmmCT[[(<71<<<%3|C    xreturnc           
      0   | j                   |j                  d   | j                   z  z
  | j                   z  }dddd|df}t        j                  ||      }|j                  \  }}}}}|j	                  |||| j                   z  | j                   || j
                  z  | j
                  || j
                  z  | j
                        }|j                  dddddddd      j                         }|j	                  ||| j                  z  || j                   z  || j
                  z  || j
                  z        }|j	                  || j                  | j                  || j                   z  || j
                  z  || j
                  z        }|j                  d	      }|S )
Nr   r   r   r               dim)r   shapeFpadviewr   permute
contiguousr   r   r   mean)	r!   r%   pad_tr0   BCTHWs	            r#   forwardzAvgDown3D.forward7   so   dmm!;;t}}L!Q5!$EE!SM1aAFFMMMMMM	
 IIaAq!Q1-88:FFO
 FFOO
 FFqFMr$   r   )__name__
__module____qualname__r   torchTensorr;   __classcell__r"   s   @r#   r   r   %   s)     D"   %,,  r$   r   c                   f     e Zd Z	 ddedef fdZddej                  dej                  fdZ xZS )	DupUp3Dr   r   c                    t         |           || _        || _        || _        || _        | j                  | j
                  z  | j
                  z  | _        || j                  z  |z  dk(  sJ || j                  z  |z  | _        y r   )r   r   r   r   r   r   r   repeatsr    s        r#   r   zDupUp3D.__init__[   s|     	&(  mmdmm3dmmCdkk)K71<<<#dkk1[@r$   r%   r&   c                    |j                  | j                  d      }|j                  |j                  d      | j                  | j
                  | j                  | j                  |j                  d      |j                  d      |j                  d            }|j                  ddddddd	d      j                         }|j                  |j                  d      | j                  |j                  d      | j
                  z  |j                  d      | j                  z  |j                  d      | j                  z        }|r!|d d d d | j
                  dz
  d d d d d f   }|S )
Nr   r,   r   r   r   r*   r(   r+   r)   )	repeat_interleaverG   r1   sizer   r   r   r2   r3   )r!   r%   first_chunks      r#   r;   zDupUp3D.forwardm   s#   !4FFFF1IMMMMMMFF1IFF1IFF1I	
 IIaAq!Q1-88:FFFF1IFF1I%FF1I%FF1I%
 !Q)+Q12Ar$   r<   )F)	r=   r>   r?   intr   r@   rA   r;   rB   rC   s   @r#   rE   rE   Z   s=     AA A$ U\\ r$   rE   c                        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 )WanCausalConv3dau  
    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
    r   r   kernel_sizestridepaddingr&   Nc                     t         |   |||||       | j                  d   | j                  d   | j                  d   | j                  d   d| j                  d   z  df| _        d| _        y )N)r   r   rO   rP   rQ   r   r   r   r   r   r   )r   r   rQ   _padding)r!   r   r   rO   rP   rQ   r"   s         r#   r   zWanCausalConv3d.__init__   sx     	#%# 	 	
 a$,,q/4<<?DLLYZO]^aeamamnoap]prst r$   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 )Nr*   r   r   r,   )listrT   todevicer@   catr.   r/   r0   r   r;   )r!   r%   cache_xrQ   r"   s       r#   r;   zWanCausalConv3d.forward   s    t}}%4==#3a#7jj*G		7A,A.AAJ'--**JEE!Wwq!!r$   )r   r   N)
r=   r>   r?   __doc__rL   r   r   r   r;   rB   rC   s   @r#   rN   rN      s    & 4545!! ! 3c3m 445	!
 c5c3//0! sE#sC-001! 
!(" "r$   rN   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 )WanRMS_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zerosra   )r!   r-   r_   r`   ra   broadcastable_dimsr.   r"   s          r#   r   zWanRMS_norm.__init__   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_   rd   rh   ra   )r!   r%   s     r#   r;   zWanRMS_norm.forward   s>    {{1(:(:1DtzzQTXT^T^^aeajajjjr$   TTF)	r=   r>   r?   r\   rL   boolr   r;   rB   rC   s   @r#   r^   r^      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 )WanUpsamplea   
    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 r[   )r   r;   floattype_as)r!   r%   r"   s     r#   r;   zWanUpsample.forward   s#    wqwwy)11!44r$   )r=   r>   r?   r\   r;   rB   rC   s   @r#   rq   rq      s    5 5r$   rq   c            	       D     e Zd ZdZd
dedededdf fdZddgfd	Z xZS )WanResampleax  
    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.
    Nr-   modeupsample_out_dimr&   c           	         t         |           || _        || _        ||dz  }|dk(  r>t	        j
                  t        dd      t	        j                  ||dd            | _        y |d	k(  rUt	        j
                  t        dd      t	        j                  ||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 )Nr   
upsample2d)       @r{   znearest-exact)scale_factorrw   r   r   rQ   
upsample3d)r   r   r   )r   r   r   downsample2d)r   r   r   r   )r   r   )rP   downsample3d)r   r   r   rS   )rP   rQ   )r   r   r-   rw   re   
Sequentialrq   Conv2dresamplerN   	time_conv	ZeroPad2dIdentity)r!   r-   rw   rx   r"   s       r#   r   zWanResample.__init__   sD   	 #"ax <MM/J		#/A>DM \!MM/J		#/A>DM -S#'9iXDN^#MM",,|*DbiiPSUXZ[djFklDM^#MM",,|*DbiiPSUXZ[djFklDM,S#y\efDN 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   rl   r,   r   r*   r   )rJ   rw   CACHE_Tcloner.   r@   rY   	unsqueezerW   rX   
zeros_liker   reshapestackr2   r   r1   )r!   r%   
feat_cachefeat_idxbcthwidxrZ   s              r#   r;   zWanResample.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$   r[   )	r=   r>   r?   r\   rL   strr   r;   rB   rC   s   @r#   rv   rv      s7    *C *s *c *T *> %)A3 +r$   rv   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 )WanResidualBlockaE  
    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^   norm1rN   conv1norm2re   Dropoutr   conv2r   conv_shortcut)r!   r   r   r   r   r"   s        r#   r   zWanResidualBlock.__init__B  s     	*=9 !6
$VWaC
 7
zz'*$Wgq!D
DJgDU_VWa@[][f[f[h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   rl   r,   r   )r   r   r   r   r   r.   r@   rY   r   rW   rX   r   r   r   r   )r!   r%   r   r   r   r   rZ   s          r#   r;   zWanResidualBlock.forwardV  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$   )rc   silu
r=   r>   r?   r\   rL   rs   r   r   r;   rB   rC   s   @r#   r   r   7  sY     #ii i 	i
 i 
i( %)A3 (r$   r   c                   (     e Zd ZdZ fdZd Z xZS )WanAttentionBlockz}
    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^   normre   r   to_qkvproj)r!   r-   r"   s     r#   r   zWanAttentionBlock.__init__  sO      $	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*   rl   r,   )rJ   r2   r   r   r   r3   chunkr/   scaled_dot_product_attentionsqueezer   r1   )r!   r%   identity
batch_sizechannelstimeheightwidthqkvqkvs               r#   r;   zWanAttentionBlock.forward  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$   )r=   r>   r?   r\   r   r;   rB   rC   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 )WanMidBlockz
    Middle block for WanVAE 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-   r   rangeappendr   re   
ModuleList
attentionsresnetsgradient_checkpointing)	r!   r-   r   r   r   r   r   _r"   s	           r#   r   zWanMidBlock.__init__  s     $Cg}EF
z" 	OA/45NN+Cg}MN	O --
3}}W-&+#r$   Nr   c                      | j                   d   |||      }t        | j                  | j                   dd        D ]  \  }}| ||      } ||||      } |S )Nr   r   )r   zipr   )r!   r%   r   r   attnresnets         r#   r;   zWanMidBlock.forward  si    DLLOAz84  ab1AB 	0LD&Gq*h/A		0 r$   )rc   r   r   r   rC   s   @r#   r   r     s8    ,C ,% ,c ,`c , %)A3 r$   r   c                   .     e Zd Zd fd	ZddgfdZ xZS )WanResidualDownBlockc                 2   t         
|           t        |||rdnd|rdnd      | _        g }t	        |      D ]   }|j                  t        |||             |}" t        j                  |      | _	        |r|rdnd}	t        ||	      | _        y d | _        y )Nr   r   r   r   r   r   rw   )r   r   r   avg_shortcutr   r   r   re   r   r   rv   downsampler)r!   r   r   r   num_res_blockstemperal_downsample	down_flagr   r   rw   r"   s             r#   r   zWanResidualDownBlock.__init__  s     &-Q1#Q	
 ~& 	ANN+FGWEFF	 }}W- %8>nD*7>D#Dr$   Nr   c                     |j                         }| j                  D ]  } ||||      } | j                  | j                  |||      }|| j                  |      z   S r[   )r   r   r   r   )r!   r%   r   r   x_copyr   s         r#   r;   zWanResidualDownBlock.forward  sd    ll 	0Fq*h/A	0'  J9A4$$V,,,r$   )FF)r=   r>   r?   r   r;   rB   rC   s   @r#   r   r     s    $2 %)A3 -r$   r   c            
       \     e Zd ZdZdddg ddg g ddd	d
f
dededef fdZddgfdZ xZ	S )WanEncoder3dao  
    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*   r   rn   rc   r   Fr   r   is_residualc                    t         |           || _        || _        || _        || _        || _        || _        t        |	      | _	        dg|z   D cg c]  }||z  	 }}d}t        ||d   dd      | _        t        j                  g       | _        t        t!        |d d |dd              D ]  \  }\  }}|
rP| j                  j#                  t%        |||||t'        |      dz
  k7  r||   nd|t'        |      dz
  k7               \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  } t1        ||	d      | _        t5        |d      | _        t        ||dd      | _        d| _        y c c}w )Nr         ?r   r   r}   rl   F)r   r   r   r   r   r{   r   r   )r   r   r-   z_dimdim_multr   attn_scalesr   r   r   rN   conv_inre   r   down_blocks	enumerater   r   r   lenr   r   r   rv   r   	mid_blockr^   norm_outconv_outr   )r!   r   r-   r   r   r   r   r   r   r   r   udimsrd   ir   r   r   rw   r"   s                      r#   r   zWanEncoder3d.__init__  s    	
 ,&#6 *=9 #$x0Aa00 '{DGQJ ==,$-c$s)T!"X.F$G 	! A   ''(&FG3x=[\K\F\,?,Bbg"#s8}q'8"8	 ~. %A$$++,<VWg,VW+((//0A'0JK$F	% H))-@-C>D$$++Kd,KLSLE1	!6 %Wg}QRS $GE:'1E&+#S 1s   G5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   )r   r   r.   r@   rY   r   rW   rX   r   r   r   r   r   r   )r!   r%   r   r   r   rZ   layers          r#   r;   zWanEncoder3d.forwardJ  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$   )
r=   r>   r?   r\   rL   r   ro   r   r;   rB   rC   s   @r#   r   r     s\      /#!@,@, @, @,D %)A3 %r$   r   c                   Z     e Zd ZdZ	 	 	 	 ddedededededed	ef fd
ZddgdfdZ	 xZ
S )WanResidualUpBlocka  
    A block that handles upsampling for the WanVAE decoder.

    Args:
        in_dim (int): Input dimension
        out_dim (int): Output dimension
        num_res_blocks (int): Number of residual blocks
        dropout (float): Dropout rate
        temperal_upsample (bool): Whether to upsample on temporal dimension
        up_flag (bool): Whether to upsample or not
        non_linearity (str): Type of non-linearity to use
    Fr   r   r   r   temperal_upsampleup_flagr   c           	         t         |           || _        || _        |rt	        |||rdndd      | _        nd | _        g }|}	t        |dz         D ]!  }
|j                  t        |	|||             |}	# t        j                  |      | _        |r!|rdnd}t        |||      | _        d| _        y d | _        d| _        y )Nr   r   r   r~   rz   )rw   rx   F)r   r   r   r   rE   r   r   r   r   re   r   r   rv   	upsamplerr   )r!   r   r   r   r   r   r   r   r   current_dimr   upsample_moder"   s               r#   r   zWanResidualUpBlock.__init__  s     	 '/Q	!D !%D ~)* 	"ANN+K'=YZ!K	" }}W- ,=L<M(}W^_DN ',# "DN&+#r$   Nr   c                    |j                         }| j                  D ]  }| ||||      } ||      } | j                  '|| j                  |||      }n| j                  |      }| j                  || j                  ||      z   }|S )I  
        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
        rK   )r   r   r   r   )r!   r%   r   r   rK   r   r   s          r#   r;   zWanResidualUpBlock.forward  s     ll 	F%1j(31I		 >>%%NN1j(;NN1%(D%%f+%FFAr$   )rc   FFr   )r=   r>   r?   r\   rL   rs   ro   r   r   r;   rB   rC   s   @r#   r   r   r  sp    $ "'#(,(, (, 	(,
 (,  (, (, (,T %)A3E r$   r   c                   Z     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dfdZ	 xZ
S )
WanUpBlocka  
    A block that handles upsampling for the WanVAE 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   r   r   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   r   re   r   r   
upsamplersrv   r   )r!   r   r   r   r   r   r   r   r   r   r"   s             r#   r   zWanUpBlock.__init__  s     	 ~)* 	"ANN+K'=YZ!K	" }}W- $ mm[}-U,VWDO&+#r$   r   c                     | j                   D ]  }| ||||      } ||      } | j                  0| | j                  d   |||      }|S  | j                  d   |      }|S )r   r   )r   r   )r!   r%   r   r   rK   r   s         r#   r;   zWanUpBlock.forward  s     ll 	F%1j(31I		 ??&%&DOOA&q*h?  'DOOA&q)r$   )rc   Nr   )r=   r>   r?   r\   rL   rs   r   r   r   r;   rB   rC   s   @r#   r   r     sf    
" '+#,, , 	,
 ,  }, ,< %)A3D r$   r   c            
       ^     e Zd ZdZddg ddg g dddd	d
f
dededef fdZddgd
fdZ xZ	S )WanDecoder3dak  
    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   FTTrc   r   r   Fr   r   r   c           
         t         |           || _        || _        || _        || _        || _        || _        t        |      | _	        |d   g|d d d   z   D cg c]  }||z  	 }}t        ||d   dd      | _        t        |d   ||d      | _        t        j                  g       | _        t#        t%        |d d |dd              D ]}  \  }\  }}|dkD  r|
s|dz  }|t'        |      dz
  k7  }d }|r||   rd}n|rd	}|
rt)        |||||r||   nd
||      }nt+        ||||||      }| j                   j-                  |        t/        d
      | _        t        ||	dd      | _        d
| _        y c c}w )Nrl   r   r   r   r}   r   r   r~   rz   F)r   r   r   r   r   r   r   )r   r   r   r   r   r   r   )r   r   r-   r   r   r   r   r   r   r   rN   r   r   r   re   r   	up_blocksr   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   up_blockr"   s                      r#   r   zWanDecoder3d.__init__  s    	
 ,&!2*=9 #+2,(4R4.!@AAaAA 'ud1gq!D %T!Wg}QRS r*$-c$s)T!"X.F$G "	, A 1u[1 3x=1,,G M,Q/ , ,-!##1#>E&7&:5#"/ &!##1#"/"/ NN!!(+E"	,J $GE:'q!L&+#e Bs   E: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 )Nr   r   rl   r,   r   r   )r   r   r.   r@   rY   r   rW   rX   r   r   r  r   r   r   )r!   r%   r   r   rK   r   rZ   r  s           r#   r;   zWanDecoder3d.forwardj  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  	KHJkJA	K 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>   r?   r\   r   rL   ro   r   r;   rB   rC   s   @r#   r  r    s`      -#!J, J, J, J,X %)A3E #r$   r  c           	         |dk(  r| S | j                         dk7  rt        d| j                         | j                  \  }}}}}||z  dk7  s||z  dk7  rt        d| d| d| d      | j                  |||||z  |||z  |      } | j	                  ddd	d
ddd      j                         } | j                  |||z  |z  |||z  ||z        } | S )Nr   r(   Invalid input shape: r   zHeight (z) and width (z#) must be divisible by patch_size ()r+   r*   r   r   r-   
ValueErrorr.   r1   r2   r3   )r%   
patch_sizer   r   framesr   r   s          r#   patchifyr    s   Quuw!|0	:;;23''/J&&% 
a5:#5#:8F8=?bcmbnnopqq 	
z8VVz-A:uXbObdnoA 	
		!Q1aA&113A	z8j0:=vvQ[G[]bfp]pqAHr$   c           	      L   |dk(  r| S | j                         dk7  rt        d| j                         | j                  \  }}}}}|||z  z  }| j                  |||||||      } | j	                  ddddddd      j                         } | j                  |||||z  ||z        } | S )	Nr   r(   r	  r   r*   r   r+   r   r  )r%   r  r   	c_patchesr  r   r   r   s           r#   
unpatchifyr    s    Quuw!|0	:;;34770J	665Z*45H 	
z8ZVVUSA 	
		!Q1aA&113A	z8VVj-@%*BTUAHr$   c            $           e Zd ZdZdZedddg ddg g dd	g d
g dddddddfdedee   dedee   dede	e
   de	e   de
de	e
   de	e
   dedededee   dee   dee   ddf" fd        Z	 	 	 	 d<d!ee   d"ee   d#ee
   d$ee
   ddf
d%Zd=d&Zd=d'Zd=d(Zd) Zd*ej&                  fd+Ze	 d>d*ej&                  d,edeeee   f   fd-       Zd>d.ej&                  d,efd/Zed>d.ej&                  d,edeeej&                  f   fd0       Zd1ej&                  d2ej&                  d3edej&                  fd4Zd1ej&                  d2ej&                  d3edej&                  fd5Zd*ej&                  defd6Zd>d.ej&                  d,edeeej&                  f   fd7Z 	 	 	 d?d8ej&                  d9ed,ed:eejB                     deeej&                  f   f
d;Z" xZ#S )@AutoencoderKLWana;  
    A VAE model with KL loss for encoding videos into latents and decoding latent representations into videos.
    Introduced in [Wan 2.1].

    This model inherits from [`ModelMixin`]. Check the superclass documentation for it's generic methods implemented
    for all models (such as downloading or saving).
    F`   N   r   r   r  rc   )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-?r   r*      base_dimdecoder_base_dimr   r   r   r   r   r   latents_meanlatents_stdr   r   r   r  scale_factor_temporalscale_factor_spatialr&   c                    t         |           || _        || _        |d d d   | _        ||}t        |||dz  ||||||	      | _        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 )Nrl   r   )	r   r-   r   r   r   r   r   r   r   r   )	r-   r   r   r   r   r   r   r   r   F      c              3   <   K   | ]  }t        |t                y wr[   
isinstancerN   .0ms     r#   	<genexpr>z,AutoencoderKLWan.__init__.<locals>.<genexpr>4       Za:a9Z   r   c              3   <   K   | ]  }t        |t                y wr[   r"  r$  s     r#   r'  z,AutoencoderKLWan.__init__.<locals>.<genexpr>7  r(  r)  )decoderencoder)r   r   r   r   r   r   r,  rN   
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  r   r   r   r  r  r  r"   s                    r#   r   zAutoencoderKLWan.__init__  sq   l 	
#6 !4TrT!:#'##!))# 3#

 *%!)UQYB.ueQ?# )#"44%#

 *+c$2J2J.K)K& !
   '*#%(" *-&(+%
 ||' Z4<<CWCWCYZZ||' Z4<<CWCWCYZZ$
 r$   r2  r3  r4  r5  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)r1  r2  r3  r4  r5  )r!   r2  r3  r4  r5  s        r#   enable_tilingzAutoencoderKLWan.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)r1  r!   s    r#   disable_tilingzAutoencoderKLWan.disable_tilingZ  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r0  r<  s    r#   enable_slicingzAutoencoderKLWan.enable_slicinga  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 AutoencoderKLWan.disable_slicingh  s    
 !r$   c                     | j                   d   | _        dg| _        d g| j                  z  | _        | j                   d   | _        dg| _        d g| j                  z  | _        y )Nr+  r   r,  )r8  	_conv_num	_conv_idx	_feat_map_enc_conv_num_enc_conv_idx_enc_feat_mapr<  s    r#   clear_cachezAutoencoderKLWan.clear_cacheo  sa    11)<$..0!55i@S"Vd&8&88r$   r%   c           
         |j                   \  }}}}}| j                  r/|| j                  kD  s|| j                  kD  r| j	                  |      S | j                          | j                  j                  !t        || j                  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 )Nr  r   r*   r   r   r   r   )r.   r1  r3  r2  tiled_encoderJ  configr  r  r   rH  r,  rI  r@   rY   r-  )r!   r%   r   	num_framer   r   iter_r   outout_encs              r#   _encodezAutoencoderKLWan._encodey  sm   )*&1i??(B(B BftOjOjFj$$Q'';;!!-t{{'='=>A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)r0  r.   splitrU  r@   rY   r   r   )r!   r%   rV  x_sliceencoded_slicesr   	posteriors          r#   encodezAutoencoderKLWan.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                  d      }O| j                  |	d d d d |
|
dz   d d d d f   | j                  | j                        }t        j                  |gd      } | j                  j                  !t!        | j                  j                        }t        j"                  d	d
      }| j                          |s|fS t%        |      S )NrV  r   r   T)r   r   rK   rM  r   rL  g      r   )minmaxsample)r.   r2  r/  r3  r1  tiled_decoderJ  r.  r   rE  r+  rF  r@   rY   rO  r  r  clampr   )r!   r^  rV  r   rP  r   r   tile_latent_min_heighttile_latent_min_widthr%   r   rR  rS  s                r#   _decodezAutoencoderKLWan._decode  s   )*&1i!%!<!<@^@^!^ $ : :d>\>\ \??(= =J`A`$$QK$@@  #y! 	0ASDNAvllaAAIq!+,RVR`R`nr #  ||AaAAIq!&;$<bfbpbp|qiidQ/	0 ;;!!-ST[[-C-CDC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   rc  )r0  r.   rY  ri  rd  r@   rY   r   )r!   r^  rV  z_slicedecoded_slicesdecodeds         r#   decodezAutoencoderKLWan.decode  s     
QJK''RS*Uwdll73::UNUii/Gll1o,,G:G,, Vs   "Bar   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   ra  r.   r   )r!   ro  r   rp  ys        r#   blend_vzAutoencoderKLWan.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 )Nrl   r   rs  )r!   ro  r   rp  r%   s        r#   blend_hzAutoencoderKLWan.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*   NrM  r   r,   rl   r   )r.   r/  r2  r3  r4  r5  r   rJ  rH  r,  rI  r-  r   r@   rY   r   ru  rw  )r!   r%   r   
num_framesr   r   latent_heightlatent_widthrg  rh  tile_latent_stride_heighttile_latent_stride_widthblend_heightblend_widthrowsr   rowjr   frame_ranger   tileresult_rows
result_rowrT  s                            r#   rN  zAutoencoderKLWan.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   rM  r   r,   rl   r   rc  )r.   r/  r2  r3  r4  r5  r   rJ  rE  r.  r+  rF  r   r@   rY   r   ru  rw  r   )r!   r^  rV  r   ry  r   r   sample_heightsample_widthrg  rh  r|  r}  r~  r  r  r   r  r  r   r   r  rm  r  r  decs                             r#   re  zAutoencoderKLWan.tiled_decode8  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$   rd  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.
        )r  r`  )r]  rX  rd  rw   rn  )	r!   rd  r  rV  r  r%   r\  r^  r  s	            r#   r;   zAutoencoderKLWan.forwardw  sU     KKN..	  9 5A Akk!k5
r$   )NNNN)r&   N)T)FTN)$r=   r>   r?   r\    _supports_gradient_checkpointingr	   rL   r   r   r   rs   ro   r   r:  r=  r@  rB  rJ  r@   rA   rU  r   r   r   r   r]  ri  r   rn  ru  rw  rN  re  	Generatorr;   rB   rC   s   @r#   r  r    s`    (-$ *.+#%*=%
$$
$ "$(/0./gs
s
 #3-s
 	s

 *s
 s
 %[s
 "$Zs
 s
 5ks
8 %[9s
\ ]s
^ _s
` as
b SMcs
d  (}es
f 'smgs
h 
is
 s
n 15/35948b (b  (}b $,E?	b
 #+5/b 
b<  !9 4 37::,0:	"E*F$GG	H: :4) )D )> - -4 -5X]XdXdIdCe - -0 %,, c ell  %,, c ell @ell @/B @D=)ell =) =)}^c^j^jOjIk =)D "' /3  	
 EOO, 
}ell*	+r$   r  )6typingr   r   r   r   r@   torch.nnre   torch.nn.functional
functionalr/   torch.utils.checkpointconfiguration_utilsr   r	   loadersr
   utilsr   utils.accelerate_utilsr   activationsr   modeling_outputsr   modeling_utilsr   vaer   r   
get_loggerr=   loggerr   Moduler   rE   Conv3drN   r^   Upsamplerq   rv   r   r   r   r   r   r   r   r  r  r  r   r$   r#   <module>r     sd   0 /      B -  8 ( 2 ' < 
		H	%
2		 2j)bii )X*"bii *"Zk")) k45"++ 5X")) XvGryy GT*		 *Z$")) $N!-299 !-Hv299 vrU UpB BJ~299 ~B.(Pz;0F Pr$   