
    bi                     ^   d dl mZmZmZ d dlZd dlmZ ddlmZm	Z	 ddl
mZ ddlmZ ddlmZ dd	lmZ dd
lmZ ddlmZ ddlmZ ddlmZmZ  G d dej6                        Z G d dej6                        Z G d dej6                        Z G d dej6                        Z G d dej6                        Z  G d dej6                        Z! G d dej6                        Z" G d dej6                        Z# G d d ej6                        Z$ G d! d"ej6                        Z% G d# d$eee      Z&y)%    )OptionalTupleUnionN   )ConfigMixinregister_to_config)FromOriginalModelMixin)apply_forward_hook   )get_activation))PixArtAlphaCombinedTimestepSizeEmbeddings)AutoencoderKLOutput)
ModelMixin)RMSNorm   )DecoderOutputDiagonalGaussianDistributionc                        e 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ededef fd	Zd
e	j                  de	j                  fdZ xZS )LTXVideoCausalConv3din_channelsout_channelskernel_sizestridedilationgroupspadding_mode	is_causalc	           
         t         |           || _        || _        || _        t        |t              r|n|||f| _        t        |t              r|n|ddf}t        |t              r|n|||f}| j                  d   dz  }	| j                  d   dz  }
d|	|
f}t        j                  ||| j                  |||||      | _
        y )Nr   r   r   )r   r   r   paddingr   )super__init__r   r   r   
isinstancetupler   nnConv3dconv)selfr   r   r   r   r   r   r   r   
height_pad	width_padr   	__class__s               k/home/cdr/jupyterlab/.venv/lib/python3.12/site-packages/diffusers/models/autoencoders/autoencoder_kl_ltx.pyr!   zLTXVideoCausalConv3d.__init__!   s     	&("*4[%*H;{\gitNu)(E:81a@P%fe4666:R%%a(A-
$$Q'1,	j),II%	
	    hidden_statesreturnc                    | j                   d   }| j                  rE|d d d d d dd d d d f   j                  dd|dz
  ddf      }t        j                  ||gd      }nv|d d d d d dd d d d f   j                  dd|dz
  dz  ddf      }|d d d d dd d d d d f   j                  dd|dz
  dz  ddf      }t        j                  |||gd      }| j                  |      }|S )Nr   r   r   dim)r   r   repeattorchconcatenater&   )r'   r-   time_kernel_sizepad_left	pad_rights        r+   forwardzLTXVideoCausalConv3d.forwardD   s   ++A.>>$Q2A2q!^4;;QCSVWCWYZ\]<^_H!--x.GQOM$Q2A2q!^4;;QDTWXDX]^C^`acd<efH%aBCAo6==q!FVYZFZ_`E`bcef>ghI!--x	.RXYZM		-0r,   )r   r   r   r   zerosT)__name__
__module____qualname__intr   r   strboolr!   r4   Tensorr9   __classcell__r*   s   @r+   r   r       s    
 9:3456#!
!
 !
 3c3m 445	!

 c5c3//0!
 U3S=112!
 !
 !
 !
FU\\ ell r,   r   c                        e Zd ZdZ	 	 	 	 	 	 	 	 ddedee   dedededed	ed
ededdf fdZ		 dde
j                  dee
j                     dee
j                     de
j                  fdZ xZS )LTXVideoResnetBlock3da  
    A 3D ResNet 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`.
        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.
    Nr   r   dropoutepselementwise_affinenon_linearityr   inject_noisetimestep_conditioningr.   c
                    t         
|           |xs |}t        |      | _        t	        |d|      | _        t        ||d|      | _        t	        |d|      | _        t        j                  |      | _        t        ||d|      | _        d | _        d | _        ||k7  r3t        j                  ||dd      | _        t        ||dd|      | _        d | _        d | _        |r^t        j$                  t'        j(                  |dd            | _        t        j$                  t'        j(                  |dd            | _        d | _        |	r5t        j$                  t'        j,                  d	|      |d
z  z        | _        y y )N:0yE>rG   rH   r   )r   r   r   r   T)rG   rH   biasr   r   r   r   r   r            ?)r    r!   r   nonlinearityr   norm1r   conv1norm2r$   DropoutrF   conv2norm3conv_shortcut	LayerNormper_channel_scale1per_channel_scale2	Parameterr4   r:   scale_shift_tablerandn)r'   r   r   rF   rG   rH   rI   r   rJ   rK   r*   s             r+   r!   zLTXVideoResnetBlock3d.__init__h   s[    	#2{*=9[dGYZ
)#,AYb

 \tHZ[
zz'*)$<QZc

 
!,&kstZ^_DJ!5'lPQZ[gp"D #'"&&(ll5;;{Aq3Q&RD#&(ll5;;{Aq3Q&RD#!% %'\\%++a2MP[]`P`2`%aD" !r,   inputstemb	generatorc                    |}| j                  |j                  dd            j                  dd      }| j                  D|j                  dd      | j                  d   z   }|j	                  d      \  }}}}|d|z   z  |z   }| j                  |      }| j                  |      }| j                  Z|j                  dd  }	t        j                  |	||j                  |j                        d    }
||
| j                  z  d d d d df   z   }| j                  |j                  dd            j                  dd      }| j                  |dz   z  z   }| j                  |      }| j                  |      }| j                  |      }| j                   Z|j                  dd  }	t        j                  |	||j                  |j                        d    }
||
| j                   z  d d d d df   z   }| j"                  1| j#                  |j                  dd            j                  dd      }| j$                  | j%                  |      }||z   }|S )	Nr   r2   )rQ   r2   N.NNNr0   )rc   devicedtype.)rT   movedimr_   	unflattenunbindrS   rU   r\   shaper4   r`   rg   rh   rV   rF   rX   r]   rY   rZ   )r'   ra   rb   rc   r-   shift_1scale_1shift_2scale_2spatial_shapespatial_noises              r+   r9   zLTXVideoResnetBlock3d.forward   s]    

