
    bi۶                     <   d dl Z d dlmZmZmZmZ d dlZd dlmZ ddl	m
Z
mZ ddlmZ ddlmZ ddlmZ dd	lmZmZ 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  G d dejB                        Z" G d dejB                        Z# G d dejB                        Z$ G d dejB                        Z% G d dejB                        Z& G d dejB                        Z' G d dejB                        Z( G d dejB                        Z) G d d ee
      Z*y)!    N)DictOptionalTupleUnion   )ConfigMixinregister_to_config)logging)apply_forward_hook   )get_activation)	AttentionMochiVaeAttnProcessor2_0)AutoencoderKLOutput)
ModelMixin   )CogVideoXCausalConv3d)DecoderOutputDiagonalGaussianDistributionc            	       v     e Zd ZdZ	 	 	 d
dedededef fdZddej                  dej                  fd	Z	 xZ
S )MochiChunkedGroupNorm3Da  
    Applies per-frame group normalization for 5D video inputs. It also supports memory-efficient chunked group
    normalization.

    Args:
        num_channels (int): Number of channels expected in input
        num_groups (int, optional): Number of groups to separate the channels into. Default: 32
        affine (bool, optional): If True, this module has learnable affine parameters. Default: True
        chunk_size (int, optional): Size of each chunk for processing. Default: 8

    num_channels
num_groupsaffine
chunk_sizec                 j    t         |           t        j                  |||      | _        || _        y )N)r   r   r   )super__init__nn	GroupNorm
norm_layerr   )selfr   r   r   r   	__class__s        m/home/cdr/jupyterlab/.venv/lib/python3.12/site-packages/diffusers/models/autoencoders/autoencoder_kl_mochi.pyr   z MochiChunkedGroupNorm3D.__init__1   s,     	,,LZ`fg$    xreturnc                 h   |j                  d      }|j                  ddddd      j                  dd      }t        j                  |j                  | j                  d      D cg c]  }| j                  |       c}d      }|j                  d|df      j                  ddddd      }|S c c}w )Nr   r   r   r      dim)	sizepermuteflattentorchcatsplitr   r!   	unflatten)r"   r&   
batch_sizechunkoutputs        r$   forwardzMochiChunkedGroupNorm3D.forward<   s    VVAY
IIaAq!$,,Q2]^@_`uDOOE2`fgh!!!j"%56>>q!Q1M as   %B/)    T   N)__name__
__module____qualname____doc__intboolr   r0   Tensorr7   __classcell__r#   s   @r$   r   r   $   sY    
 	%	% 	% 		%
 	%  r%   r   c                        e Zd ZdZ	 	 d
dedee   def fdZ	 ddej                  dee
eej                  f      dej                  fd	Z xZS )MochiResnetBlock3DaU  
    A 3D ResNet block used in the Mochi model.

    Args:
        in_channels (`int`):
            Number of input channels.
        out_channels (`int`, *optional*):
            Number of output channels. If None, defaults to `in_channels`.
        non_linearity (`str`, defaults to `"swish"`):
            Activation function to use.
    in_channelsout_channelsact_fnc                    t         |           |xs |}|| _        || _        t	        |      | _        t        |      | _        t        ||ddd      | _	        t        |      | _
        t        ||ddd      | _        y )Nr   r   r   	replicaterF   rG   kernel_sizestridepad_mode)r   r   rF   rG   r   nonlinearityr   norm1r   conv1norm2conv2)r"   rF   rG   rH   r#   s       r$   r   zMochiResnetBlock3D.__init__S   s     	#2{&(*62,+F
*#,AVWbm

 -,G
*$<QWXcn

r%   inputs
conv_cacher'   c                 P   i }|xs i }|}| j                  |      }| j                  |      }| j                  ||j                  d            \  }|d<   | j	                  |      }| j                  |      }| j                  ||j                  d            \  }|d<   ||z   }||fS )NrR   rV   rT   )rQ   rP   rR   getrS   rT   )r"   rU   rV   new_conv_cachehidden_statess        r$   r7   zMochiResnetBlock3D.forwardj   s    
 %2


=1))-815MV`VdVdelVm1n.~g.

