o
    ۷i                     @   sN  d dl Z d dlmZ ddlmZmZ ddlmZ ddlm	Z	 ddl
mZ ddlmZ dd	lmZ dd
lmZ ddlmZmZmZ G dd dejZG dd dejZG dd dejZG dd dejZG dd dejZG dd dejZG dd dejZG dd dejZG dd dejZG dd  d ejZ G d!d" d"eeeeZ!dS )#    N   )ConfigMixinregister_to_config)FromOriginalModelMixin)apply_forward_hook   )get_activation))PixArtAlphaCombinedTimestepSizeEmbeddings)AutoencoderKLOutput)
ModelMixin   )AutoencoderMixinDecoderOutputDiagonalGaussianDistributionc                       sP   e Zd ZdZddededdf fdd	Zdd
ejdedB dejfddZ	  Z
S )PerChannelRMSNorma  
    Per-pixel (per-location) RMS normalization layer.

    For each element along the chosen dimension, this layer normalizes the tensor by the root-mean-square of its values
    across that dimension:

        y = x / sqrt(mean(x^2, dim=dim, keepdim=True) + eps)
    r   :0yE>channel_dimepsreturnNc                    s   t    || _|| _dS )z
        Args:
            dim: Dimension along which to compute the RMS (typically channels).
            eps: Small constant added for numerical stability.
        N)super__init__r   r   )selfr   r   	__class__ g/home/ubuntu/vllm_env/lib/python3.10/site-packages/diffusers/models/autoencoders/autoencoder_kl_ltx2.pyr   (   s   

zPerChannelRMSNorm.__init__xc                 C   s8   |p| j }tj|d | j dd}t|| j }|| S )zI
        Apply RMS normalization along the configured dimension.
        r   T)dimkeepdim)r   torchmeansqrtr   )r   r   r   mean_sqrmsr   r   r   forward2   s   
zPerChannelRMSNorm.forward)r   r   N)__name__
__module____qualname____doc__intfloatr   r   Tensorr$   __classcell__r   r   r   r   r      s    	(
r   c                       s   e Zd Z					ddededeeeeef B deeeeef B deeeeef B d	ed
ef fddZddejde	dejfddZ
  ZS )LTX2VideoCausalConv3dr   r   zerosin_channelsout_channelskernel_sizestridedilationgroupsspatial_padding_modec              
      s   t    || _|| _t|tr|n|||f| _t|tr|n|ddf}t|tr+|n|||f}| jd d }| jd d }	d||	f}
tj||| j||||
|d| _	d S )Nr   r   r   )r3   r4   r5   paddingpadding_mode)
r   r   r0   r1   
isinstancetupler2   nnConv3dconv)r   r0   r1   r2   r3   r4   r5   r6   
height_pad	width_padr7   r   r   r   r   @   s&   


zLTX2VideoCausalConv3d.__init__Thidden_statescausalr   c                 C   s   | j d }|r.|d d d d d dd d d d f dd|d ddf}tj||gdd}nH|d d d d d dd d d d f dd|d d ddf}|d d d d dd d d d d f dd|d d ddf}tj|||gdd}| |}|S )Nr   r   r   r   )r2   repeatr   concatenater=   )r   r@   rA   time_kernel_sizepad_left	pad_rightr   r   r   r$   a   s   
:>>
zLTX2VideoCausalConv3d.forward)r   r   r   r   r/   Tr&   r'   r(   r*   r:   strr   r   r,   boolr$   r-   r   r   r   r   r.   ?   s,    $!r.   c                       s   e Zd ZdZ								dded	edB d
edededededededdf fddZ			dde	j
de	j
dB de	jdB dede	j
f
ddZ  ZS )LTX2VideoResnetBlock3da  
    A 3D ResNet block used in the LTX 2.0 audiovisual model.

    Args:
        in_channels (`int`):
            Number of input channels.
        out_channels (`int`, *optional*):
            Number of output channels. If None, defaults to `in_channels`.
        dropout (`float`, defaults to `0.0`):
            Dropout rate.
        eps (`float`, defaults to `1e-6`):
            Epsilon value for normalization layers.
        elementwise_affine (`bool`, defaults to `False`):
            Whether to enable elementwise affinity in the normalization layers.
        non_linearity (`str`, defaults to `"swish"`):
            Activation function to use.
        conv_shortcut (bool, defaults to `False`):
            Whether or not to use a convolution shortcut.
    N        ư>Fswishr/   r0   r1   dropoutr   elementwise_affinenon_linearityinject_noisetimestep_conditioningr6   r   c
           
         s  t    |p|}t|| _t | _t||d|	d| _t | _t	