=#8#8B#?@HHQO!!->>!W-0F0FGb0ccD151C.GWgw)Q[9GCM))-8

=1"".)//4M!KK=;O;OWdWjWjM *]T=T=T-TVZ\]_cehVh,iiM

=#8#8B#?@HHQO!!-)Q[9GCM))-8]3

=1"".)//4M!KK=;O;OWdWjWjM *]T=T=T-TVZ\]_cehVh,iiM::!ZZq" 56>>r1EF)''/F%.r,   )N        ư>FswishTFFNN)r;   r<   r=   __doc__r>   r   floatr@   r?   r!   r4   rA   	Generatorr9   rB   rC   s   @r+   rE   rE   S   s    . '+#($"&+-b-b sm-b 	-b
 -b !-b -b -b -b  $-b 
-b` qu-ll-*25<<*@-T\]b]l]lTm-	-r,   rE   c                        e Zd Z	 	 	 ddededeeeeeef   f   dededdf fdZd	e	j                  de	j                  fd
Z xZS )LTXVideoDownsampler3dr   r   r   r   r   r.   Nc                 "   t         |           t        |t              r|n|||f| _        ||d   z  |d   z  |d   z  |z  | _        || j                  d   | j                  d   z  | j                  d   z  z  }t        ||dd||      | _        y Nr   r   r   r   )r   r   r   r   r   r   )r    r!   r"   r#   r   
group_sizer   r&   )r'   r   r   r   r   r   r*   s         r+   r!   zLTXVideoDownsampler3d.__init__   s     	 *65 9fPV?W&2VAY>J|[#AQ(G$++VW.(XY(#%%
	r,   r-   c           
         t        j                  |d d d d d | j                  d   dz
  f   |gd      }|j                  dd| j                  d   f      j                  dd| j                  d   f      j                  dd| j                  d   f      }|j	                  ddddd	ddd
      j                  dd      }|j                  dd| j                  f      }|j                  d      }| j                  |      }|j                  dd| j                  d   f      j                  dd| j                  d   f      j                  dd| j                  d   f      }|j	                  ddddd	ddd
      j                  dd      }||z   }|S )Nr   r   r   r0   rQ   r2   r            )	r4   catr   rj   permuteflattenr~   meanr&   )r'   r-   residuals      r+   r9   zLTXVideoDownsampler3d.forward   s   		=A7KQ!9K7K1K#Lm"\bcd ##ADKKN';<Yq2t{{1~./Yq2t{{1~./ 	
 ##Aq!Q1a;CCAqI%%a"doo)>?==Q='		-0##ADKKN';<Yq2t{{1~./Yq2t{{1~./ 	
 &--aAq!Q1EMMaQRS%0r,   )r   Tr:   r;   r<   r=   r>   r   r   r@   r?   r!   r4   rA   r9   rB   rC   s   @r+   r{   r{      s}    
 45#

 
 c5c3//0	

 
 
 

0U\\ ell r,   r{   c                        e Zd Z	 	 	 	 	 ddedeeeeeef   f   dededededdf fd	Zd
e	j                  de	j                  fdZ xZS )LTXVideoUpsampler3dr   r   r   r   upscale_factorr   r.   Nc                     t         |           t        |t              r|n|||f| _        || _        || _        ||d   z  |d   z  |d   z  |z  }t        ||dd||      | _        y r}   )	r    r!   r"   r#   r   r   r   r   r&   )	r'   r   r   r   r   r   r   r   r*   s	           r+   r!   zLTXVideoUpsampler3d.__init__   s|     	 *65 9fPV?W ,#fQi/&);fQiGNZ(#%%
	r,   r-   c           
         |j                   \  }}}}}| j                  r|j                  |d| j                  d   | j                  d   | j                  d   |||      }|j	                  dddddddd	      j                  dd      j                  d	d      j                  dd      }| j                  d   | j                  d   z  | j                  d   z  | j                  z  }|j                  d|ddd      }|d d d d | j                  d   dz
  d f   }| j                  |      }|j                  |d| j                  d   | j                  d   | j                  d   |||      }|j	                  dddddddd	      j                  dd      j                  d	d      j                  dd      }|d d d d | j                  d   dz
  d f   }| j                  r|z   }|S )
Nr2   r   r   r   r   r   r   r   rQ   )	rl   r   reshaper   r   r   r   r3   r&   )	r'   r-   
batch_sizenum_channels
num_framesheightwidthr   repeatss	            r+   r9   zLTXVideoUpsampler3d.forward  s   >K>Q>Q;
L*fe==$,,BAAAPZ\bdiH  ''1aAq!Q?GG1MUUVWYZ[ccdeghiH{{1~A6QGDL_L__Gq'1a;H1dkk!nq&8&: :;H		-0%--DKKNDKKNDKKNJX^`e
 &--aAq!Q1EMMaQRS[[\]_`aiijkmno%aDKKNQ,>,@&@A==)H4Mr,   )r   TFr   r:   r   rC   s   @r+   r   r      s     45#

 c5c3//0
 	

 
 
 
 

4U\\ ell r,   r   c                        e Zd ZdZdZ	 	 	 	 	 	 	 ddedee   dedededed	e	d
e	f fdZ
	 	 ddej                  deej                     deej                     dej                  fdZ xZS )LTXVideoDownBlock3D  
    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.
    Tr   r   
num_layersrF   
resnet_epsresnet_act_fnspatio_temporal_scaler   c	                 |   t         |           |xs |}g }	t        |      D ]"  }
|	j                  t	        ||||||             $ t        j                  |	      | _        d | _        |r)t        j                  t        ||dd|      g      | _        d | _
        ||k7  rt	        ||||||      | _
        d| _        y )Nr   r   rF   rG   rI   r   r   r   r   r   rP   F)r    r!   rangeappendrE   r$   
ModuleListresnetsdownsamplersr   conv_outgradient_checkpointing)r'   r   r   r   rF   r   r   r   r   r   _r*   s              r+   r!   zLTXVideoDownBlock3D.__init__F  s     	#2{z" 
	ANN% +!,#""/'	
	 }}W-   "($/%0$%("+
!D ,&1')+#DM ',#r,   r-   rb   rc   r.   c                 F   t        | j                        D ]D  \  }}t        j                         r!| j                  r| j                  ||||      }; ||||      }F | j                  | j                  D ]
  } ||      } | j                  | j                  |||      }|S z-Forward method of the `LTXDownBlock3D` class.)	enumerater   r4   is_grad_enabledr   _gradient_checkpointing_funcr   r   r'   r-   rb   rc   iresnetdownsamplers          r+   r9   zLTXVideoDownBlock3D.forward~  s     #4<<0 	GIAv$$&4+F+F $ A A&-Y]_h i &}dI F		G (#00 ; +M :; ==$ MM-yIMr,   )Nr   rs   rt   ru   TTrv   r;   r<   r=   rw    _supports_gradient_checkpointingr>   r   rx   r?   r@   r!   r4   rA   ry   r9   rB   rC   s   @r+   r   r   ,  s    . (,$
 '+ $&*6,6, sm6, 	6,
 6, 6, 6,  $6, 6,v (,/3	|| u||$ EOO,	
 
r,   r   c                        e Zd ZdZdZ	 	 	 	 	 	 	 	 ddedee   dedededed	e	d
e	def fdZ
	 	 ddej                  deej                     deej                     dej                  fdZ xZS )LTXVideo095DownBlock3Dr   Tr   r   r   rF   r   r   r   r   downsample_typec
                    t         |           |xs |}g }
t        |      D ]"  }|
j                  t	        ||||||             $ t        j                  |
      | _        d | _        |rt        j                         | _        |	dk(  r1| j                  j                  t        ||dd|             d| _        y |	dk(  r0| j                  j                  t        ||d|             d| _        y |	d	k(  r0| j                  j                  t        ||d
|             d| _        y |	dk(  r(| j                  j                  t        ||d|             d| _        y )Nr   r&   r   r   rP   spatial)r   r   r   )r   r   r   r   temporal)r   r   r   spatiotemporalF)r    r!   r   r   rE   r$   r   r   r   r   r{   r   )r'   r   r   r   rF   r   r   r   r   r   r   r   r*   s               r+   r!   zLTXVideo095DownBlock3D.__init__  ss    	#2{z" 
	ANN% +!,#""/'	
	 }}W-   "D&(!!((($/%0$%("+8 ',#' !I-!!(()$/lS\hq$ ',# !J.!!(()$/lS\hq ',# !$44!!(()$/lS\hq ',#r,   r-   rb   rc   r.   c                    t        | j                        D ]D  \  }}t        j                         r!| j                  r| j                  ||||      }; ||||      }F | j                  | j                  D ]
  } ||      } |S r   )r   r   r4   r   r   r   r   r   s          r+   r9   zLTXVideo095DownBlock3D.forward  s     #4<<0 	GIAv$$&4+F+F $ A A&-Y]_h i &}dI F		G (#00 ; +M :; r,   )Nr   rs   rt   ru   TTr&   rv   r   rC   s   @r+   r   r     s    . (,$
 '+ $&*%?,?, sm?, 	?,
 ?, ?, ?,  $?, ?, ?,H (,/3	|| u||$ EOO,	
 
r,   r   c                        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Z		 	 dde
j                  dee
j                     dee
j                     de
j                  fdZ xZS )LTXVideoMidBlock3das  
    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   r   rF   r   r   r   rJ   rK   r.   Nc	                    t         |           d | _        |rt        |dz  d      | _        g }	t	        |      D ]$  }
|	j                  t        ||||||||             & t        j                  |	      | _	        d| _
        y )NrQ   r   r   r   rF   rG   rI   r   rJ   rK   F)r    r!   time_embedderr   r   r   rE   r$   r   r   r   )r'   r   r   rF   r   r   r   rJ   rK   r   r   r*   s              r+   r!   zLTXVideoMidBlock3d.__init__  s     	! !J;YZ?\]!^Dz" 	ANN% +!,#""/'!-*?		 }}W-&+#r,   r-   rb   rc   c                    | j                   a| j                  |j                         dd|j                  d      |j                        }|j	                  |j                  d      dddd      }t        | j                        D ]D  \  }}t        j                         r!| j                  r| j                  ||||      }; ||||      }F |S )z,Forward method of the `LTXMidBlock3D` class.Nr   timestep
resolutionaspect_ratior   hidden_dtyper2   r   )r   r   sizerh   viewr   r   r4   r   r   r   )r'   r-   rb   rc   r   r   s         r+   r9   zLTXVideoMidBlock3d.forward?  s     )%%!(--a0*00 & D 99]//2B1a@D"4<<0 	GIAv$$&4+F+F $ A A&-Y]_h i &}dI F		G r,   )r   rs   rt   ru   TFFrv   )r;   r<   r=   rw   r   r>   rx   r?   r@   r!   r4   rA   r   ry   r9   rB   rC   s   @r+   r   r     s    $ (,$
  $"&+!,!, !, 	!,
 !, !, !, !,  $!, 
!,L (,/3	|| u||$ EOO,	
 
r,   r   c                        e Zd ZdZdZ	 	 	 	 	 	 	 	 	 	 	 ddedee   dedededed	e	d
e	de	de	de	def fdZ
	 	 ddej                  deej                     deej                     dej                  fdZ xZS )LTXVideoUpBlock3da  
    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.
    Tr   r   r   rF   r   r   r   r   rJ   rK   upsample_residualr   c                    t         |           |xs |}d | _        |
rt        |dz  d      | _        d | _        ||k7  rt        |||||||	|
      | _        d | _        |r,t        j                  t        ||z  d|||      g      | _        g }t        |      D ]$  }|j                  t        |||||||	|
             & t        j                  |      | _        d| _        y )NrQ   r   r   r   )r   r   r   r   F)r    r!   r   r   conv_inrE   
upsamplersr$   r   r   r   r   r   r   )r'   r   r   r   rF   r   r   r   r   rJ   rK   r   r   r   r   r*   s                  r+   r!   zLTXVideoUpBlock3d.__init__t  s    	#2{! !J;YZ?\]!^D,&0')+#)&;	DL   mm'$~5("+!2'5
DO z" 	ANN% ,!-#""/'!-*?		 }}W-&+#r,   r-   rb   rc   r.   c                     | j                   | j                  |||      }| j                  a| j                  |j                         d d |j                  d      |j                        }|j                  |j                  d      dddd      }| j                  | j                  D ]
  } ||      } t        | j                        D ]D  \  }}t        j                         r!| j                  r| j                  ||||      }; ||||      }F |S )Nr   r   r2   r   )r   r   r   r   rh   r   r   r   r   r4   r   r   r   )r'   r-   rb   rc   	upsamplerr   r   s          r+   r9   zLTXVideoUpBlock3d.forward  s    <<# LLiHM)%%!(--a0*00 & D 99]//2B1a@D??&!__ 9	 )- 89 #4<<0 	GIAv$$&4+F+F $ A A&-Y]_h i &}dI F		G r,   )Nr   rs   rt   ru   TTFFFr   rv   r   rC   s   @r+   r   r   Z  s   . (,$
 '+ $&*"&+"'B,B, smB, 	B,
 B, B, B,  $B, B, B,  $B,  B, B,N (,/3	|| u||$ EOO,	
 
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dededef fdZ	de
j                  de
j                  fdZ xZS )LTXVideoEncoder3da  
    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 `(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 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 `True`):
            Whether this layer behaves causally (future frames depend only on past frames) or not.
    r   r   block_out_channels.down_block_typesspatio_temporal_scalinglayers_per_blockr   
patch_sizepatch_size_tresnet_norm_epsr   c                    t         |           || _        |	| _        ||dz  z  | _        |d   }t        | j                  |dd|      | _        |d   dk(  }t        |      |rdndz
  }t        j                  g       | _
        t        |      D ]  }|}|s|dz   |k  r||dz      n||   }n||dz      }||   dk(  rt        ||||   |
||   |	      }n5||   dk(  rt        ||||   |
||   |||   
      }nt        d||          | j                  j                  |        t!        ||d   |