=1))-815MV`VdVdelVm1n.~g.%.n,,r%   )Nswishr:   )r;   r<   r=   r>   r?   r   strr   r0   rA   r   r7   rB   rC   s   @r$   rE   rE   F   sv    
 '+	

 sm
 	
4 9=-- T#u||"345- 
	-r%   rE   c                        e Zd ZdZ	 	 	 	 ddedededededef fdZ	 	 dd	ej                  d
e	e
eej                  f      dedej                  fdZ xZS )MochiDownBlock3Da  
    An downsampling block used in the Mochi model.

    Args:
        in_channels (`int`):
            Number of input channels.
        out_channels (`int`, *optional*):
            Number of output channels. If None, defaults to `in_channels`.
        num_layers (`int`, defaults to `1`):
            Number of resnet blocks in the block.
        temporal_expansion (`int`, defaults to `2`):
            Temporal expansion factor.
        spatial_expansion (`int`, defaults to `2`):
            Spatial expansion factor.
    rF   rG   
num_layerstemporal_expansionspatial_expansionadd_attentionc                 V   t         |           || _        || _        t	        |||||f|||fd      | _        g }g }g }	t        |      D ]  }
|j                  t        |             |rG|j                  t        |             |	j                  t        ||dz  dddt                            g|j                  d        |	j                  d         t        j                  |      | _        t        j                  |      | _        t        j                  |	      | _        d	| _        y )
NrK   rL   rF   rJ   r8   l2T	query_dimheadsdim_headqk_norm	is_causal	processorF)r   r   ra   rb   r   conv_inrangeappendrE   r   r   r   r   
ModuleListresnetsnorms
attentionsgradient_checkpointing)r"   rF   rG   r`   ra   rb   rc   rr   rs   rt   _r#   s              r$   r   zMochiDownBlock3D.__init__   s    	"4!2,#%+->@QR&(9;LM 
 
z" 	(ANN-,GH4,OP!!".*b0!# $"&":"<	 T"!!$'!	($ }}W-]]5)
--
3&+#r%   r[   rV   r   r'   c                    i }|xs i }| j                  |      \  }|d<   t        t        | j                  | j                  | j
                              D ]l  \  }\  }}}d| }	t        j                         r5| j                  r)| j                  |||j                  |	            \  }||	<   n |||j                  |	            \  }||	<   |{|}
 ||      }|j                  \  }}}}}|j                  ddddd      j                  dd      j                         }|j                  d      |k  r	 ||      }nYg }t!        d|j                  d      |      D ]#  }||||z    } ||      }|j#                  |       % t        j$                  |      }|j'                  d|||f      j                  ddddd      }|
|z   }o ||fS )	-Forward method of the `MochiUpBlock3D` class.rn   resnet_rX   r   r   r)   r   r   )rn   	enumerateziprr   rs   rt   r0   is_grad_enabledru   _gradient_checkpointing_funcrY   shaper.   r/   
contiguousr-   ro   rp   r1   r3   )r"   r[   rV   r   rZ   iresnetnormattnconv_cache_keyresidualr4   r   
num_framesheightwidthhidden_states_chunkshidden_states_chunks                     r$   r7   zMochiDownBlock3D.forward   s    %2
37<<3N0~i0'0T\\4::t1_'` #	9#A#d&qc]N$$&4+F+F@D@a@a!NN>2A=~n= AG!jnn^.LA=~n= ( $] 3FSFYFYC
L*fe - 5 5aAq! D L LQPQ R ] ] _ !%%a(J6$($7M+-("1m&8&8&;ZH I.;AJ.O+.23F.G+,334GHI %*II.B$CM - 7 7JPU;V W _ _`acdfgijlm n (= 8G#	9J n,,r%   )r   r   r   T)Ni   r;   r<   r=   r>   r?   r@   r   r0   rA   r   r   r]   r7   rB   rC   s   @r$   r_   r_      s    ( "#!"".,., ., 	.,
  ., ., .,f 9=	2-||2- T#u||"3452- 	2-
 
2-r%   r_   c                        e Zd ZdZ	 	 d
dededef fdZ	 ddej                  de	e
eej                  f      dej                  fd	Z xZS )MochiMidBlock3Dz
    A middle block used in the Mochi model.

    Args:
        in_channels (`int`):
            Number of input channels.
        num_layers (`int`, defaults to `3`):
            Number of resnet blocks in the block.
    rF   r`   rc   c                    t         |           g }g }g }t        |      D ]  }|j                  t	        |             |rG|j                  t        |             |j                  t        ||dz  dddt                            g|j                  d        |j                  d         t        j                  |      | _
        t        j                  |      | _        t        j                  |      | _        d| _        y )Nre   rJ   r8   rf   Trg   F)r   r   ro   rp   rE   r   r   r   r   rq   rr   rs   rt   ru   )	r"   rF   r`   rc   rr   rs   rt   rv   r#   s	           r$   r   zMochiMidBlock3D.__init__  s     	