|| _t||d|	d| _d | _d | _||krLt	j||ddd| _t	j||ddd| _d | _d | _|rjt	t|dd| _t	t|dd| _d | _|rt	td||d  | _d S d S )	Nr   )r0   r1   r2   r6   T)r   rR   biasr   )r0   r1   r2   r3            ?)r   r   r   nonlinearityr   norm1r.   conv1norm2r;   DropoutrQ   conv2norm3conv_shortcut	LayerNormr<   per_channel_scale1per_channel_scale2	Parameterr   r/   scale_shift_tablerandn)
r   r0   r1   rQ   r   rR   rS   rT   rU   r6   r   r   r   r      s@   

 zLTX2VideoResnetBlock3d.__init__Tinputstemb	generatorrA   c                 C   s  |}|  |}| jd ur)|dd| jd  }|jdd\}}}}	|d|  | }| |}| j||d}| jd ur]|jdd  }
tj	|
||j
|jdd  }||| j d d d d df  }| |}| jd uro|d|	  | }| |}| |}| j||d}| jd ur|jdd  }
tj	|
||j
|jdd  }||| j d d d d df  }| jd ur| |dd	d	d}| jd ur| |}|| }|S )
Nr   )rW   rC   N.NNNrB   rA   )ri   devicedtype.rC   )rZ   re   	unflattenunbindrY   r[   rb   shaper   rf   rm   rn   r\   rQ   r^   rc   r_   movedimr`   )r   rg   rh   ri   rA   r@   shift_1scale_1shift_2scale_2spatial_shapespatial_noiser   r   r   r$      sH   











zLTX2VideoResnetBlock3d.forward)NrN   rO   FrP   FFr/   NNT)r&   r'   r(   r)   r*   r+   rL   rK   r   r   r,   	Generatorr$   r-   r   r   r   r   rM   r   sZ    	
7rM   c                       sb   e Zd Z		ddededeeeeef B deddf
 fd	d
Zddejde	dejfddZ
  ZS )LTXVideoDownsampler3dr   r/   r0   r1   r3   r6   r   Nc                    s   t    t|tr|n|||f| _||d  |d  |d  | | _|| jd | jd  | jd   }t||dd|d| _d S Nr   r   r   r   r0   r1   r2   r3   r6   )r   r   r9   r:   r3   
group_sizer.   r=   )r   r0   r1   r3   r6   r   r   r   r      s   
""zLTXVideoDownsampler3d.__init__Tr@   rA   c              
   C   s  t j|d d d d d | jd d f |gdd}|dd| jd fdd| jd fdd| jd f}|ddddd	ddd
dd}|dd| jf}|jdd}| j||d}|dd| jd fdd| jd fdd| jd f}|ddddd	ddd
dd}|| }|S )Nr   r   r   rB   rW   rC   r            rk   )	r   catr3   ro   permuteflattenr~   r    r=   )r   r@   rA   residualr   r   r   r$     s    2  zLTXVideoDownsampler3d.forward)r   r/   rI   rJ   r   r   r   r   r{      s    $r{   c                       sj   e Zd Z				ddedeeeeef B dededed	d
f fddZddej	ded	ej	fddZ
  ZS )LTXVideoUpsampler3dr   Fr/   r0   r3   r   upscale_factorr6   r   Nc                    sh   t    t|tr|n|||f| _|| _|| _||d  |d  |d  | }t||dd|d| _d S r|   )	r   r   r9   r:   r3   r   r   r.   r=   )r   r0   r3   r   r   r6   r1   r   r   r   r   !  s   
 zLTXVideoUpsampler3d.__init__Tr@   rA   c           
   
   C   sh  |j \}}}}}| jre||d| jd | jd | jd |||}|dddddddd	ddd	ddd}| jd | jd  | jd  | j }	|d|	ddd}|d d d d | jd d d f }| j||d
}||d| jd | jd | jd |||}|dddddddd	ddd	ddd}|d d d d | jd d d f }| jr|| }|S )NrC   r   r   r   r   r   r   r   rW   rk   )	rq   r   reshaper3   r   r   r   rD   r=   )
r   r@   rA   
batch_sizenum_channels
num_framesheightwidthr   repeatsr   r   r   r$   9  s$   "0$$"0$zLTXVideoUpsampler3d.forward)r   Fr   r/   rI   )r&   r'   r(   r*   r:   rL   rK   r   r   r,   r$   r-   r   r   r   r   r      s&    $r   c                       s   e Zd ZdZdZ									dd
ededB dededededededef fddZ				dde
jde
jdB de
jdB dede
jf
ddZ  ZS )LTX2VideoDownBlock3Da  
    Down block used in the LTXVideo 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 layers.
        dropout (`float`, defaults to `0.0`):
            Dropout rate.
        resnet_eps (`float`, defaults to `1e-6`):
            Epsilon value for normalization layers.
        resnet_act_fn (`str`, defaults to `"swish"`):
            Activation function to use.
        spatio_temporal_scale (`bool`, defaults to `True`):
            Whether or not to use a downsampling layer. If not used, output dimension would be same as input dimension.
            Whether or not to downsample across temporal dimension.
        is_causal (`bool`, defaults to `True`):
            Whether this layer behaves causally (future frames depend only on past frames) or not.
    TNr   rN   rO   rP   r=   r/   r0   r1   
num_layersrQ   
resnet_epsresnet_act_fnspatio_temporal_scaledownsample_typer6   c
                    s   t    |p|}g }
t|D ]}|
t||||||	d qt|
| _d | _|rst | _|dkrA| jt	||dd|	d n2|dkrR| jt
||d|	d n!|d	krc| jt
||d
|	d n|dkrs| jt
||d|	d d| _d S )N)r0   r1   rQ   r   rS   r6   r=   r   r   r   r   r}   spatial)r   r   r   )r0   r1   r3   r6   temporal)r   r   r   spatiotemporalF)r   r   rangeappendrM   r;   
ModuleListresnetsdownsamplersr.   r{   gradient_checkpointing)r   r0   r1   r   rQ   r   r   r   r   r6   r   _r   r   r   r   m  sp   


	
	zLTX2VideoDownBlock3D.__init__r@   rh   ri   rA   r   c                 C   sl   t | jD ]\}}t r| jr| |||||}q|||||d}q| jdur4| jD ]}|||d}q+|S )z-Forward method of the `LTXDownBlock3D` class.rk   N)	enumerater   r   is_grad_enabledr   _gradient_checkpointing_funcr   )r   r@   rh   ri   rA   iresnetdownsamplerr   r   r   r$     s   	

zLTX2VideoDownBlock3D.forward)Nr   rN   rO   rP   Tr=   r/   ry   r&   r'   r(   r)    _supports_gradient_checkpointingr*   r+   rK   rL   r   r   r,   rz   r$   r-   r   r   r   r   r   S  sX    	
Mr   c                       s   e Zd ZdZdZ							dd	ed
edededededededdf fddZ				dde
jde
jdB de
jdB dede
jf
ddZ  ZS )LTX2VideoMidBlock3das  
    A middle block used in the LTXVideo model.

    Args:
        in_channels (`int`):
            Number of input channels.
        num_layers (`int`, defaults to `1`):
            Number of resnet layers.
        dropout (`float`, defaults to `0.0`):
            Dropout rate.
        resnet_eps (`float`, defaults to `1e-6`):
            Epsilon value for normalization layers.
        resnet_act_fn (`str`, defaults to `"swish"`):
            Activation function to use.
        is_causal (`bool`, defaults to `True`):
            Whether this layer behaves causally (future frames depend only on past frames) or not.
    Tr   rN   rO   rP   Fr/   r0   r   rQ   r   r   rT   rU   r6   r   Nc	                    sj   t    d | _|rt|d d| _g }	t|D ]}
|	t||||||||d qt|	| _	d| _
d S )NrW   r   r0   r1   rQ   r   rS   rT   rU   r6   F)r   r   time_embedderr	   r   r   rM   r;   r   r   r   )r   r0   r   rQ   r   r   rT   rU   r6   r   r   r   r   r   r     s(   

zLTX2VideoMidBlock3d.__init__r@   rh   ri   rA   c                 C   s   | j dur!| j | dd|d|jd}||ddddd}t| jD ]\}}t r;| j	r;| 
|||||}q&|||||d}q&|S )z,Forward method of the `LTXMidBlock3D` class.Nr   timestep
resolutionaspect_ratior   hidden_dtyperC   r   rk   )r   r   sizern   viewr   r   r   r   r   r   )r   r@   rh   ri   rA   r   r   r   r   r   r$     s   
	zLTX2VideoMidBlock3d.forward)r   rN   rO   rP   FFr/   ry   r   r   r   r   r   r     sV    	
&r   c                       s   e Zd ZdZdZ												dd
ededB dedededededededededef fddZ				d de
jde
jdB de
jdB dede
jf
ddZ  ZS )!LTX2VideoUpBlock3da  
    Up block used in the LTXVideo 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 layers.
        dropout (`float`, defaults to `0.0`):
            Dropout rate.
        resnet_eps (`float`, defaults to `1e-6`):
            Epsilon value for normalization layers.
        resnet_act_fn (`str`, defaults to `"swish"`):
            Activation function to use.
        spatio_temporal_scale (`bool`, defaults to `True`):
            Whether or not to use a downsampling layer. If not used, output dimension would be same as input dimension.
            Whether or not to downsample across temporal dimension.
        is_causal (`bool`, defaults to `True`):
            Whether this layer behaves causally (future frames depend only on past frames) or not.
    TNr   rN   rO   rP   Fr/   r0   r1   r   rQ   r   r   r   rT   rU   upsample_residualr   r6   c                    s   t    |p|}d | _|	rt|d d| _d | _||kr*t|||||||	|d| _d | _|r?tt	|| d|
||dg| _g }t
|D ]}|t|||||||	|d qEt|| _d| _d S )NrW   r   r   r   )r3   r   r   r6   F)r   r   r   r	   conv_inrM   
upsamplersr;   r   r   r   r   r   r   )r   r0   r1   r   rQ   r   r   r   rT   rU   r   r   r6   r   r   r   r   r   r   >  sZ   

zLTX2VideoUpBlock3d.__init__r@   rh   ri   rA   r   c                 C   s   | j d ur| j ||||d}| jd ur/| j| d d |d|jd}||ddddd}| jd ur@| jD ]}|||d}q7t| jD ]\}}t	
 rZ| jrZ| |||||}qE|||||d}qE|S )Nrk   r   r   rC   r   )r   r   r   r   rn   r   r   r   r   r   r   r   r   )r   r@   rh   ri   rA   	upsamplerr   r   r   r   r   r$     s&   



zLTX2VideoUpBlock3d.forward)Nr   rN   rO   rP   TFFFr   r/   ry   r   r   r   r   r   r   $  sj    	
Gr   c                       s   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dedededef fddZ	d$de
jdedB d e
jfd!d"Z  ZS )%LTX2VideoEncoder3daL  
    The `LTXVideoEncoder3d` layer of a variational autoencoder that encodes input video samples to its latent
    representation.

    Args:
        in_channels (`int`, defaults to 3):
            Number of input channels.
        out_channels (`int`, defaults to 128):
            Number of latent channels.
        block_out_channels (`tuple[int, ...]`, defaults to `(256, 512, 1024, 2048)`):
            The number of output channels for each block.
        spatio_temporal_scaling (`tuple[bool, ...], defaults to `(True, True, True, True)`:
            Whether a block should contain spatio-temporal downscaling layers or not.
        layers_per_block (`tuple[int, ...]`, defaults to `(4, 6, 6, 2, 2)`):
            The number of layers per block.
        downsample_type (`tuple[str, ...]`, defaults to `("spatial", "temporal", "spatiotemporal", "spatiotemporal")`):
            The spatiotemporal downsampling pattern per block. Per-layer values can be
                - `"spatial"` (downsample spatial dims by 2x)
                - `"temporal"` (downsample temporal dim by 2x)
                - `"spatiotemporal"` (downsample both spatial and temporal dims by 2x)
        patch_size (`int`, defaults to `4`):
            The size of spatial patches.
        patch_size_t (`int`, defaults to `1`):
            The size of temporal patches.
        resnet_norm_eps (`float`, defaults to `1e-6`):
            Epsilon value for ResNet normalization layers.
        is_causal (`bool`, defaults to `True`):
            Whether this layer behaves causally (future frames depend only on past frames) or not.
    r               i   r   r   r   r   TTTTrW   r   r   r   r   r   r   r   r   rW   r   rO   Tr/   r0   r1   block_out_channels.down_block_typesspatio_temporal_scalinglayers_per_blockr   
patch_sizepatch_size_tresnet_norm_eps	is_causalr6   c              
      s
  t    || _|	| _||d  | _|| _|}t| j|dd|d| _t|}t	