|      | _        t%        |dd      | _        t        j(                         | _        t        ||dz   dd|      | _        d| _        y )Nr   r   r   r   rP   r2   r   r   )r   r   r   r   r   r   )r   r   r   r   r   r   r   zUnknown down block type: )r   r   r   r   rM   FrN   )r    r!   r   r   r   r   r   lenr$   r   down_blocksr   r   r   
ValueErrorr   r   	mid_blockr   norm_outSiLUconv_actr   r   )r'   r   r   r   r   r   r   r   r   r   r   r   output_channel
is_ltx_095num_block_out_channelsr   input_channel
down_blockr*   s                     r+   r!   zLTXVideoEncoder3d.__init__  s   & 	$(&Q6+A.+(('
 &b)-EE
!$%7!8AQR!S==,-. 	0A*M>?!eF\>\!3AE!:btuvbw!3AE!:"&;;0 -!//2.*A!*D'
 "!$(@@3 -!//2.*A!*D'$3A$6
 !#<=Ma=P<Q!RSS##J/;	0@ ,&'+&	
  $5Q	,&\A5EST]^js
 ',#r,   r-   r.   c           
      j   | j                   }| j                  }|j                  \  }}}}}||z  }	||z  }
||z  }|j                  |||	||
|||      }|j	                  dddddddd      j                  dd      }| j                  |      }t        j                         rL| j                  r@| j                  D ]  }| j                  ||      } | j                  | j                  |      }n*| j                  D ]
  } ||      } | j                  |      }| j                  |j                  dd	            j                  d	d      }| j                  |      }| j!                  |      }|d