z" 	(ANN-+FG4+NO!!"-)R/!# $"&":"<	 T"!!$'#	(& }}W-]]5)
--
3&+#r%   r[   rV   r'   c                    i }|xs i }t        t        | j                  | j                  | j                              D ]  \  }\  }}}d| }t        j                         r5| j                  r)| j                  |||j                  |            \  }||<   n |||j                  |            \  }||<   |z|}	 ||      }|j                  \  }
}}}}|j                  ddddd      j                  dd      j                         } ||      }|j                  d|
||f      j                  ddddd      }|	|z   } ||fS )z.Forward method of the `MochiMidBlock3D` class.ry   rX   r   r   r)   r   r   )rz   r{   rr   rs   rt   r0   r|   ru   r}   rY   r~   r.   r/   r   r3   )r"   r[   rV   rZ   r   r   r   r   r   r   r4   r   r   r   r   s                  r$   r7   zMochiMidBlock3D.forward&  sh    %2
'0T\\4::t1_'` 	9#A#d&qc]N$$&4+F+F@D@a@aM:>>.+IA=~n= AG!jnn^.LA=~n= ( $] 3FSFYFYC
L*fe - 5 5aAq! D L LQPQ R ] ] _ $] 3 - 7 7JPU;V W _ _`acdfgijlm n (= 8+	9. n,,r%   )r   Tr:   r   rC   s   @r$   r   r      ss     "	#,#, #, 	#,P 9=!-||!- T#u||"345!- 
	!-r%   r   c                        e Zd ZdZ	 	 	 ddededededef
 fdZ	 ddej                  d	ee	e
ej                  f      d
ej                  fdZ xZS )MochiUpBlock3Da  
    An upsampling block used in the Mochi model.

    Args:
        in_channels (`int`):
            Number of input channels.
        out_channels (`int`, *optional*):
            Number of output channels. If None, defaults to `in_channels`.
        num_layers (`int`, defaults to `1`):
            Number of resnet blocks in the block.
        temporal_expansion (`int`, defaults to `2`):
            Temporal expansion factor.
        spatial_expansion (`int`, defaults to `2`):
            Spatial expansion factor.
    rF   rG   r`   ra   rb   c                 "   t         |           || _        || _        g }t	        |      D ]  }|j                  t        |              t        j                  |      | _	        t        j                  |||z  |dz  z        | _        d| _        y )Nre   r   F)r   r   ra   rb   ro   rp   rE   r   rq   rr   Linearprojru   )	r"   rF   rG   r`   ra   rb   rr   rv   r#   s	           r$   r   zMochiUpBlock3D.__init__[  s     	"4!2z" 	HANN-+FG	H}}W-IIk<:L+LO`bcOc+cd	&+#r%   r[   rV   r'   c           
         i }|xs i }t        | j                        D ]r  \  }}d| }t        j                         r5| j                  r)| j                  |||j                  |            \  }||<   T |||j                  |            \  }||<   t |j                  ddddd      }| j                  |      }|j                  ddddd      }|j                  \  }}}	}
}| j                  }| j                  }| j                  }|j                  |d||||	|
|      }|j                  ddd	dd
ddd      j                         }|j                  |d|	|z  |
|z  ||z        }||fS )rx   ry   rX   r   r   r   r)   r   r,            )rz   rr   r0   r|   ru   r}   rY   r.   r   r~   ra   rb   viewr   )r"   r[   rV   rZ   r   r   r   r4   r   r   r   r   stshsws                  r$   r7   zMochiUpBlock3D.forwardp  s    %2
"4<<0 	IAv&qc]N$$&4+F+F@D@a@a!NN>2A=~n= AG!jnn^.LA=~n=	 &--aAq!<		-0%--aAq!<>K>Q>Q;
L*fe$$#### &**:r2r2zSY[`a%--aAq!Q1EPPR%**:r:?FUWKY^acYcdn,,r%   )r   r   r   r:   )r;   r<   r=   r>   r?   r   r0   rA   r   r   r]   r7   rB   rC   s   @r$   r   r   J  s    ( "#!",, , 	,
  , ,0 9=&-||&- T#u||"345&- 
	&-r%   r   c                   f     e Zd Zddededef fdZdej                  dej                  fdZ xZS )	FourierFeaturesstartstopstepc                 L    t         |           || _        || _        || _        y r:   )r   r   r   r   r   )r"   r   r   r   r#   s       r$   r   zFourierFeatures.__init__  s#    
		r%   rU   r'   c                    |j                   }|j                  t        j                        }|j                  d   }| j
                  | j                  z
  | j                  z  }t        j                  | j                  | j
                  | j                  |j                   |j                        }t        j                  d|      dt        j                  z  z  }|j                  |      ddddddf   }|j                  |d|j                  d   |z        }||z  }t        j                  |t        j                  |      t        j                   |      gd      j                  |      S )z.Forward method of the `FourierFeatures` class.r   )dtypedeviceg       @r   N)r+   output_sizer*   )r   tor0   float32r~   r   r   r   aranger   powpirepeatrepeat_interleaver1   sincos)r"   rU   original_dtyper   	num_freqsfreqswhs           r$   r7   zFourierFeatures.forward  s   5==)||AYY+		9	TZZDIIV\\Z`ZgZghIIc5!Q\2HH\"4D$#<= $$1&,,q/I*E % 
 Eyy&%))A,		!=1EHHXXr%   )r   r9   r   )	r;   r<   r=   r?   r   r0   rA   r7   rB   rC   s   @r$   r   r     s;    c S C Yell Yu|| Yr%   r   c                        e Zd ZdZ	 	 	 	 	 	 ddededeedf   deedf   deedf   deedf   d	eedf   d
