
    
3jh              
          S SK r S SKrS SKJrJr  S SKrS SKJr  S SKJ	r	J
r
  SSKJrJr  SSKJr  SSKJrJr  SS	KJr  SS
KJr  SSKJr  SSKJrJrJr  SSKJr  SSKJ r   SSK!J"r"  \" 5       (       a  S SK#J$s  J%r&  Sr'OSr'\RP                  " \)5      r*Sr+S r,    SS\-S-  S\.\R^                  -  S-  S\0\-   S-  S\0\1   S-  4S jjr2 " S S\\5      r3g)    N)AnyCallable)Image)T5EncoderModelT5Tokenizer   )MultiPipelineCallbacksPipelineCallback)CogVideoXLoraLoaderMixin)AutoencoderKLCogVideoXCogVideoXTransformer3DModel)get_3d_rotary_pos_embed)DiffusionPipeline)KarrasDiffusionSchedulers)is_torch_xla_availableloggingreplace_example_docstring)randn_tensor)VideoProcessor   )CogVideoXPipelineOutputTFa  
    Examples:
        ```python
        >>> import torch
        >>> from diffusers import CogVideoXFunControlPipeline, DDIMScheduler
        >>> from diffusers.utils import export_to_video, load_video

        >>> pipe = CogVideoXFunControlPipeline.from_pretrained(
        ...     "alibaba-pai/CogVideoX-Fun-V1.1-5b-Pose", torch_dtype=torch.bfloat16
        ... )
        >>> pipe.scheduler = DDIMScheduler.from_config(pipe.scheduler.config)
        >>> pipe.to("cuda")

        >>> control_video = load_video(
        ...     "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/hiker.mp4"
        ... )
        >>> prompt = (
        ...     "An astronaut stands triumphantly at the peak of a towering mountain. Panorama of rugged peaks and "
        ...     "valleys. Very futuristic vibe and animated aesthetic. Highlights of purple and golden colors in "
        ...     "the scene. The sky is looks like an animated/cartoonish dream of galaxies, nebulae, stars, planets, "
        ...     "moons, but the remainder of the scene is mostly realistic."
        ... )

        >>> video = pipe(prompt=prompt, control_video=control_video).frames[0]
        >>> export_to_video(video, "output.mp4", fps=8)
        ```