d
d	d
f   }|j#                  d|j%                  d      dz
  ddd      }t        j&                  ||gd      }|S )z4The forward method of the `LTXVideoEncoder3d` class.r   r   r   r   r   r   rQ   r   r2   Nr0   )r   r   rl   r   r   r   r   r4   r   r   r   r   r   r   ri   r   r   r3   r   r   )r'   r-   pp_tr   r   r   r   r   post_patch_num_framespost_patch_heightpost_patch_widthr   last_channels                 r+   r9   zLTXVideoEncoder3d.forwardI  s    OO>K>Q>Q;
L*fe *c 1"aK A:%--&;SBSUVXhjk
 &--aAq!Q1EMMaQRS]3  "t'B'B".. ]
 $ A A*m \] !==dnnm\M".. :
 *= 9: !NN=9Mm&;&;Ar&BCKKBPQRm4m4$QV,#**1m.@.@.Ca.GAqQ		=,"?QGr,   )r      r         r   r   r   r   r   TTTFrQ   r   r   r   rQ   r&   r&   r&   r&   rQ   r   rt   T)r;   r<   r=   rw   r>   r   r?   r@   rx   r!   r4   rA   r9   rB   rC   s   @r+   r   r     s    6 .B-
 5N,;+K!%#U,U, U, "#s(O	U,
  S/U, "'tSy!1U,  S/U, sCxU, U, U,  !U," #U,n%U\\ %ell %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d	ed