ef fdZ	 dde	j                  deeee	j                  f      de	j                  fdZ xZS )MochiEncoder3Da  
    The `MochiEncoder3D` layer of a variational autoencoder that encodes input video samples to its latent
    representation.

    Args:
        in_channels (`int`, *optional*):
            The number of input channels.
        out_channels (`int`, *optional*):
            The number of output channels.
        block_out_channels (`Tuple[int, ...]`, *optional*, defaults to `(128, 256, 512, 768)`):
            The number of output channels for each block.
        layers_per_block (`Tuple[int, ...]`, *optional*, defaults to `(3, 3, 4, 6, 3)`):
            The number of resnet blocks for each block.
        temporal_expansions (`Tuple[int, ...]`, *optional*, defaults to `(1, 2, 3)`):
            The temporal expansion factor for each of the up blocks.
        spatial_expansions (`Tuple[int, ...]`, *optional*, defaults to `(2, 2, 2)`):
            The spatial expansion factor for each of the up blocks.
        non_linearity (`str`, *optional*, defaults to `"swish"`):
            The non-linearity to use in the decoder.
    rF   rG   block_out_channels.layers_per_blocktemporal_expansionsspatial_expansionsadd_attention_blockrH   c	                 p   t         |           t        |      | _        t	               | _        t        j                  ||d         | _        t        |d   |d   |d         | _
        g }	t        t        |      dz
        D ]?  }
t        ||
   ||
dz      ||
dz      ||
   ||
   ||
dz            }|	j                  |       A t        j                  |	      | _        t        |d   |d   |d         | _        t%        |d         | _        t        j                  |d   d|z  d      | _        d| _        y )	Nr   rF   r`   rc   r   )rF   rG   r`   ra   rb   rc   r,   r   F)bias)r   r   r   rP   r   fourier_featuresr   r   proj_inr   block_inro   lenr_   rp   rq   down_blocks	block_outr   norm_outproj_outru   )r"   rF   rG   r   r   r   r   r   rH   r   r   
down_blockr#   s               r$   r   zMochiEncoder3D.__init__  sU    	*62 / 1yy.@.CD'*1-:J1:M]pqr]s
 s-.23 		+A).q1/A6+AE2#6q#9"4Q"71!a%8J z*		+ ==5(*2.;KB;O_rsu_v
 00B20FG		"4R"8!l:JQVW&+#r%   r[   rV   r'   c                    i }|xs i }| j                  |      }|j                  ddddd      }| j                  |      }|j                  ddddd      }t        j                         r| j
                  r}| j                  | j                  ||j                  d            \  }|d<   t        | j                        D ]2  \  }}d| }| j                  |||j                  |            \  }||<   4 ni| j                  ||j                  d            \  }|d<   t        | j                        D ])  \  }}d| } |||j                  |            \  }||<   + | j                  ||j                  d	            \  }|d	<   | j                  |      }| j                  |      }|j                  ddddd      }| j                  |      }|j                  ddddd      }||fS )