g | _t|D ]/}|}|| }|| dkrPt|||| |
|| || |d}n	td||  | j| q0t||d |
|d	| _t | _t	 | _t||d dd|d| _d
| _d S )Nr   r   r   r}   r   )r0   r1   r   r   r   r   r6   zUnknown down block type: rC   )r0   r   r   r6   F)r   r   r   r   r0   r   r.   r   lenr;   r   down_blocksr   r   
ValueErrorr   r   	mid_blockr   norm_outSiLUconv_actconv_outr   )r   r0   r1   r   r   r   r   r   r   r   r   r   r6   output_channelnum_block_out_channelsr   input_channel
down_blockr   r   r   r     s\   
	


zLTX2VideoEncoder3d.__init__Nr@   rA   r   c              
   C   sT  | j }| j}|j\}}}}}	|| }
|| }|	| }|p| j}||||
|||||}|dddddddddd}| j||d	}t	 rc| j
rc| jD ]}| ||d
d
|}qL| | j|d
d
|}n| jD ]}|||d	}qf| j||d	}| |}| |}| j||d	}|d
d
dd
f }|d|dd ddd}tj||gdd}|S )z4The forward method of the `LTXVideoEncoder3d` class.r   r   r   r   r   r   rW   r   rk   NrC   rB   )r   r   rq   r   r   r   r   r   r   r   r   r   r   r   r   r   r   rD   r   r   )r   r@   rA   pp_tr   r   r   r   r   post_patch_num_framespost_patch_heightpost_patch_widthr   last_channelr   r   r   r$     s4   
 