ededeedf   dedeedf   deedf   ddf fdZdde	j                  dee	j                     de	j                  fdZ xZS )LTXVideoDecoder3da  
    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   r   r   r   r   rJ   rK   r   upsample_factorr.   Nc                    t         |           || _        || _        ||dz  z  | _        t        t        |            }t        t        |            }t        t        |            }t        t        |
            }
t        t        |            }t        t        |            }|d   }t        ||dd|	      | _        t        ||d   ||	|
d   |      | _
        t        |      }t        j                  g       | _        t        |      D ]Z  }|||   z  }||   ||   z  }t!        ||||dz      |||   |	|
|dz      |||   ||   
      }| j                  j#                  |       \ t%        |dd	
      | _        t        j(                         | _        t        || j                  dd|	      | _        d | _        d | _        d | _        |rt        j4                  t7        j8                  dt6        j:                              | _        t=        |dz  d      | _        t        j4                  t7        j>                  d|      |dz  z        | _        d	| _         y )Nr   r   r   r   rP   )r   r   r   r   rJ   rK   )
r   r   r   r   r   r   rJ   rK   r   r   rM   FrN   g     @@)rh   rR   )!r    r!   r   r   r   r#   reversedr   r   r   r   r   r$   r   	up_blocksr   r   r   r   r   r   r   r   r   r_   timestep_scale_multiplierr^   r4   tensorfloat32r   r`   r   )r'   r   r   r   r   r   r   r   r   r   rJ   rK   r   r   r   r   r   r   up_blockr*   s                      r+   r!   zLTXVideoDecoder3d.__init__  sV     	$((:q=8"8,>#?@"'1H(I"J *:!;<Xl34!(+<"=> 9:+A.+#.aXYen
 ,&'*&%a"7
 "%%7!8r*-. 	,A*oa.@@M/2oa6HHN()++AE2*&=a&@#)!a%0&;"3A"6.q1H NN!!(+#	,(  $5Q	,&T5F5FTU^_kt

 "!%)-& -/\\%,,vUZUbUb:c-dD*!J>\]K]_`!aD%'\\%++a2PSacfSf2f%gD"&+#r,   r-   rb   c           
         | j                  |      }| j                  || j                  z  }t        j                         rN| j                  rB| j                  | j                  ||      }| j                  D ]  }| j                  |||      } n,| j                  ||      }| j                  D ]  } |||      } | j                  |j                  dd            j                  dd      }| j                  | j                  |j                         d d |j                  d      |j                        }|j                  |j                  d      dddd      j                  dd      }|| j                   d   z   }|j#                  d      \  }}|d|z   z  |z   }| j%                  |      }| j'                  |      }| j(                  }| j*                  }|j,                  \  }}	}
}}|j/                  |d||||
||      }|j1                  dddd	d
ddd      j                  d
d      j                  dd      j                  d	d      }|S )Nr   r2   r   r   )r   r2   re   r0   r   r   r   rQ   r   r   )r   r   r4   r   r   r   r   r   r   ri   r   r   r   rh   r   rj   r_   rk   r   r   r   r   rl   r   r   )r'   r-   rb   r   shiftscaler   r   r   r   r   r   r   s                r+   r9   zLTXVideoDecoder3d.forward  sI   ]3))5$888D  "t'B'B ==dnnm]abM NN a $ A A(M[_ `a !NN=$?M NN > ( => m&;&;Ar&BCKKBPQR)%%!(--a0*00 & D 99]//2B1a@JJ1gVD$001LMMD;;1;-LE5)QY7%?Mm4m4OO>K>Q>Q;
L*fe%--j"c1aU[]bc%--aAq!Q1EMMaQRS[[\]_`aiijkmnor,   )r   r   r   r   r   rQ   r   rt   FFFFFFr  r   r   r   r   N)r;   r<   r=   rw   r>   r   r@   rx   r!   r4   rA   r   r9   rB   rC   s   @r+   r   r   q  s2   : .B4M,;!%)E&+.J,8Q,Q, Q, "#s(O	Q,
 "'tSy!1Q,  S/Q, Q, Q, Q, Q, D#I&Q,  $Q, !s+Q, tSy)Q, 