z-Forward method of the `MochiEncoder3D` class.r   r   r   r)   r   r   down_block_rX   r   )r   r.   r   r0   r|   ru   r}   r   rY   rz   r   r   r   rP   r   )r"   r[   rV   rZ   r   r   r   s          r$   r7   zMochiEncoder3D.forward  s   
 %2
--m<%--aAq!<]3%--aAq!<  "t'B'B8<8Y8Y}jnnZ.H95M>*5 "+4+;+;!< :#.qc!2@D@a@az~~n/MA=~n= 9=*..*D 9F 95M>*5 "+4+;+;!< :#.qc!2@J!jnn^.LA=~n= 6:^^jnn[&A 6D 6
2~k2 m4))-8%--aAq!<m4%--aAq!<n,,r%   )      i   i   r   r   r)   r   r   r   r   r   r   r   r   FTTTTr\   r:   )r;   r<   r=   r>   r?   r   r@   r]   r   r0   rA   r   r   r7   rB   rC   s   @r$   r   r     s    2 /C,;/8.70O(,(, (, "#s(O	(,
  S/(, #38_(, "#s(O(, #49-(, (,V \`.-"\\.-7?S%,,EV@W7X.-	.-r%   r   c                        e Zd ZdZ	 	 	 	 	 ddededeedf   deedf   deedf   deedf   d	ef fd
Z	 ddej                  de
eeej                  f      dej                  fdZ xZS )MochiDecoder3Da  
    The `MochiDecoder3D` layer of a variational autoencoder that decodes its latent representation into an output
    sample.

    Args:
        in_channels (`int`, *optional*):
            The number of input channels.
        out_channels (`int`, *optional*):
            The number of output channels.
        block_out_channels (`Tuple[int, ...]`, *optional*, defaults to `(128, 256, 512, 768)`):
            The number of output channels for each block.
        layers_per_block (`Tuple[int, ...]`, *optional*, defaults to `(3, 3, 4, 6, 3)`):
            The number of resnet blocks for each block.
        temporal_expansions (`Tuple[int, ...]`, *optional*, defaults to `(1, 2, 3)`):
            The temporal expansion factor for each of the up blocks.
        spatial_expansions (`Tuple[int, ...]`, *optional*, defaults to `(2, 2, 2)`):
            The spatial expansion factor for each of the up blocks.
        non_linearity (`str`, *optional*, defaults to `"swish"`):
            The non-linearity to use in the decoder.
    rF   rG   r   .r   r   r   rH   c           
      (   t         |           t        |      | _        t	        j
                  ||d   d      | _        t        |d   |d   d      | _        g }t        t        |      dz
        D ]F  }	t        ||	 dz
     ||	 dz
     ||	 dz
     ||	 dz
     ||	 dz
           }
|j                  |
       H t	        j                  |      | _        t        |d	   |d	   d      | _        t	        j                   |d	   |      | _        d| _        y )