zLTX2VideoEncoder3d.forward)r   r   r   r   r   r   r   rW   r   rO   Tr/   r%   )r&   r'   r(   r)   r*   r:   rK   rL   r+   r   r   r,   r$   r-   r   r   r   r   r     sP     




(Pr   c                       s   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dedededeedf dedeedf deedf deddf fdd Z			d'd!e
jd"e
jdB d#edB de
jfd$d%Z  ZS )(LTX2VideoDecoder3da  
    The `LTXVideoDecoder3d` layer of a variational autoencoder that decodes its latent representation into an output
    sample.

    Args:
        in_channels (`int`, defaults to 128):
            Number of latent channels.
        out_channels (`int`, defaults to 3):
            Number of output channels.
        block_out_channels (`tuple[int, ...]`, defaults to `(128, 256, 512, 512)`):
            The number of output channels for each block.
        spatio_temporal_scaling (`tuple[bool, ...], defaults to `(True, True, True, False)`:
            Whether a block should contain spatio-temporal upscaling layers or not.
        layers_per_block (`tuple[int, ...]`, defaults to `(4, 3, 3, 3, 4)`):
            The number of layers per block.
        patch_size (`int`, defaults to `4`):
            The size of spatial patches.
        patch_size_t (`int`, defaults to `1`):
            The size of temporal patches.
        resnet_norm_eps (`float`, defaults to `1e-6`):
            Epsilon value for ResNet normalization layers.
        is_causal (`bool`, defaults to `False`):
            Whether this layer behaves causally (future frames depend only on past frames) or not.
        timestep_conditioning (`bool`, defaults to `False`):
            Whether to condition the model on timesteps.
    r   r   r   r   r   TTTr   r   r   r   rW   r   rO   FFFFr   reflectr0   r1   r   .r   r   r   r   r   r   rT   rU   r   upsample_factorr6   r   Nc                    s  t    || _|| _||d  | _|	| _tt|}tt|}tt|}tt|
}
tt|}tt|}|d }t||dd|d| _	t
||d ||
d ||d| _t|}tg | _t|D ]2}|||  }|| ||  }t||||d  ||| |
|d  ||| || |d
}| j| qdt | _t | _t|| jdd|d| _d | _d | _d | _|rttjdtjd	| _t|d d| _tt d||d
  | _d| _!d S )Nr   r   r   r   r}   )r0   r   r   rT   rU   r6   )
r0   r1   r   r   r   rT   rU   r   r   r6   g     @@)rn   rX   F)"r   r   r   r   r1   r   r:   reversedr.   r   r   r   r   r;   r   	up_blocksr   r   r   r   r   r   r   r   r   re   timestep_scale_multiplierrd   r   tensorfloat32r	   rf   r   )r   r0   r1   r   r   r   r   r   r   r   rT   rU   r   r   r6   r   r   r   r   up_blockr   r   r   r   Z  s|   




	
zLTX2VideoDecoder3d.__init__r@   rh   rA   c              
   C   s  |p| j }| j||d}| jd ur|| j }t r7| jr7| | j||d |}| jD ]}| |||d |}q*n| j|||d}| jD ]	}||||d}qB| 	|}| j
d ur| j
| d d |d|jd}||ddddddd}|| jd  }|jdd\}}|d|  | }| |}| j||d}| j}| j}|j\}	}
}}}||	d||||||}|ddd	d
dddddddd	d
d}|S )Nrk   r   r   rC   r   )r   rC   rj   rB   r   r   r   rW   r   r   )r   r   r   r   r   r   r   r   r   r   r   r   r   rn   r   ro   re   rp   r   r   r   r   rq   r   r   )r   r@   rh   rA   r   shiftscaler   r   r   r   r   r   r   r   r   r   r$     sB   






 
0zLTX2VideoDecoder3d.forward)r   r   r   r   r   rW   r   rO   Fr   Fr   r   r   )NN)r&   r'   r(   r)   r*   r:   rL   r+   rK   r   r   r,   r$   r-   r   r   r   r   r   >  st    


	



`r   c                6       s  e Zd ZdZdZe										
																d_de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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edf d&e	d'ed(ed)e
d*e
d+e	d,e	d-ed.ed/ed0ed1df4 fd2d3Z						d`d4edB d5edB d6edB d7e
dB d8e
dB d9e
dB d1dfd:d;Zdad<ejd=e	dB d1ejfd>d?Ze	dbd<ejd=e	dB d@e	d1eee B fdAdBZ			dcdCejdDejdB d=e	dB d@e	d1eejB f
dEdFZe			dcdCejdDejdB d=e	dB d@e	d1eejB f
dGdHZdIejdJejdKed1ejfdLdMZdIejdJejdKed1ejfdNdOZdIejdJejdKed1ejfdPdQZdad<ejd=e	dB d1ejfdRdSZ	dbdCejdDejdB d=e	dB d@e	d1eejB f
dTdUZdad<ejd=e	dB d1efdVdWZ	dbdCejdDejdB d=e	dB d@e	d1eejB f
dXdYZ						dddZejdDejdB d[e	d+e	dB d,e	dB d@e	d\ejdB d1ejejB fd]d^Z  Z S )eAutoencoderKLLTX2Videoae	  
    A VAE model with KL loss for encoding images into latents and decoding latent representations into images. Used in
    [LTX-2](https://huggingface.co/Lightricks/LTX-2).

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

    Args:
        in_channels (`int`, defaults to `3`):
            Number of input channels.
        out_channels (`int`, defaults to `3`):
            Number of output channels.
        latent_channels (`int`, defaults to `128`):
            Number of latent channels.
        block_out_channels (`tuple[int, ...]`, defaults to `(128, 256, 512, 512)`):
            The number of output channels for each block.
        spatio_temporal_scaling (`tuple[bool, ...], defaults to `(True, True, True, False)`:
            Whether a block should contain spatio-temporal downscaling or not.
        layers_per_block (`tuple[int, ...]`, defaults to `(4, 3, 3, 3, 4)`):
            The number of layers per block.
        patch_size (`int`, defaults to `4`):
            The size of spatial patches.
        patch_size_t (`int`, defaults to `1`):
            The size of temporal patches.
        resnet_norm_eps (`float`, defaults to `1e-6`):
            Epsilon value for ResNet normalization layers.
        scaling_factor (`float`, *optional*, defaults to `1.0`):
            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.
        encoder_causal (`bool`, defaults to `True`):
            Whether the encoder should behave causally (future frames depend only on past frames) or not.
        decoder_causal (`bool`, defaults to `False`):
            Whether the decoder should behave causally (future frames depend only on past frames) or not.
    Tr   r   r   r   r   r   r   r   r   FFFFr   r   FrW   r   rO         ?r/   r   Nr0   r1   latent_channelsr   .r   decoder_block_out_channelsr   decoder_layers_per_blockr   decoder_spatio_temporal_scalingdecoder_inject_noiser   r   r   rU   r   r   r   scaling_factorencoder_causaldecoder_causalencoder_spatial_padding_modedecoder_spatial_padding_modespatial_compression_ratiotemporal_compression_ratior   c                    s  t    t|||||	|||||||d| _t||||
||||||||||d| _tj|fdd}tj|fdd}| j	d|dd | j	d|dd |d u rU|d	t
|	  n|| _|d u rd|d	t
|	  n|| _d| _d| _d| _d| _d
| _d	| _d| _d| _d
| _d| _d| _d| _d S )N)r0   r1   r   r   r   r   r   r   r   r   r   r6   )r0   r1   r   r   r   r   r   r   r   rU   rT   r   r   r6   F)requires_gradlatents_meanT)
persistentlatents_stdr      r   i     )r   r   r   encoderr   decoderr   r/   onesregister_buffersumr   r   use_slicing
use_tilinguse_framewise_encodinguse_framewise_decodingnum_sample_frames_batch_sizenum_latent_frames_batch_sizetile_sample_min_heighttile_sample_min_widthtile_sample_min_num_framestile_sample_stride_heighttile_sample_stride_widthtile_sample_stride_num_frames)r   r0   r1   r   r   r   r   r   r   r   r   r   r   r   r   rU   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r     sn   
"
zAutoencoderKLLTX2Video.__init__r
  r  r  r  r  r  c                 C   sR   d| _ |p| j| _|p| j| _|p| j| _|p| j| _|p| j| _|p%| j| _dS )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  r  r  r  r  r   r   r   enable_tiling  s   z$AutoencoderKLLTX2Video.enable_tilingr   rA   c           	      C   sh   |j \}}}}}| jr|| jkr| j||dS | jr+|| jks$|| jkr+| j||dS | j||d}|S )Nrk   )	rq   r  r  _temporal_tiled_encoder  r  r
  tiled_encoder   )	r   r   rA   r   r   r   r   r   encr   r   r   _encode  s   zAutoencoderKLLTX2Video._encodereturn_dictc                    sd   j r|jd dkr fdd|dD }t|}nj| d}t|}|s-|fS t|dS )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   c                    s   g | ]	}j | d qS rk   )r  ).0x_slicerA   r   r   r   