Q,f*U\\ *%,,9O *[`[g[g *r,   r   c            2           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df0 fd       Z	 	 	 	 	 	 d?dee   dee   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(ej$                  dej$                  fd)Ze	 dAd(ej$                  d*e	deeee   f   fd+       Z	 dBd,ej$                  d-eej$                     d*e	deeej$                  f   fd.Ze	 dBd,ej$                  d-eej$                     d*e	deeej$                  f   fd/       Zd0ej$                  d1ej$                  d2edej$                  fd3Zd0ej$                  d1ej$                  d2edej$                  fd4Zd0ej$                  d1ej$                  d2edej$                  fd5Zd(ej$                  dej$                  fd6Z	 dAd,ej$                  d-eej$                     d*e	deeej$                  f   fd7Z d(ej$                  defd8Z!	 dAd,ej$                  d-eej$                     d*e	deeej$                  f   fd9Z"	 	 	 	 dCd:ej$                  d-eej$                     d;e	d*e	d<eejF                     deej$                  ej$                  f   fd=Z$ xZ%S )DAutoencoderKLLTXVideoag	  
    A VAE model with KL loss for encoding images into latents and decoding latent representations into images. Used in
    [LTX](https://huggingface.co/Lightricks/LTX-Video).

    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.
    TNr   r   latent_channelsr   .r   decoder_block_out_channelsr   decoder_layers_per_blockr   decoder_spatio_temporal_scalingdecoder_inject_noiser   r   r   rK   r   r   r   scaling_factorencoder_causaldecoder_causalspatial_compression_ratiotemporal_compression_ratior.   c                 R   t         |           t        |||||	||||||      | _        t	        ||||
|||||||||      | _        t        j                  |fd      }t        j                  |fd      }| j                  d|d       | j                  d|d       ||d	t        |	      z  z  n|| _        ||d	t        |	      z  z  n|| _        d| _        d| _        d| _        d| _        d
| _        d	| _        d| _        d| _        d
| _        d| _        d| _        d| _        y )N)r   r   r   r   r   r   r   r   r   r   r   )r   r   r   r   r   r   r   r   r   rK   rJ   r   r   F)requires_gradlatents_meanT)
persistentlatents_stdr      r   i     )r    r!   r   encoderr   decoderr4   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'   r   r   r  r   r   r  r   r  r   r	  r
  r   r   r   rK   r   r   r   r  r  r  r  r  r  r  r*   s                             r+   r!   zAutoencoderKLLTXVideo.__init__7  s   @ 	(#(1-$;-+!%+$
 )'%9$C5!%+$"7-/+
  {{O#5UKjj/!35I^\dK]KDI )0 c"9:::* 	& *1 1$; <<<+ 	' !
   ',#&+#
 -/),-) '*#%("*,' *-&(+%-.*r,   r"  r#  r$  r%  r&  r'  c                    d| _         |xs | j                  | _        |xs | j                  | _        |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#  r$  r%  r&  r'  s          r+   enable_tilingz#AutoencoderKLLTXVideo.enable_tiling  s}    4 &<&[@[@[#%:%Xd>X>X"*D*gHgHg')B)ddFdFd&(@(aDDaDa%-J-pdNpNp*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$AutoencoderKLLTXVideo.disable_tiling  s    
  r,   c                     d| _         y)z
        Enable sliced VAE decoding. When this option is enabled, the VAE will split the input tensor in slices to
        compute decoding in several steps. This is useful to save some memory and allow larger batch sizes.
        TNr  r+  s    r+   enable_slicingz$AutoencoderKLLTXVideo.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%AutoencoderKLLTXVideo.disable_slicing  s    
 !r,   xc                    |j                   \  }}}}}| j                  r || j                  kD  r| j                  |      S | j                  r/|| j
                  kD  s|| j                  kD  r| j                  |      S | j                  |      }|S r  )	rl   r  r$  _temporal_tiled_encoder  r#  r"  tiled_encoder  )r'   r2  r   r   r   r   r   encs           r+   _encodezAutoencoderKLLTXVideo._encode  s    >?gg;
L*fe&&:8W8W+W..q11??(B(B BftOjOjFj$$Q''ll1o
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  rl   splitr7  r4   r   r   r   )r'   r2  r8  x_sliceencoded_slicesh	posteriors          r+   encodezAutoencoderKLLTXVideo.encode  s      
QCD771:Ndll73NNN		.)AQA03	<"y99 Os   Bzrb   c                    |j                   \  }}}}}| j                  | j                  z  }	| j                  | j                  z  }
| j                  | j
                  z  }| j                  r||kD  r| j                  |||      S | j                  r||
kD  s||	kD  r| j                  |||      S | j                  ||      }|s|fS t        |      S )Nr8  sample)rl   r"  r  r#  r$  r  r  _temporal_tiled_decoder  tiled_decoder  r   )r'   rA  rb   r8  r   r   r   r   r   tile_latent_min_heighttile_latent_min_widthtile_latent_min_num_framesdecs                r+   _decodezAutoencoderKLLTXVideo._decode  s     ?@gg;
L*fe!%!<!<@^@^!^ $ : :d>\>\ \%)%D%DHgHg%g"&&:8R+R..q$K.PP??(= =J`A`$$Q+$FFll1d#6MC((r,   c                    | j                   r|j                  d   dkD  r|O|j                  d      |j                  d      fD cg c]!  \  }}| j                  ||      j                  # }}}n7|j                  d      D cg c]  }| j                  |      j                   }}t        j                  |      }n| j                  ||      j                  }|s|fS t        |      S c c}}w 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   rD  )r  rl   r;  rL  rE  r4   r   r   )r'   rA  rb   r8  z_slicet_slicedecoded_slicesdecodeds           r+   decodezAutoencoderKLLTXVideo.decode  s    " 
QSTSZSZ[\S]_c_i_ijk_lRm">NgwDLL'299" " OPggVWj!Y7$,,w"7">">!Y!Yii/Gll1d+22G:G,," "Zs   &C*"C0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   minrl   r   )r'   rS  rT  rU  ys        r+   blend_vzAutoencoderKLLTXVideo.blend_v9  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 )NrQ   r   rW  r'   rS  rT  rU  r2  s        r+   blend_hzAutoencoderKLLTXVideo.blend_hA  s    1771:qwwqz<@|$ 	A Aq!l]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 | |z   d d 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   rW  r\  s        r+   blend_tzAutoencoderKLLTXVideo.blend_tI  s    1772;\B|$ 	A A}q'8!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 ]  }g }t        d|| j
                        D ]P  }| j                  |dddddd||| j                  z   ||| j                  z   f         }|j                  |       R |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   Nr   rQ   r0   r   )rl   r  r"  r#  r%  r&  r   r  r   r   rZ  r]  r4   r   )r'   r2  r   r   r   r   r   latent_heightlatent_widthrH  rI  tile_latent_stride_heighttile_latent_stride_widthblend_heightblend_widthrowsr   rowjtimeresult_rows
result_rowtiler6  s                           r+   r5  z"AutoencoderKLLTXVideo.tiled_encodeQ  sJ    ?@gg;
L*fe$"@"@@ > >>!%!<!<@^@^!^ $ : :d>\>\ \$($B$BdFdFd$d!#'#@#@DDbDb#b -0II+.FF q&$"@"@A 	AC1eT%B%BC !||aAq1t'B'B#BBADLfLfHfDffg 

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                 v   |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 ]b  }g }t        d||      D ]=  }| j                  |dddddd|||z   |||z   f   |      }|j                  |       ? |j                  |       d 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   rQ   r0   r   rD  )rl   r  r"  r#  r%  r&  r   r  r   r   rZ  r]  r4   r   r   )r'   rA  rb   r8  r   r   r   r   r   sample_heightsample_widthrH  rI  rd  re  rf  rg  rh  r   ri  rj  rk  rl  rm  rn  rK  s                             r+   rG  z"AutoencoderKLLTXVideo.tiled_decode  sf   " ?@gg;
L*fe!?!??t===!%!<!<@^@^!^ $ : :d>\>\ \$($B$BdFdFd$d!#'#@#@DDbDb#b 22T5S5SS0043P3PP q&";< 	AC1e%=> !||AaAq17M3M/MqSTWlSlOl&l$most

4 ! 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,   c           
      t   |j                   \  }}}}}|dz
  | j                  z  dz   }| j                  | j                  z  }| j                  | j                  z  }	||	z
  }
g }t	        d|| j                        D ]  }|d d d d ||| j                  z   dz   d d d d f   }| j
                  r0|| j                  kD  s|| j                  kD  r| j                  |      }n| j                  |      }|dkD  r|d d d d dd d d d d f   }|j                  |        g }t        |      D ]m  \  }}|dkD  r=| j                  ||dz
     ||
      }|j                  |d d d d d |	d d d d f          H|j                  |d d d d d |	dz   d d d d f          o t        j                  |d      d d d d d |f   }|S )Nr   r   r   r0   )rl   r  r$  r'  r   r  r"  r#  r5  r  r   r   r`  r4   r   )r'   r2  r   r   r   r   r   latent_num_framesrJ  tile_latent_stride_num_framesblend_num_framesri  r   rn  rm  r6  s                   r+   r4  z,AutoencoderKLLTXVideo._temporal_tiled_encode  s   >?gg;