Nr,   )r   r   r   )rM   Fr   r   r   )rF   rG   r`   ra   rb   r   )r   r   r   rP   r   Conv3drn   r   r   ro   r   r   rp   rq   	up_blocksr   r   r   ru   )r"   rF   rG   r   r   r   r   rH   r   r   up_blockr#   s              r$   r   zMochiDecoder3D.__init__=  s0    	*62yy.@.DR[\'*2.'+
 	s-.23 	'A%.rAv6/Q7+QBF3#6rAv#>"4aR!V"<H X&	' y1(*1-'*

 		"4Q"7F&+#r%   r[   rV   r'   c                 0   i }|xs i }| j                  |      }t        j                         r| j                  r}| j	                  | j
                  ||j                  d            \  }|d<   t        | j                        D ]2  \  }}d| }| j	                  |||j                  |            \  }||<   4 ni| j                  ||j                  d            \  }|d<   t        | j                        D ])  \  }}d| } |||j                  |            \  }||<   + | j                  ||j                  d            \  }|d<   | j                  |      }|j                  ddddd	      }| j                  |      }|j                  ddd	dd      }||fS )
z-Forward method of the `MochiDecoder3D` class.r   	up_block_rX   r   r   r   r   r)   r   )rn   r0   r|   ru   r}   r   rY   rz   r   r   rP   r.   r   )r"   r[   rV   rZ   r   r   r   s          r$   r7   zMochiDecoder3D.forwardg  s   
 %2
]3   "t'B'B8<8Y8Y}jnnZ.H95M>*5  )8 8#,QC@D@a@amZ^^N-KA=~n= 9=*..*D 9F 95M>*5  )8 8#,QC@H!jnn^.LA=~n= 6:^^jnn[&A 6D 6
2~k2 ))-8%--aAq!<m4%--aAq!<n,,r%   )r   r   r   r   r\   r:   )r;   r<   r=   r>   r?   r   r]   r   r0   rA   r   r   r7   rB   rC   s   @r$   r   r   '  s    2 /C,;/8.7(,(, (, "#s(O	(,
  S/(, #38_(, "#s(O(, (,V \`*-"\\*-7?S%,,EV@W7X*-	*-r%   r   c                       e Zd ZdZdZdgZe	 	 	 	 	 	 	 	 	 	 	 	 	 d1dededee   dee   ded	eed
f   de	deed
f   deed
f   dee
d
f   deed
f   deed
f   de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 Zdej*                  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
deeej*                  f   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j*                  fd+Z!d4d#ej*                  d!e
deeej*                  f   fd,Z"	 	 	 d5d-ej*                  d.e
d!e
d/eejF                     deej*                  ej*                  f   f
d0Z$ xZ%S )6AutoencoderKLMochia  
    A VAE model with KL loss for encoding images into latents and decoding latent representations into images. Used in
    [Mochi 1 preview](https://github.com/genmoai/models).

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

    Parameters:
        in_channels (int, *optional*, defaults to 3): Number of channels in the input image.
        out_channels (int,  *optional*, defaults to 3): Number of channels in the output.
        block_out_channels (`Tuple[int]`, *optional*, defaults to `(64,)`):
            Tuple of block output channels.
        act_fn (`str`, *optional*, defaults to `"silu"`): The activation function to use.
        scaling_factor (`float`, *optional*, defaults to `1.15258426`):
            The component-wise standard deviation of the trained latent space computed using the first batch of the
            training set. This is used to scale the latent space to have unit variance when training the diffusion
            model. The latents are scaled with the formula `z = z * scaling_factor` before being passed to the
            diffusion model. When decoding, the latents are scaled back to the original scale with the formula: `z = 1
            / scaling_factor * z`. For more details, refer to sections 4.3.2 and D.1 of the [High-Resolution Image
            Synthesis with Latent Diffusion Models](https://huggingface.co/papers/2112.10752) paper.
    TrE   rF   rG   encoder_block_out_channelsdecoder_block_out_channelslatent_channelsr   .rH   r   r   r   latents_meanlatents_stdscaling_factorc           
         t         |           t        ||||||	|
|      | _        t	        ||||||	|      | _        t        j                  d |	d      | _        t        j                  d |d      | _	        d| _
        d| _        d| _        d| _        d| _        d| _        d	| _        d
| _        d
| _        d| _        d| _        y )N)rF   rG   r   r   r   r   r   rH   )rF   rG   r   r   r   r   rH   c                     | |z  S r:    r&   ys     r$   <lambda>z-AutoencoderKLMochi.__init__.<locals>.<lambda>  s
    q1u r%   r   c                     | |z  S r:   r   r   s     r$   r   z-AutoencoderKLMochi.__init__.<locals>.<lambda>  s
    A r%   FT   r   r      )r   r   r   encoderr   decoder	functoolsreducespatial_compression_ratiotemporal_compression_ratiouse_slicing
use_tilinguse_framewise_encodinguse_framewise_decodingdrop_last_temporal_framesnum_sample_frames_batch_sizenum_latent_frames_batch_sizetile_sample_min_heighttile_sample_min_widthtile_sample_stride_heighttile_sample_stride_width)r"   rF   rG   r   r   r   r   rH   r   r   r   r   r   r   r#   s                 r$   r   zAutoencoderKLMochi.__init__  s    V 	%#(9- 31 3	
 &'%9- 31
 *3)9)9:LN`bc)d&*3*:*:;MObde*f' !
   ',#&+# *.&
 -/),-) '*#%(" *-&(+%r%   Nr   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 AutoencoderKLMochi.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!AutoencoderKLMochi.disable_tiling5  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!AutoencoderKLMochi.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"AutoencoderKLMochi.disable_slicingC  s    
 !r%   c                 r    d| _         | j                         D ]  \  }}t        |t              sd|_         y)a  
        Enables the framewise VAE encoding implementation with past latent padding. By default, Diffusers uses the
        oneshot encoding implementation without current latent replicate padding.

        Warning: Framewise encoding may not work as expected due to the causal attention layers. If you enable
        framewise encoding, encode a video, and try to decode it, there will be noticeable jittering effect.
        TconstantN)r   named_modules