c                    UnUnU u  pVXV-  nXtU-  :  a  Un[        [        XE-  U-  5      5      n	OUn	[        [        X6-  U-  5      5      n[        [        XH-
  S-  5      5      n
[        [        X9-
  S-  5      5      nX4X-   X-   44$ )Ng       @)intround)src	tgt_width
tgt_heighttwthhwrresize_heightresize_widthcrop_top	crop_lefts               u/home/wildlama/miniconda3/lib/python3.13/site-packages/diffusers/pipelines/cogvideo/pipeline_cogvideox_fun_control.pyget_resize_crop_region_for_gridr(   L   s    	B	BDA	AG}5!,-E"&1*-.5",345HE2,345I 8#;Y=U"VVV    num_inference_stepsdevice	timestepssigmasc                    Ub  Ub  [        S5      eUb  S[        [        R                  " U R                  5      R
                  R                  5       5      ;   nU(       d  [        SU R                   S35      eU R                  " S
X2S.UD6  U R                  n[        U5      nX14$ Ub  S[        [        R                  " U R                  5      R
                  R                  5       5      ;   nU(       d  [        SU R                   S35      eU R                  " S
XBS.UD6  U R                  n[        U5      nX14$ U R                  " U4S	U0UD6  U R                  nX14$ )a  
Calls the scheduler's `set_timesteps` method and retrieves timesteps from the scheduler after the call. Handles
custom timesteps. Any kwargs will be supplied to `scheduler.set_timesteps`.

Args:
    scheduler (`SchedulerMixin`):
        The scheduler to get timesteps from.
    num_inference_steps (`int`):
        The number of diffusion steps used when generating samples with a pre-trained model. If used, `timesteps`
        must be `None`.
    device (`str` or `torch.device`, *optional*):
        The device to which the timesteps should be moved to. If `None`, the timesteps are not moved.
    timesteps (`list[int]`, *optional*):
        Custom timesteps used to override the timestep spacing strategy of the scheduler. If `timesteps` is passed,
        `num_inference_steps` and `sigmas` must be `None`.
    sigmas (`list[float]`, *optional*):
        Custom sigmas used to override the timestep spacing strategy of the scheduler. If `sigmas` is passed,
        `num_inference_steps` and `timesteps` must be `None`.

Returns:
    `tuple[torch.Tensor, int]`: A tuple where the first element is the timestep schedule from the scheduler and the
    second element is the number of inference steps.
zYOnly one of `timesteps` or `sigmas` can be passed. Please choose one to set custom valuesr,   zThe current scheduler class zx's `set_timesteps` does not support custom timestep schedules. Please check whether you are using the correct scheduler.)r,   r+   r-   zv's `set_timesteps` does not support custom sigmas schedules. Please check whether you are using the correct scheduler.)r-   r+   r+    )

ValueErrorsetinspect	signatureset_timesteps
parameterskeys	__class__r,   len)	schedulerr*   r+   r,   r-   kwargsaccepts_timestepsaccept_sigmass           r'   retrieve_timestepsr=   _   s}   > !3tuu'3w/@/@AXAX/Y/d/d/i/i/k+ll .y/B/B.C Da b  	M)MfM''	!)n )) 
	 C(9(9):Q:Q(R(](](b(b(d$ee.y/B/B.C D_ `  	GvGG''	!)n )) 	 3MFMfM''	))r)   c            2       @  ^  \ rS rSrSr/ rSr/ SQrS\S\	S\
S\S	\4
U 4S
 jjr     SBS\\\   -  S\S\S\R$                  S-  S\R&                  S-  4
S jjr        SCS\\\   -  S\\\   -  S-  S\S\S\R,                  S-  S\R,                  S-  S\S\R$                  S-  S\R&                  S-  4S jjr SDS jr SES\R,                  S-  S\R,                  S-  S\\R,                  \R,                  4   4S jjrS\R,                  S\R,                  4S  jrS! r    SFS" jrSGS# jrSGS$ jrS%\S&\S'\S\R$                  S\\R,                  \R,                  4   4
S( jr \!S) 5       r"\!S* 5       r#\!S+ 5       r$\!S, 5       r%\!S- 5       r&\RN                  " 5       \(" \)5      SSSSSS.SS/S0SS1SSSSSS2SSSS/S4S\\\   -  S-  S\\\   -  S-  S3\\*RT                     S-  S%\S-  S&\S-  S4\S5\\   S-  S6\+S7\S\S8\+S9\RX                  \\RX                     -  S-  S\R,                  S-  S:\R,                  S-  S\R,                  S-  S\R,                  S-  S;\S<\S=\-\\.4   S-  S>\/\\/S4   \0-  \1-  S-  S?\\   S\S\2\-  4.S@ jj5       5       r3SAr4U =r5$ )HCogVideoXFunControlPipeline   a  
Pipeline for controlled text-to-video generation using CogVideoX Fun.

This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods the
library implements for all the pipelines (such as downloading or saving, running on a particular device, etc.)

Args:
    vae ([`AutoencoderKL`]):
        Variational Auto-Encoder (VAE) Model to encode and decode videos to and from latent representations.
    text_encoder ([`T5EncoderModel`]):
        Frozen text-encoder. CogVideoX uses
        [T5](https://huggingface.co/docs/transformers/model_doc/t5#transformers.T5EncoderModel); specifically the
        [t5-v1_1-xxl](https://huggingface.co/PixArt-alpha/PixArt-alpha/tree/main/t5-v1_1-xxl) variant.
    tokenizer (`T5Tokenizer`):
        Tokenizer of class
        [T5Tokenizer](https://huggingface.co/docs/transformers/model_doc/t5#transformers.T5Tokenizer).
    transformer ([`CogVideoXTransformer3DModel`]):
        A text conditioned `CogVideoXTransformer3DModel` to denoise the encoded video latents.
    scheduler ([`SchedulerMixin`]):
        A scheduler to be used in combination with `transformer` to denoise the encoded video latents.
z#text_encoder->vae->transformer->vae)latentsprompt_embedsnegative_prompt_embeds	tokenizertext_encodervaetransformerr9   c                   > [         TU ]  5         U R                  XX4US9  [        U SS 5      (       a/  S[	        U R
                  R                  R                  5      S-
  -  OSU l        [        U SS 5      (       a   U R
                  R                  R                  OSU l
        [        U SS 5      (       a   U R
                  R                  R                  OSU l        [        U R                  S9U l        g )	N)rD   rE   rF   rG   r9   rF      r         gffffff?)vae_scale_factor)super__init__register_modulesgetattrr8   rF   configblock_out_channelsvae_scale_factor_spatialtemporal_compression_ratiovae_scale_factor_temporalscaling_factorvae_scaling_factor_imager   video_processor)selfrD   rE   rF   rG   r9   r7   s         r'   rN   $CogVideoXFunControlPipeline.__init__   s     	hq 	 	
 CJ$PUW[B\B\A#dhhoo889A=>bc 	% ;B$t:T:TDHHOO66Z[ 	& KRRVX]_cJdJd(F(Fjm%-t?\?\]r)   Nr      promptnum_videos_per_promptmax_sequence_lengthr+   dtypec           	         U=(       d    U R                   nU=(       d    U R                  R                  n[        U[        5      (       a  U/OUn[        U5      nU R                  USUSSSS9nUR                  nU R                  USSS9R                  n	U	R                  S   UR                  S   :  a]  [        R                  " X5      (       dB  U R                  R                  U	S S 2US-
  S24   5      n
[        R                  S	U S
U
 35        U R                  UR                  U5      5      S   nUR                  XTS9nUR                  u  pnUR                  SUS5      nUR!                  Xb-  US5      nU$ )N
max_lengthTpt)paddingra   
truncationadd_special_tokensreturn_tensorslongest)rc   rf   r   zXThe following part of your input was truncated because `max_sequence_length` is set to  z	 tokens: r   )r_   r+   )_execution_devicerE   r_   
isinstancestrr8   rD   	input_idsshapetorchequalbatch_decodeloggerwarningtorepeatview)rY   r\   r]   r^   r+   r_   
batch_sizetext_inputstext_input_idsuntruncated_idsremoved_textrB   _seq_lens                 r'   _get_t5_prompt_embeds1CogVideoXFunControlPipeline._get_t5_prompt_embeds   s    14110**00'44&&[
nn *# % 
 %....SW.Xbb  $(<(<R(@@UcIuIu>>66qJ]`aJadfJfGf7ghLNN'(	,A
 )).*;*;F*CDQG%((u(D &++A%,,Q0EqI%**:+MwXZ[r)   Tnegative_promptdo_classifier_free_guidancerB   rC   c
                 2   U=(       d    U R                   n[        U[        5      (       a  U/OUnUb  [        U5      n
OUR                  S   n
Uc  U R                  UUUUU	S9nU(       a  Uc  U=(       d    Sn[        U[        5      (       a  X/-  OUnUb;  [        U5      [        U5      La$  [        S[        U5       S[        U5       S35      eU
[        U5      :w  a!  [        SU S[        U5       S	U SU
 S
3	5      eU R                  UUUUU	S9nXV4$ )ab  
Encodes the prompt into text encoder hidden states.

Args:
    prompt (`str` or `list[str]`, *optional*):
        prompt to be encoded
    negative_prompt (`str` or `list[str]`, *optional*):
        The prompt or prompts not to guide the image generation. If not defined, one has to pass
        `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
        less than `1`).
    do_classifier_free_guidance (`bool`, *optional*, defaults to `True`):
        Whether to use classifier free guidance or not.
    num_videos_per_prompt (`int`, *optional*, defaults to 1):
        Number of videos that should be generated per prompt. torch device to place the resulting embeddings on
    prompt_embeds (`torch.Tensor`, *optional*):
        Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
        provided, text embeddings will be generated from `prompt` input argument.
    negative_prompt_embeds (`torch.Tensor`, *optional*):
        Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
        weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
        argument.
    device: (`torch.device`, *optional*):
        torch device
    dtype: (`torch.dtype`, *optional*):
        torch dtype
r   )r\   r]   r^   r+   r_    z?`negative_prompt` should be the same type to `prompt`, but got z != .z`negative_prompt`: z has batch size z, but `prompt`: zT. Please make sure that passed `negative_prompt` matches the batch size of `prompt`.)	ri   rj   rk   r8   rm   r}   type	TypeErrorr0   )rY   r\   r   r   r]   rB   rC   r^   r+   r_   rv   s              r'   encode_prompt)CogVideoXFunControlPipeline.encode_prompt   sk   L 1411'44&&VJ&,,Q/J  66&;$7 7 M '+A+I-3O@J?\_@`@`j+<<fuO!d6l$:O&OUVZ[jVkUl mV~Q(  s?33 )/)::J3K_J` ax/
| <33  &*%?%?&&;$7 &@ &" 44r)   c
                 V   [        U[        5      (       a*  [        U5      U:w  a  [        S[        U5       SU S35      eUUS-
  U R                  -  S-   UX@R
                  -  XPR
                  -  4n
U	c  [        XXvS9n	OU	R                  U5      n	XR                  R                  -  n	U	$ )Nz/You have passed a list of generators of length z+, but requested an effective batch size of z@. Make sure the batch size matches the length of the generators.r   )	generatorr+   r_   )
rj   listr8   r0   rU   rS   r   rs   r9   init_noise_sigma)rY   rv   num_channels_latents
num_framesheightwidthr_   r+   r   rA   rm   s              r'   prepare_latents+CogVideoXFunControlPipeline.prepare_latentsO  s     i&&3y>Z+GA#i.AQ R&<'gi  !^ > >>B 333222
 ?"5fZGjj(G NN;;;r)   maskmasked_imagereturnc                    Ub  / n[        UR                  S5      5       HU  nX   R                  S5      nU R                  R	                  U5      S   nUR                  5       nUR                  U5        MW     [        R                  " USS9nXR                  R                  R                  -  nUb  / n[        UR                  S5      5       HU  nX$   R                  S5      nU R                  R	                  U5      S   nUR                  5       nUR                  U5        MW     [        R                  " USS9nXR                  R                  R                  -  nX4$ S nX4$ )Nr   dim)rangesize	unsqueezerF   encodemodeappendrn   catrQ   rV   )	rY   r   r   masksicurrent_maskmask_pixel_valuesmask_pixel_valuemasked_image_latentss	            r'   prepare_control_latents3CogVideoXFunControlPipeline.prepare_control_latentsj  sH    E499Q<(#w003#xx|<Q?+002\*	 )
 99U*D((//888D# "<,,Q/0#/?#<#<Q#? #'88??3C#DQ#G #3#8#8#: !(()9:	 1
 $)99->A#F #7((//:X:X#X  )) $( ))r)   rA   c                     UR                  SSSSS5      nSU R                  -  U-  nU R                  R                  U5      R                  nU$ )Nr   rI   r   r   rK   )permuterW   rF   decodesample)rY   rA   framess      r'   decode_latents*CogVideoXFunControlPipeline.decode_latents  sJ    //!Q1a0d333g=)00r)   c                 n   S[        [        R                  " U R                  R                  5      R
                  R                  5       5      ;   n0 nU(       a  X$S'   S[        [        R                  " U R                  R                  5      R
                  R                  5       5      ;   nU(       a  XS'   U$ )Netar   )r1   r2   r3   r9   stepr5   r6   )rY   r   r   accepts_etaextra_step_kwargsaccepts_generators         r'   prepare_extra_step_kwargs5CogVideoXFunControlPipeline.prepare_extra_step_kwargs  s     s7#4#4T^^5H5H#I#T#T#Y#Y#[\\'*e$ (3w/@/@ATAT/U/`/`/e/e/g+hh-6k*  r)   c
           
        ^  US-  S:w  d	  US-  S:w  a  [        SU SU S35      eUbW  [        U 4S jU 5       5      (       d=  [        ST R                   SU V
s/ s H  oT R                  ;  d  M  U
PM     sn
 35      eUb  Ub  [        S	U S
U S35      eUc  Uc  [        S5      eUbA  [        U[        5      (       d,  [        U[
        5      (       d  [        S[        U5       35      eUb  Ub  [        S	U SU S35      eUb  Ub  [        SU SU S35      eUbC  Ub@  UR                  UR                  :w  a&  [        SUR                   SUR                   S35      eUb  U	b  [        S5      eg g s  sn
f )NrJ   r   z7`height` and `width` have to be divisible by 8 but are z and r   c              3   @   >#    U  H  oTR                   ;   v   M     g 7fN)_callback_tensor_inputs).0krY   s     r'   	<genexpr>;CogVideoXFunControlPipeline.check_inputs.<locals>.<genexpr>  s      F
7Y!---7Ys   z2`callback_on_step_end_tensor_inputs` has to be in z, but found zCannot forward both `prompt`: z and `prompt_embeds`: z2. Please make sure to only forward one of the two.zeProvide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined.z2`prompt` has to be of type `str` or `list` but is z and `negative_prompt_embeds`: z'Cannot forward both `negative_prompt`: zu`prompt_embeds` and `negative_prompt_embeds` must have the same shape when passed directly, but got: `prompt_embeds` z != `negative_prompt_embeds` ztCannot pass both `control_video` and `control_video_latents`. Please make sure to pass only one of these parameters.)r0   allr   rj   rk   r   r   rm   )rY   r\   r   r   r   "callback_on_step_end_tensor_inputsrB   rC   control_videocontrol_video_latentsr   s   `          r'   check_inputs(CogVideoXFunControlPipeline.check_inputs  sU    A:?eai1nVW]V^^cdicjjklmm-9# F
7YF
 C
 C
 DTEaEaDbbn  |^  pH  |^vw  ko  kG  kG  bGpq  |^  pH  oI  J  -";08N}o ^0 0  ^ 5w  FC)@)@TZ\`IaIaQRVW]R^Q_`aa"8"D0 9*++]_ 
 &+A+M9/9J K*++]_ 
 $)?)K""&<&B&BB --:-@-@,A B.445Q8  $)>)J G  *K$E pHs   E61E6c                 F    SU l         U R                  R                  5         g)zEnables fused QKV projections.TN)fusing_transformerrG   fuse_qkv_projectionsrY   s    r'   r   0CogVideoXFunControlPipeline.fuse_qkv_projections  s    "&--/r)   c                     U R                   (       d  [        R                  S5        gU R                  R	                  5         SU l         g)z)Disable QKV projection fusion if enabled.zKThe Transformer was not initially fused for QKV projections. Doing nothing.FN)r   rq   rr   rG   unfuse_qkv_projectionsr   s    r'   r   2CogVideoXFunControlPipeline.unfuse_qkv_projections  s2    &&NNhi335&+D#r)   r   r   r   c           
         XR                   U R                  R                  R                  -  -  nX R                   U R                  R                  R                  -  -  nU R                  R                  R                  nU R                  R                  R                  nU R                  R                  R
                  U-  n	U R                  R                  R                  U-  n
Uc>  [        XV4X5      n[        U R                  R                  R                  UXV4UUS9u  pX4$ X8-   S-
  U-  n[        U R                  R                  R                  S XV4USX4US9u  pX4$ )N)	embed_dimcrops_coords	grid_sizetemporal_sizer+   r   slice)r   r   r   r   	grid_typemax_sizer+   )
rS   rG   rQ   
patch_sizepatch_size_tsample_widthsample_heightr(   r   attention_head_dim)rY   r   r   r   r+   grid_height
grid_widthpp_tbase_size_widthbase_size_heightgrid_crops_coords	freqs_cos	freqs_sinbase_num_framess                  r'   %_prepare_rotary_positional_embeddingsACogVideoXFunControlPipeline._prepare_rotary_positional_embeddings  sd    !>!>AQAQAXAXAcAc!cd<<t?O?O?V?V?a?aab
##..%%22**11>>!C++22@@AE; ?)?! $;**11DD.&3($ I* ##  */!3;O#:**11DD!&3-!*<$ I ##r)   c                     U R                   $ r   )_guidance_scaler   s    r'   guidance_scale*CogVideoXFunControlPipeline.guidance_scale  s    ###r)   c                     U R                   $ r   )_num_timestepsr   s    r'   num_timesteps)CogVideoXFunControlPipeline.num_timesteps  s    """r)   c                     U R                   $ r   )_attention_kwargsr   s    r'   attention_kwargs,CogVideoXFunControlPipeline.attention_kwargs      %%%r)   c                     U R                   $ r   )_current_timestepr   s    r'   current_timestep,CogVideoXFunControlPipeline.current_timestep  r   r)   c                     U R                   $ r   )
_interruptr   s    r'   	interrupt%CogVideoXFunControlPipeline.interrupt#  s    r)   2      Fg        pilr   r*   r,   r   use_dynamic_cfgr   r   r   output_typereturn_dictr   callback_on_step_endr   c                 Z   [        U[        [        45      (       a  UR                  nUb%  [        US   [        R                  5      (       a  U/nU=(       d-    U R
                  R                  R                  U R                  -  nU=(       d-    U R
                  R                  R                  U R                  -  nUb  [        US   5      OUR                  S5      nSn
U R                  UUUUUUUUU5	        Xl        UU l        SU l        SU l        Ub  [        U["        5      (       a  SnO3Ub!  [        U[$        5      (       a  [        U5      nOUR&                  S   nU R(                  nUS:  nU R+                  UUUU
UUUUS9u  nnU(       a  [,        R.                  " UU/SS9n[0        (       a  S	nOUn[3        U R4                  UUU5      u  pv[        U5      U l        US-
  U R8                  -  S-   nU R
                  R                  R:                  nUb  UU-  S:w  a  [=        S
U< SU< S35      eU R
                  R                  R>                  S-  nU RA                  UU
-  UUUUURB                  UUU5	      nUc4  U RD                  RG                  X4US9nURI                  UURB                  S9nU RK                  SU5      u  nnURM                  SSSSS5      nU RO                  X5      n U R
                  R                  RP                  (       a"  U RS                  XEUR                  S5      U5      OSn![U        [        U5      X`R4                  RV                  -  -
  S5      n"U RY                  US9 n#Sn$[[        U5       GH  u  n%n&U R\                  (       a  M  U&U l        U(       a  [,        R.                  " U/S-  5      OUn'U R4                  R_                  U'U&5      n'U(       a  [,        R.                  " U/S-  5      OUn([,        R.                  " U'U(/SS9n'U&Ra                  U'R&                  S   5      n)U R
                  Rc                  S5         U R                  U'UU)U!USS9S   n*SSS5        W*Re                  5       n*U	(       aO  SUS[f        Rh                  " [f        Rj                  UU&Rm                  5       -
  U-  S-  -  5      -
  S-  -  -   U l        U(       a)  U*Ro                  S5      u  n+n,U+U Rp                  U,U+-
  -  -   n*U R4                  Rr                  " U*U&U40 U DSS0D6S   nURI                  URB                  5      nUb\  0 n-U H  n.[u        5       U.   U-U.'   M     U" U U%U&U-5      n/U/Rw                  SU5      nU/Rw                  SU5      nU/Rw                  SU5      nU%[        U5      S-
  :X  d)  U%S-   U":  a0  U%S-   U R4                  RV                  -  S:X  a  U#Ry                  5         [0        (       d  GM  [z        R|                  " 5         GM     SSS5        SU l        US:X  d,  U R                  U5      n0U RD                  R                  U0US9n0OUn0U R                  5         U(       d  U04$ [        U0S9$ ! , (       d  f       GN= f! , (       d  f       N~= f)aJ  
Function invoked when calling the pipeline for generation.

Args:
    prompt (`str` or `list[str]`, *optional*):
        The prompt or prompts to guide the image generation. If not defined, one has to pass `prompt_embeds`.
        instead.
    negative_prompt (`str` or `list[str]`, *optional*):
        The prompt or prompts not to guide the image generation. If not defined, one has to pass
        `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
        less than `1`).
    control_video (`list[PIL.Image.Image]`):
        The control video to condition the generation on. Must be a list of images/frames of the video. If not
        provided, `control_video_latents` must be provided.
    height (`int`, *optional*, defaults to self.transformer.config.sample_height * self.vae_scale_factor_spatial):
        The height in pixels of the generated image. This is set to 480 by default for the best results.
    width (`int`, *optional*, defaults to self.transformer.config.sample_height * self.vae_scale_factor_spatial):
        The width in pixels of the generated image. This is set to 720 by default for the best results.
    num_inference_steps (`int`, *optional*, defaults to 50):
        The number of denoising steps. More denoising steps usually lead to a higher quality image at the
        expense of slower inference.
    timesteps (`list[int]`, *optional*):
        Custom timesteps to use for the denoising process with schedulers which support a `timesteps` argument
        in their `set_timesteps` method. If not defined, the default behavior when `num_inference_steps` is
        passed will be used. Must be in descending order.
    guidance_scale (`float`, *optional*, defaults to 6.0):
        Guidance scale as defined in [Classifier-Free Diffusion
        Guidance](https://huggingface.co/papers/2207.12598). `guidance_scale` is defined as `w` of equation 2.
        of [Imagen Paper](https://huggingface.co/papers/2205.11487). Guidance scale is enabled by setting
        `guidance_scale > 1`. Higher guidance scale encourages to generate images that are closely linked to
        the text `prompt`, usually at the expense of lower image quality.
    num_videos_per_prompt (`int`, *optional*, defaults to 1):
        The number of videos to generate per prompt.
    generator (`torch.Generator` or `list[torch.Generator]`, *optional*):
        One or a list of [torch generator(s)](https://pytorch.org/docs/stable/generated/torch.Generator.html)
        to make generation deterministic.
    latents (`torch.Tensor`, *optional*):
        Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for video
        generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
        tensor will be generated by sampling using the supplied random `generator`.
    control_video_latents (`torch.Tensor`, *optional*):
        Pre-generated control latents, sampled from a Gaussian distribution, to be used as inputs for
        controlled video generation. If not provided, `control_video` must be provided.
    prompt_embeds (`torch.Tensor`, *optional*):
        Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
        provided, text embeddings will be generated from `prompt` input argument.
    negative_prompt_embeds (`torch.Tensor`, *optional*):
        Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
        weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
        argument.
    output_type (`str`, *optional*, defaults to `"pil"`):
        The output format of the generate image. Choose between
        [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.
    return_dict (`bool`, *optional*, defaults to `True`):
        Whether or not to return a [`~pipelines.stable_diffusion_xl.StableDiffusionXLPipelineOutput`] instead
        of a plain tuple.
    attention_kwargs (`dict`, *optional*):
        A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under
        `self.processor` in
        [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
    callback_on_step_end (`Callable`, *optional*):
        A function that calls at the end of each denoising steps during the inference. The function is called
        with the following arguments: `callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int,
        callback_kwargs: Dict)`. `callback_kwargs` will include a list of all tensors as specified by
        `callback_on_step_end_tensor_inputs`.
    callback_on_step_end_tensor_inputs (`list`, *optional*):
        The list of tensor inputs for the `callback_on_step_end` function. The tensors specified in the list
        will be passed as `callback_kwargs` argument. You will only be able to include variables listed in the
        `._callback_tensor_inputs` attribute of your pipeline class.
    max_sequence_length (`int`, defaults to `226`):
        Maximum sequence length in encoded prompt. Must be consistent with
        `self.transformer.config.max_text_seq_length` otherwise may lead to poor results.

Examples:

Returns:
    [`~pipelines.cogvideo.pipeline_cogvideox.CogVideoXPipelineOutput`] or `tuple`:
    [`~pipelines.cogvideo.pipeline_cogvideox.CogVideoXPipelineOutput`] if `return_dict` is True, otherwise a
    `tuple`. When returning a tuple, the first element is a list with the generated images.
Nr   rI   r   Fg      ?)r]   rB   rC   r^   r+   r   cpuz?The number of latent frames must be divisible by `patch_size_t=z-` but the given video contains latent_frames=z, which is not divisible.)r   r   )r+   r_   r   rK   )totalcond_uncond)hidden_statesencoder_hidden_statestimestepimage_rotary_embr   r   g      @r   rA   rB   rC   latent)videor   )r   )Crj   r
   r	   tensor_inputsr   rG   rQ   r   rS   r   r8   r   r   r   r   r   r   rk   r   rm   ri   r   rn   r   XLA_AVAILABLEr=   r9   r   rU   r   r0   in_channelsr   r_   rX   preprocess_videors   r   r   r    use_rotary_positional_embeddingsr   maxorderprogress_bar	enumerater   scale_model_inputexpandcache_contextfloatmathcospiitemchunkr   r   localspopupdatexm	mark_stepr   postprocess_videomaybe_free_model_hooksr   )1rY   r\   r   r   r   r   r*   r,   r   r   r]   r   r   rA   r   rB   rC   r   r   r   r   r   r^   r   rv   r+   r   timestep_devicelatent_framesr   latent_channelsr{   r   r  num_warmup_stepsr  old_pred_original_sampler   tlatent_model_inputlatent_control_inputr  
noise_prednoise_pred_uncondnoise_pred_textcallback_kwargsr   callback_outputsr
  s1                                                    r'   __call__$CogVideoXFunControlPipeline.__call__'  s   X *-=?U,VWW1E1S1S.$M!4Dekk)R)R*OM`4++22@@4C`C``]))00==@]@]].;.GSq)*MbMgMghiMj
 ! 	."!
	
  .!1!% *VS"9"9JJvt$<$<VJ&,,Q/J''
 '5s&:# 150B0B'"7'#9 3 1C 	1
-- '!II'=}&MSTUM =#O$O);NN/)*
&	 ")n $aD,J,JJQN ''..;;#(D(IR\O T+)++DF 
 **11==B&&..

 !( 00AA-fkAlM),,F-BUBU,VM#'#?#?m#T   5 = =aAq! L !::9J
 &&GG 66vgllSToW]^ 	 s9~0CnnFZFZ0ZZ\]^%89\'+$!),1>>)*&A\UYYy1}%=bi"%)^^%E%EFXZ[%\" ?ZEII459:_t % &+YY0BDX/Y_`%a" 88$6$<$<Q$?@ %%33MB!%!1!1&8.;!))9)9$) "2 " "J C (--/
 #+,~TXXdgg2E2PTg1glo0o&opptuu0 ,D( /9C9I9I!9L6%!2T5H5HO^oLo5p!pJ ..--j!WmHYmglmnop!**]%8%89 (3&(O?-3Xa[* @';D!Q'X$.229gFG$4$8$8-$XM-=-A-ABZ\r-s*I**A9I/IqSTuX\XfXfXlXlNlpqNq '') =LLNq - :z "&h&''0E((::T_:`EE 	##%8O&e44o CB) :9s,   :C!ZZ
3FZ
Z

ZZ
Z*)
r   r   r   r   r   r   rS   rU   rW   rX   )Nr   r[   NN)NTr   NNr[   NNr   )NNNNNN)r   N)6__name__
__module____qualname____firstlineno____doc___optional_componentsmodel_cpu_offload_seqr   r   r   r   r   r   rN   rk   r   r   rn   r+   r_   r}   boolTensorr   r   tupler   r   r   r   r   r   r   propertyr   r   r   r   r   no_gradr   EXAMPLE_DOC_STRINGr   r  	Generatordictr   r   r
   r	   r   r1  __static_attributes____classcell__)r7   s   @r'   r?   r?      s   , A^^ %^ $	^
 1^ -^4 #'%&#&&*$((d3i(  #( !	(
 t#( {{T!(\ 37,0%&-16:#&&*$(O5d3iO5 tCy4/O5 &*	O5
  #O5 ||d*O5 !&t 3O5 !O5 t#O5 {{T!O5f nr8 UY*LL4'*>CllT>Q*	u||U\\)	**8ell u|| !0 #"8t0
,*$*$ *$ 	*$
 *$ 
u||U\\)	**$X $ $ # # & & & &   ]]_12 *.2626! #%&* ! %%&DH'+59-16:  26nr9B#&/e5d3i$&e5 tCy4/e5 EKK(4/	e5
 d
e5 Tze5 !e5 9t#e5 e5 e5  #e5 e5 ??T%//%::TAe5 $e5  %||d2e5  ||d*!e5" !&t 3#e5$ %e5& 'e5( sCx.4/)e5* 'Sz4'78;KKNddgkk+e5, -1I-e5. !/e50 
!5	(1e5 3 e5r)   r?   r3  )4r2   r  typingr   r   rn   PILr   transformersr   r   	callbacksr	   r
   loadersr   modelsr   r   models.embeddingsr   pipelines.pipeline_utilsr   
schedulersr   utilsr   r   r   utils.torch_utilsr   rX   r   pipeline_outputr   torch_xla.core.xla_modelcore	xla_modelr   r  
get_loggerr4  rq   r@  r(   r   rk   r+   r   r  r=   r?   r/   r)   r'   <module>rU     s           4 A / I 8 9 3 O O - - 4 ))MM			H	% <W* '+(,"&!%8*t8* %,,%8* Cy4	8*
 K$8*vt
5"35M t
5r)   