L*fe'!^0O0OORSS%)%D%DHgHg%g"(,(J(JdNmNm(m%58UUq*d&H&HI 	AQ1q4#B#BBQFF1LMDFT-H-H$HETXTnTnLn((.||D)1uAq!"aN+JJt	 
 ~ 	YGAt1u||CAJ6FG!!$q!-K.K-KQPQ'Q"RS!!$q!-P/Lq/P-PRSUV'V"WX	Y ii
*1a1C2C1C+CD
r,   c           
      J   |j                   \  }}}}}|dz
  | j                  z  dz   }	| j                  | j                  z  }
| j                  | j                  z  }| j
                  | j                  z  }| j                  | j                  z  }| j
                  | j                  z
  }g }t        d||      D ]  }|d d d d |||z   dz   d d d d f   }| j                  rC|j                   d   |kD  s|j                   d   |
kD  r| j                  ||d      j                  }n| j                  ||      }|dkD  r|d d d d d dd d d d f   }|j                  |        g }t        |      D ]  \  }}|dkD  rI| j                  ||dz
     ||      }|d d d d d | j                  d d d d f   }|j                  |       T|j                  |d d d d d | j                  dz   d d d d f           t        j                   |d      d d d d d |	f   }|s|fS t#        |	      S )
Nr   r   r2   rf   TrC  r   r0   rD  )rl   r  r"  r  r#  r$  r'  r   r  rG  rE  r  r   r   r`  r4   r   r   )r'   rA  rb   r8  r   r   r   r   r   num_sample_framesrH  rI  rJ  rt  ru  ri  r   rn  rQ  rm  rK  s                        r+   rF  z,AutoencoderKLLTXVideo._temporal_tiled_decode  sG    ?@gg;
L*fe'!^t/N/NNQRR!%!<!<@^@^!^ $ : :d>\>\ \%)%D%DHgHg%g"(,(J(JdNmNm(m%::T=_=__q*&CD 	 AQ1q#==AA1aGHDDJJrN5J$JdjjY[n_uNu++D$D+IPP,,tT21u!!QQ/2JJw	  
 ~ 	^GAt1u||CAJ6FGAq"FD$F$F"F1LM!!$'!!$q!-Ut/Q/QTU/U-UWXZ['["\]	^ ii
*1a1C2C1C+CD6MC((r,   rE  sample_posteriorrc   c                     |}| j                  |      j                  }|r|j                  |      }n|j                         }| j	                  ||      }	|s|	j                  fS |	S )N)rc   )r@  r:  rE  moderR  )
r'   rE  rb   rx  r8  rc   r2  r?  rA  rK  s
             r+   r9   zAutoencoderKLLTXVideo.forward  sb     KKN..	  9 5A Akk!T"JJ= 