isinstancer   rO   r"   namemodules      r$   _enable_framewise_encodingz-AutoencoderKLMochi._enable_framewise_encodingJ  s:     '+# ..0 	-LD&&"78",	-r%   c                 r    d| _         | j                         D ]  \  }}t        |t              sd|_         y)z
        Enables the framewise VAE decoding implementation with past latent padding. By default, Diffusers uses the
        oneshot decoding implementation without current latent replicate padding.
        Tr  N)r   r  r  r   rO   r	  s      r$   _enable_framewise_decodingz-AutoencoderKLMochi._enable_framewise_decodingW  s:    
 '+# ..0 	-LD&&"78",	-r%   r&   c                     |j                   \  }}}}}| j                  r/|| j                  kD  s|| j                  kD  r| j	                  |      S | j
                  rt        d      | j                  |      \  }}|S )NFrame-wise encoding does not work with the Mochi VAE Encoder due to the presence of attention layers. As intermediate frames are not independent from each other, they cannot be encoded frame-wise.)r~   r   r   r   tiled_encoder   NotImplementedErrorr   )	r"   r&   r4   r   r   r   r   encrv   s	            r$   _encodezAutoencoderKLMochi._encodea  s|    >?gg;
L*fe??(B(B BftOjOjFj$$Q''&&%q 
 \\!_FC
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~   r2   r  r0   r1   r   r   )r"   r&   r  x_sliceencoded_slicesr   	posteriors          r$   encodezAutoencoderKLMochi.encodeq  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                  rzd }
g }t        d|| j                        D ]D  }|d d d d ||| j                  z   f   }| j                  ||
      \  }}
|j                  |       F t        j                  |d      }n| j                  |      \  }}| j                  r9|j                  d      | j                  k\  r|d d d d | j                  dz
  d f   }|s|fS t!        |      S )N)r  r   rX   r   r*   r   sample)r~   r   r   r   r   tiled_decoder   ro   r   r   rp   r0   r1   r   r-   r   r   )r"   r  r  r4   r   r   r   r   tile_latent_min_heighttile_latent_min_widthrV   decr   z_intermediaterv   s                  r$   _decodezAutoencoderKLMochi._decode  s\   >?gg;
L*fe!%!<!<@^@^!^ $ : :d>\>\ \??(= =J`A`$$QK$@@&&JC1j$*K*KL +!"1aQ1R1R-R)R#R!S-1\\.U_\-`*


>*+
 ))CQ'C\\!_FC))chhqkT=\=\.\aD;;a?AABC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~   r2   r%  r  r0   r1   r   )r"   r  r  z_slicedecoded_slicesdecodeds         r$   decodezAutoencoderKLMochi.decode  s     
QJK''RS*Uwdll73::UNUii/Gll1o,,G:G,, Vs   "Babblend_extentc           	         t        |j                  d   |j                  d   |      }t        |      D ]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   minr~   ro   )r"   r+  r,  r-  r   s        r$   blend_vzAutoencoderKLMochi.blend_v  s    1771:qwwqz<@|$ 	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 )Nr)   r   r/  )r"   r+  r,  r-  r&   s        r$   blend_hzAutoencoderKLMochi.blend_h  s    1771:qwwqz<@|$ 	A Aq!l]Q->!>?1q<GWCWX[\]^`acdfgij]j[kL \  AaAq!m	 r%   c                 b   |j                   \  }}}}}|| j                  z  }|| j                  z  }| j                  | j                  z  }	| j                  | j                  z  }
| j                  | j                  z  }| j
                  | j                  z  }|	|z
  }|
|z
  }g }t        d|| j                        D ]  }g }t        d|| j
                        D ]j  }| j                  rt        d      | j                  |dddddd||| j                  z   ||| j                  z   f         \  }}|j                  |       l |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  Nr   r)   r*   r   )r~   r   r   r   r   r   ro   r   r  r   rp   rz   r1  r3  r0   r1   )r"   r&   r4   r   r   r   r   latent_heightlatent_widthr!  r"  tile_latent_stride_heighttile_latent_stride_widthblend_heightblend_widthrowsr   rowjtimerv   result_rows