<listcomp>  s    z1AutoencoderKLLTX2Video.encode.<locals>.<listcomp>rk   )latent_dist)r  rq   splitr   r   r  r   r
   )r   r   rA   r  encoded_slicesh	posteriorr   r  r   encode  s   
zAutoencoderKLLTX2Video.encodezrh   c                 C   s   |j \}}}}}	| j| j }
| j| j }| j| j }| jr*||kr*| j||||dS | jr>|	|ks5||
kr>| j	||||dS | j
|||d}|sK|fS t|dS )NrA   r  rk   sample)rq   r
  r   r  r  r   r  _temporal_tiled_decoder  tiled_decoder   r   )r   r!  rh   rA   r  r   r   r   r   r   tile_latent_min_heighttile_latent_min_widthtile_latent_min_num_framesdecr   r   r   _decode  s   
zAutoencoderKLLTX2Video._decodec                    s   j r4|jd dkr4|dur! fdd|d|dfD }n fdd|dD }t|}n	j|| dj}|sB|fS t|dS )	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   Nc                    s"   g | ]\}}j || d jqS r  r+  r$  )r  z_slicet_slicer  r   r   r     s    z1AutoencoderKLLTX2Video.decode.<locals>.<listcomp>c                    s   g | ]
}j | d jqS r  r,  )r  r-  r  r   r   r    s    rk   r#  )r  rq   r  r   r   r+  r$  r   )r   r!  rh   rA   r  decoded_slicesdecodedr   r  r   decode  s   
zAutoencoderKLLTX2Video.decodeabblend_extentc              	   C   s   t |jd |jd |}t|D ]@}|d d d d d d | | d d f d||   |d d d d d d |d d f ||   |d d d d d d |d d f< q|S )Nr   r   minrq   r   )r   r2  r3  r4  yr   r   r   blend_v     R&zAutoencoderKLLTX2Video.blend_vc                 C   s   t |jd |jd |}t|D ]@}|d d d d d d d d | | f d||   |d d d d d d d d |f ||   |d d d d d d d d |f< q|S )NrW   r   r5  r   r2  r3  r4  r   r   r   r   blend_h  r9  zAutoencoderKLLTX2Video.blend_hc              	   C   s   t |jd |jd |}t|D ]@}|d d d d | | d d d d f d||   |d d d d |d d d d f ||   |d d d d |d d d d f< q|S )Nr   r5  r:  r   r   r   blend_t  r9  zAutoencoderKLLTX2Video.blend_tc                 C   s  |j \}}}}}|| j }|| j }	| j| j }
| j| j }| j| j }| j| j }|
| }|| }g }td|| jD ]6}g }td|| jD ]%}| j|dddddd||| j ||| j f |d}|| qF|| q;g }t	|D ]O\}}g }t	|D ]:\}}|dkr| 
||d  | ||}|dkr| ||d  ||}||ddddddd|d|f  q|tj|dd qxtj|d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   Nrk   r   rW   rB   r   )rq   r   r
  r  r  r  r   r   r   r   r8  r;  r   r   )r   r   rA   r   r   r   r   r   latent_heightlatent_widthr'  r(  tile_latent_stride_heighttile_latent_stride_widthblend_heightblend_widthrowsr   rowjtimeresult_rows