r,   )r   r   r   r   r   r   r   r   r   r   )FFFFFr   r  r  FrQ   r   rt   g      ?TFNN)NNNNNN)r.   N)T)NT)NFTN)&r;   r<   r=   rw   r   r   r>   r   r?   r@   rx   r!   r   r)  r,  r/  r1  r4   rA   r7  r
   r   r   r   r@  r   rL  rR  rZ  r]  r`  r5  rG  r4  rF  ry   r9   rB   rC   s   @r+   r  r    s   %N (,$ ".B-
 7K,;4C4M<U1T+K.J+7&+!% ##$)-*.;j/j/ j/ 	j/
 "#s(Oj/  S/j/ %*#s(Oj/  S/j/ #(S/j/ "'tSy!1j/  */tSy)9!j/" $D#I.#j/$ sCx%j/& !s+'j/( sCx)j/*  $+j/, -j/. /j/0 1j/2 3j/4 5j/6 7j/8 $'9j/: %(;j/< 
=j/ j/\ 15/34859489= q ( q  (} q %-SM	 q
 $,E? q #+5/ q (0 q 
 qD  ! %,,  37::,0:	"E*F$GG	H: :6 Y]))%-ell%;)QU)	}ell*	+)* X\--%-ell%;-QU-	}ell*	+- -@ %,, c ell  %,, c ell  %,, c ell 1ell 1u|| 1h RV:):)%-ell%;:)JN:)	}ell*	+:)x 9L > RV$)$)%-ell%;$)JN$)	}ell*	+$)R (,!& /3 u||$ 	
  EOO, 
u||U\\)	*r,   r  )'typingr   r   r   r4   torch.nnr$   configuration_utilsr   r   loadersr	   utils.accelerate_utilsr
   activationsr   
embeddingsr   modeling_outputsr   modeling_utilsr   normalizationr   vaer   r   Moduler   rE   r{   r   r   r   r   r   r   r   r   r,   r+   <module>r     s     * )   B - 8 ( B 2 ' # <0299 0fqBII qh.BII .b1")) 1hg")) gTmRYY mbP Pf{		 {|V		 VrY		 YxHJ5K Hr,   