result_rowtiler  s                            r$   r  zAutoencoderKLMochi.tiled_encode  sm    ?@gg;
L*fe$"@"@@ > >>!%!<!<@^@^!^ $ : :d>\>\ \$($B$BdFdFd$d!#'#@#@DDbDb#b -0II+.FF q&$"@"@A 	AC1eT%B%BC !..-y 
 #ll!Q1q4+F+F'F#FAPTPjPjLjHjjkGD! 

4 ! 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                 0   |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                  rg }d}t        d|| j                        D ]P  }|dddd||| j                  z   |||
z   |||z   f   }| j                  ||      \  }}|j                  |       R t        j                  |d      }n,| j                  |dddddd|||
z   |||z   f         \  }}| j                  r9|j                  d      | j                  k\  r|dddd| j                  dz
  df   }|j                  |        |j                  |       A 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   NrX   r   r*   r   r)   r   r  )r~   r   r   r   r   r   ro   r   r   r   rp   r0   r1   r   r-   r   rz   r1  r3  r   )r"   r  r  r4   r   r   r   r   sample_heightsample_widthr!  r"  r7  r8  r9  r:  r;  r   r<  r=  r>  rV   krA  rv   r?  r@  r#  s                               r$   r   zAutoencoderKLMochi.tiled_decode  sQ    ?@gg;
L*fe!?!??t===!%!<!<@^@^!^ $ : :d>\>\ \$($B$BdFdFd$d!#'#@#@DDbDb#b 22T5S5SS0043P3PP q&";< 	AC1e%=> !..D!%J"1j$2S2ST 	* D$E$E EE$: ::$9 99	;  ,0<<<+T(jD)	* !99Tq1D"ll1Q1a!>T:T6TVWZ[^sZsVs-s+tuGD!11diildFeFe6e1d&E&E&I&K KLD

4 /!0 KK5	8 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|fS |S )N)rG  )r  r  r  moder*  )	r"   r  rF  r  rG  r&   r  r  r#  s	            r$   r7   zAutoencoderKLMochi.forward[  sZ     KKN..	  9 5A Akk!n6M
r%   )   r   )@   r   r   i  r   r   r   silur   r   r   )gX(;gRP:vg:*$gV*~g]̴%?ghgҩy?g>1g[bdg,,
g[aogkn|)g?gı?gPo*T?g`4?gq@a?g7k1Z?gAtŽ?g\4?gT~`4?g	(V?gDcd?gˏ?g      ?)NNNN)r'   N)T)FTN)&r;   r<   r=   r>    _supports_gradient_checkpointing_no_split_modulesr	   r?   r   r]   r@   floatr   r   r   r   r  r  r  r  r0   rA   r  r   r   r   r   r  r   r%  r*  r1  r3  r  r   	Generatorr7   rB   rC   s   @r$   r   r     so   , (,$-. 1D1E!,;/8.70O+
*
 !$Qf,f, f, %*#J	f,
 %*#Jf, f,  S/f, f, #38_f, "#s(Of, #49-f, E3J'f,4 5#:&5f,P Qf, f,T 15/35948b (b  (}b $,E?	b
 #+5/b 
b<  !-- %,,   37::,0:	"E*F$GG	H: :6) )D )E-Y^YeYeJeDf ): - -4 -5X]XdXdIdCe - -2 %,, c ell  %,, c ell 7ell 7u|| 7rL)ell L) L)}^c^j^jOjIk L)b "' /3  	
 EOO, 
u||U\\)	*r%   r   )+r   typingr   r   r   r   r0   torch.nnr   configuration_utilsr   r	   utilsr
   utils.accelerate_utilsr   activationsr   attention_processorr   r   modeling_outputsr   modeling_utilsr   autoencoder_kl_cogvideoxr   vaer   r   
get_loggerr;   loggerModuler   rE   r_   r   r   r   r   r   r   r   r%   r$   <module>r_     s      / /   B  8 ( E 2 ' ; < 
		H	%bii D7- 7-ts-ryy s-lQ-bii Q-hL-RYY L-^Ybii Y:n-RYY n-bj-RYY j-ZW[ Wr%   