result_rowtiler  r   r   r   r  '  s>   


0.0z#AutoencoderKLLTX2Video.tiled_encodec                 C   s  |j \}}}}}	|| j }
|	| j }| j| j }| j| j }| j| j }| j| j }| j| j }| j| j }g }td||D ]4}g }td|	|D ]$}| j|dddddd||| ||| f ||d}|| qH|| q>g }t	|D ]Q\}}g }t	|D ]<\}}|dkr| 
||d  | ||}|dkr| ||d  ||}||ddddddd| jd| jf  q|tj|dd qytj|ddddddddd|
d|f }|s|fS t|d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   Nrk   r   rW   rB   r   r#  )rq   r   r
  r  r  r  r   r   r   r   r8  r;  r   r   r   )r   r!  rh   rA   r  r   r   r   r   r   sample_heightsample_widthr'  r(  r@  rA  rB  rC  rD  r   rE  rF  rG  rH  rI  rJ  r*  r   r   r   r&  [  s@   

020
z#AutoencoderKLLTX2Video.tiled_decodec              
   C   s  |j \}}}}}|d | j d }| j| j }	| j| j }
|	|
 }g }td|| jD ]R}|d d d d ||| j d d d d d f }| jrY|| jksQ|| jkrY| j||d}n| j	||d}|dkrw|d d d d dd d d d d f }|
| q*g }t|D ]B\}}|dkr| ||d  ||}|
|d d d d d |
d d d d f  q|
|d d d d d |
d d d d d f  qtj|ddd d d d d |f }|S )Nr   r   rk   r   rB   )rq   r   r  r  r   r  r
  r  r  r   r   r   r=  r   r   )r   r   rA   r   r   r   r   r   latent_num_framesr)  tile_latent_stride_num_framesblend_num_framesrE  r   rJ  rI  r  r   r   r   r    s,   0&.2$z-AutoencoderKLLTX2Video._temporal_tiled_encodec              
   C   s  |j \}}}}}	|d | j d }
| j| j }| j| j }| j| j }| j| j }| j| j }g }td||D ]Y}|d d d d ||| d d d d d f }| jrl|j d |ksa|j d |krl| j	|||ddj
}n| j|||d}|dkr|d d d d d dd d d d f }|| q7g }t|D ]F\}}|dkr| ||d  ||}|d d d d d | jd d d d f }|| q||d d d d d | jd d d d d f  qtj|dd	d d d d d |
f }|s|fS t|d
S )Nr   r   rC   rl   Tr"  rk   r   rB   r#  )rq   r   r
  r   r  r  r  r   r  r&  r$  r   r   r   r=  r   r   r   )r   r!  rh   rA   r  r   r   r   r   r   num_sample_framesr'  r(  r)  rN  rO  rE  r   rJ  r0  rI  r*  r   r   r   r%    s6   ."&(4$
z-AutoencoderKLLTX2Video._temporal_tiled_decoder$  sample_posteriorri   c                 C   sN   |}| j ||dj}	|r|	j|d}
n|	 }
| j|
||d}|s%|jfS |S )Nrk   )ri   )r   r  r$  moder1  )r   r$  rh   rQ  r   r   r  ri   r   r  r!  r*  r   r   r   r$     s   
zAutoencoderKLLTX2Video.forward)r   r   r   r   r   r   r   r   r   r   r   r   r   r   FrW   r   rO   r   TTr/   r   NN)NNNNNNr%   )NTry   )NFNNTN)!r&   r'   r(   r)   r   r   r*   r:   rK   rL   r+   r   r  r   r,   r  r   r
   r   r   r   r+  r1  r8  r;  r=  r  r&  r  r%  rz   r$   r-   r   r   r   r   r     s   '










 r
 "

 %   5
>
)
	r   )"r   torch.nnr;   configuration_utilsr   r   loadersr   utils.accelerate_utilsr   activationsr   
embeddingsr	   modeling_outputsr
   modeling_utilsr   vaer   r   r   Moduler   r.   rM   r{   r   r   r   r   r   r   r   r   r   r   r   <module>   s0   !3~03|U   .