
    bik                        d dl Z d dlmZmZmZmZmZmZ d dlZ	d dl
Z
d dlmZmZ ddlmZmZ ddlmZ ddlmZmZ ddlmZ dd	lmZmZmZ dd
lmZ ddlmZ ddl m!Z! ddl"m#Z#  e       rd dl$m%c m&Z' dZ(ndZ( ejR                  e*      Z+dZ,ddZ-	 	 	 	 ddee.   deee/e
j`                  f      deee.      deee1      fdZ2 G d de!e      Z3y)    N)AnyCallableDictListOptionalUnion)T5EncoderModelT5TokenizerFast   )MultiPipelineCallbacksPipelineCallback)Mochi1LoraLoaderMixin)AutoencoderKLMochiMochiTransformer3DModel)FlowMatchEulerDiscreteScheduler)is_torch_xla_availableloggingreplace_example_docstring)randn_tensor)VideoProcessor   )DiffusionPipeline   )MochiPipelineOutputTFa_  
    Examples:
        ```py
        >>> import torch
        >>> from diffusers import MochiPipeline
        >>> from diffusers.utils import export_to_video

        >>> pipe = MochiPipeline.from_pretrained("genmo/mochi-1-preview", torch_dtype=torch.bfloat16)
        >>> pipe.enable_model_cpu_offload()
        >>> pipe.enable_vae_tiling()
        >>> prompt = "Close-up of a chameleon's eye, with its scaly skin changing color. Ultra high resolution 4k."
        >>> frames = pipe(prompt, num_inference_steps=28, guidance_scale=3.5).frames[0]
        >>> export_to_video(frames, "mochi.mp4")
        ```
c                 N   || dz  }t        |      D cg c]
  }||z  |z   }}||| z  z
  }| |z
  }|||dz  z  z  }||z  d|z  |dz  z  z
  }||dz  z  }	t        ||       D cg c]  }||dz  z  ||z  z   |	z    }
}||
z   }|D cg c]  }d|z
  	 }}|S c c}w c c}w c c}w )Nr         ?)range)	num_stepsthreshold_noiselinear_stepsilinear_sigma_schedulethreshold_noise_step_diffquadratic_stepsquadratic_coeflinear_coefconstquadratic_sigma_schedulesigma_schedulexs                c/home/cdr/jupyterlab/.venv/lib/python3.12/site-packages/diffusers/pipelines/mochi/pipeline_mochi.pylinear_quadratic_scheduler,   A   s    A~IN|I\]AQ0<?]] ,/J J,.O.,RSAS2STN!L017P3PTcefTf3ggKlAo.ECHW`Ca >?!Q$+/1E9    +-EEN'56!cAg6N6 ^  7s   B%BB"num_inference_stepsdevice	timestepssigmasc                    ||t        d      |dt        t        j                  | j                        j
                  j                               v }|st        d| j                   d       | j                  d
||d| | j                  }t        |      }||fS |dt        t        j                  | j                        j
                  j                               v }|st        d| j                   d       | j                  d
||d| | j                  }t        |      }||fS  | j                  |fd	|i| | j                  }||fS )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.   r0   zv's `set_timesteps` does not support custom sigmas schedules. Please check whether you are using the correct scheduler.)r0   r.   r.    )

ValueErrorsetinspect	signatureset_timesteps
parameterskeys	__class__r/   len)	schedulerr-   r.   r/   r0   kwargsaccepts_timestepsaccept_sigmass           r+   retrieve_timestepsr@   S   s   > !3tuu'3w/@/@AXAX/Y/d/d/i/i/k+ll .y/B/B.C Da b  	 	M)FMfM''	!)n ))) 
	 C(9(9):Q:Q(R(](](b(b(d$ee.y/B/B.C D_ `  	 	GvfGG''	!)n ))) 	 	 3MFMfM''	)))    c            -       T    e Zd ZdZdZg Zg dZ	 d:dedede	de
ded	ef fd
Z	 	 	 	 	 d;deeee   f   dededeej(                     deej*                     f
dZ	 	 	 	 	 	 	 	 	 	 d<deeee   f   deeeee   f      dededeej.                     deej.                     deej.                     deej.                     dedeej(                     deej*                     fdZ	 	 	 	 	 d=dZd Zd Zd Zd  Z	 d>d!Zed"        Z ed#        Z!ed$        Z"ed%        Z#ed&        Z$ed'        Z% ejL                          e'e(      ddddd(d)dd*dddddddd+dddd,gdfdeeee   f   deeeee   f      d-ee   d.ee   d/ed0ed1ee   d2e)dee   d3eeejT                  eejT                     f      d,eej.                     deej.                     deej.                     deej.                     deej.                     d4ee   d5ed6ee+ee,f      d7ee-eee+gdf      d8ee   def*d9              Z. xZ/S )?MochiPipelinea  
    The mochi pipeline for text-to-video generation.

    Reference: https://github.com/genmoai/models

    Args:
        transformer ([`MochiTransformer3DModel`]):
            Conditional Transformer architecture to denoise the encoded video latents.
        scheduler ([`FlowMatchEulerDiscreteScheduler`]):
            A scheduler to be used in combination with `transformer` to denoise the encoded image latents.
        vae ([`AutoencoderKLMochi`]):
            Variational Auto-Encoder (VAE) Model to encode and decode videos to and from latent representations.
        text_encoder ([`T5EncoderModel`]):
            [T5](https://huggingface.co/docs/transformers/en/model_doc/t5#transformers.T5EncoderModel), specifically
            the [google/t5-v1_1-xxl](https://huggingface.co/google/t5-v1_1-xxl) variant.
        tokenizer (`CLIPTokenizer`):
            Tokenizer of class
            [CLIPTokenizer](https://huggingface.co/docs/transformers/en/model_doc/clip#transformers.CLIPTokenizer).
        tokenizer (`T5TokenizerFast`):
            Second Tokenizer of class
            [T5TokenizerFast](https://huggingface.co/docs/transformers/en/model_doc/t5#transformers.T5TokenizerFast).
    ztext_encoder->transformer->vae)latentsprompt_embedsnegative_prompt_embedsr<   vaetext_encoder	tokenizertransformerforce_zeros_for_empty_promptc                 X   t         |           | j                  |||||       d| _        d| _        d| _        t        | j                        | _        t        | d      r"| j                  | j                  j                  nd| _        d| _        d	| _        | j                  |
       y )N)rG   rH   rI   rJ   r<         r   )vae_scale_factorrI      i  iP  )rK   )super__init__register_modulesvae_spatial_scale_factorvae_temporal_scale_factor
patch_sizer   video_processorhasattrrI   model_max_lengthtokenizer_max_lengthdefault_heightdefault_widthregister_to_config)selfr<   rG   rH   rI   rJ   rK   r:   s          r+   rR   zMochiPipeline.__init__   s     	%# 	 	
 )*%)*&-t?\?\]/6t[/IdnnNhDNN++nq 	! " =YZrA   Nr   rP   promptnum_videos_per_promptmax_sequence_lengthr.   dtypec                 N   |xs | j                   }|xs | j                  j                  }t        |t              r|gn|}t        |      }| j                  |d|ddd      }|j                  }|j                  }	|	j                         j                  |      }	| j                  j                  rJ|dk(  s|d   dk(  r=t        j                  ||      }t        j                  |	t        j                  |      }	| j                  |d	d
      j                  }
|
j                  d   |j                  d   k\  rXt        j                   ||
      sB| j                  j#                  |
d d |dz
  df         }t$        j'                  d| d|        | j                  |j                  |      |	      d   }|j                  ||      }|j                  \  }}}|j)                  d|d      }|j+                  ||z  |d      }|	j+                  |d      }	|	j)                  |d      }	||	fS )N
max_lengthTpt)paddingrd   
truncationadd_special_tokensreturn_tensors )r.   )rb   r.   longest)rf   ri   r   zXThe following part of your input was truncated because `max_sequence_length` is set to  z	 tokens: )attention_maskr   )_execution_devicerH   rb   
isinstancestrr;   rI   	input_idsrm   booltoconfigrK   torch
zeros_likeshapeequalbatch_decodeloggerwarningrepeatview)r^   r_   r`   ra   r.   rb   
batch_sizetext_inputstext_input_idsprompt_attention_maskuntruncated_idsremoved_textrE   _seq_lens                  r+   _get_t5_prompt_embedsz#MochiPipeline._get_t5_prompt_embeds   s:    14110**00'4&&[
nn *# % 
 %.. + : : 5 : : < ? ? G
 ;;332PRWYIY"--nVLN$)$4$45JRWR\R\ek$l!..SW.Xbb  $(<(<R(@@UcetIu>>66qJ]`aJadfJfGf7ghLNN'(	,A
 )).*;*;F*CTi)jklm%((uV(D &++7A%,,Q0EqI%**:8M+MwXZ[ 5 : ::r J 5 < <=RTU V333rA   Tnegative_promptdo_classifier_free_guidancerE   rF   r   negative_prompt_attention_maskc                    |
xs | j                   }
t        |t              r|gn|}|t        |      }n|j                  d   }|| j                  |||	|
|      \  }}|r||xs d}t        |t              r||gz  n|}|:t        |      t        |      ur$t        dt        |       dt        |       d      |t        |      k7  r!t        d| dt        |       d	| d| d
	      | j                  |||	|
|      \  }}||||fS )a"  
        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`   ra   r.   rb   rj   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`.)	rn   ro   rp   r;   rw   r   type	TypeErrorr3   )r^   r_   r   r   r`   rE   rF   r   r   ra   r.   rb   r~   s                r+   encode_promptzMochiPipeline.encode_prompt  s   P 1411'4&&VJ&,,Q/J 373M3M&;$7 4N 40M0 '+A+I-3O@J?\_@`jO+<<fuO!d6l$:O&OUVZ[jVkUl mV~Q(  s?33 )/)::J3K_J` ax/
| <33  FJE_E_&&;$7 F` FB"$B 35KMkkkrA   c	           
          |dz  dk7  s|dz  dk7  rt        d| d| d      |Lt         fd|D              s8t        d j                   d|D 	cg c]  }	|	 j                  vs|	 c}	       ||t        d	| d
| d      ||t        d      |7t        |t              s't        |t
              st        dt        |             ||t        d      ||t        d      |||j                  |j                  k7  r&t        d|j                   d|j                   d      |j                  |j                  k7  r&t        d|j                   d|j                   d      y y y c c}	w )NrM   r   z7`height` and `width` have to be divisible by 8 but are z and r   c              3   :   K   | ]  }|j                   v   y wN)_callback_tensor_inputs).0kr^   s     r+   	<genexpr>z-MochiPipeline.check_inputs.<locals>.<genexpr>c  s#      F
23A---F
s   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 zEMust provide `prompt_attention_mask` when specifying `prompt_embeds`.zWMust provide `negative_prompt_attention_mask` when specifying `negative_prompt_embeds`.zu`prompt_embeds` and `negative_prompt_embeds` must have the same shape when passed directly, but got: `prompt_embeds` z != `negative_prompt_embeds` z`prompt_attention_mask` and `negative_prompt_attention_mask` must have the same shape when passed directly, but got: `prompt_attention_mask` z% != `negative_prompt_attention_mask` )r3   allr   ro   rp   listr   rw   )
r^   r_   heightwidth"callback_on_step_end_tensor_inputsrE   rF   r   r   r   s
   `         r+   check_inputszMochiPipeline.check_inputsU  s7    A:?eai1nVW]V^^cdicjjklmm-9# F
7YF
 C
 DTEaEaDbbn  |^  pHvw  bc  ko  kG  kG  bGpq  pH  oI  J  -";08N}o ^0 0  ^ 5w  FC)@TZ\`IaQRVW]R^Q_`aa$)>)Fdee!-2P2Xvww$)?)K""&<&B&BB --:-@-@,A B.445Q8 
 %**.L.R.RR 55J5P5P4Q R6<<=Q@  S *L$+ pHs   E3%E3c                 8    | j                   j                          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.
        N)rG   enable_slicingr^   s    r+   enable_vae_slicingz MochiPipeline.enable_vae_slicing      
 	!rA   c                 8    | j                   j                          y)z
        Disable sliced VAE decoding. If `enable_vae_slicing` was previously enabled, this method will go back to
        computing decoding in one step.
        N)rG   disable_slicingr   s    r+   disable_vae_slicingz!MochiPipeline.disable_vae_slicing  s    
 	  "rA   c                 8    | j                   j                          y)a  
        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.
        N)rG   enable_tilingr   s    r+   enable_vae_tilingzMochiPipeline.enable_vae_tiling  s     	 rA   c                 8    | j                   j                          y)z
        Disable tiled VAE decoding. If `enable_vae_tiling` was previously enabled, this method will go back to
        computing decoding in one step.
        N)rG   disable_tilingr   s    r+   disable_vae_tilingz MochiPipeline.disable_vae_tiling  r   rA   c
                 r   || j                   z  }|| j                   z  }|dz
  | j                  z  dz   }|||||f}
|	|	j                  ||      S t        |t              r)t        |      |k7  rt        dt        |       d| d      t        |
||t        j                        }	|	j                  |      }	|	S )Nr   )r.   rb   z/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.)	generatorr.   rb   )
rT   rU   rs   ro   r   r;   r3   r   ru   float32)r^   r~   num_channels_latentsr   r   
num_framesrb   r.   r   rD   rw   s              r+   prepare_latentszMochiPipeline.prepare_latents  s     4888666 1n)G)GG!K
1:vuM::V5:99i&3y>Z+GA#i.AQ R&<'gi 
 u	&PUP]P]^**U#rA   c                     | j                   S r   _guidance_scaler   s    r+   guidance_scalezMochiPipeline.guidance_scale  s    ###rA   c                      | j                   dkD  S )Nr   r   r   s    r+   r   z)MochiPipeline.do_classifier_free_guidance  s    ##c))rA   c                     | j                   S r   )_num_timestepsr   s    r+   num_timestepszMochiPipeline.num_timesteps  s    """rA   c                     | j                   S r   )_attention_kwargsr   s    r+   attention_kwargszMochiPipeline.attention_kwargs      %%%rA   c                     | j                   S r   )_current_timestepr   s    r+   current_timestepzMochiPipeline.current_timestep  r   rA   c                     | j                   S r   )
_interruptr   s    r+   	interruptzMochiPipeline.interrupt  s    rA      @   g      @pilrD   r   r   r   r-   r/   r   r   output_typereturn_dictr   callback_on_step_endr   c                 d   t        |t        t        f      r|j                  }|xs | j                  }|xs | j
                  }| j                  ||||||||       || _        || _        d| _	        d| _
        |t        |t              rd}n-|t        |t              rt        |      }n|j                  d   }| j                  }| j!                  ||| j"                  |	||||||
      \  }}}}| j$                  j&                  j(                  }| j+                  ||	z  |||||j,                  ||
|	      }| j"                  r2t/        j0                  ||gd      }t/        j0                  ||gd      }d}t3        ||      }t5        j6                  |      }t9        | j:                  ||||      \  }}t=        t        |      || j:                  j>                  z  z
  d      }t        |      | _         | jC                  |	      5 }tE        |      D ]_  \  }}| jF                  rd
|z
  | _	        | j"                  rt/        j0                  |gdz        n|}|jI                  |j                  d         jK                  |j,                        } | j$                  jM                  d      5  | j%                  ||| ||d      d   }!ddd       !jK                  t.        jN                        }!| j"                  r)|!jQ                  d      \  }"}#|"| jR                  |#|"z
  z  z   }!|j,                  }$| j:                  jU                  |!||jK                  t.        jN                        d      d   }|jK                  |$      }|j,                  |$k7  r9t.        jV                  jX                  j[                         r|jK                  |$      }|Hi }%|D ]  }&t]               |&   |%|&<     || |||%      }'|'j_                  d|      }|'j_                  d|      }|t        |      dz
  k(  s'|dz   |kD  r/|dz   | j:                  j>                  z  dk(  r|ja                          tb        sLte        jf                          b 	 ddd       d| _	        |dk(  r|}(nti        | jj                  j&                  d      xr" | jj                  j&                  jl                  du})ti        | jj                  j&                  d      xr" | jj                  j&                  jn                  du}*|)r |*rt/        jp                  | jj                  j&                  jl                        js                  ddddd      jK                  |jt                  |j,                        }+t/        jp                  | jj                  j&                  jn                        js                  ddddd      jK                  |jt                  |j,                        },||,z  | jj                  j&                  jv                  z  |+z   }n#|| jj                  j&                  jv                  z  }| jj                  jy                  |d      d   }(| jz                  j}                  |(|      }(| j                          |s|(fS t        |(      S # 1 sw Y   xY w# 1 sw Y   3xY w)a  
        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.
            height (`int`, *optional*, defaults to `self.default_height`):
                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.default_width`):
                The width in pixels of the generated image. This is set to 848 by default for the best results.
            num_frames (`int`, defaults to `19`):
                The number of video frames to generate
            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`, defaults to `4.5`):
                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 image
                generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
                tensor will ge generated by sampling using the supplied random `generator`.
            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.
            prompt_attention_mask (`torch.Tensor`, *optional*):
                Pre-generated attention mask for text embeddings.
            negative_prompt_embeds (`torch.FloatTensor`, *optional*):
                Pre-generated negative text embeddings. For PixArt-Sigma this negative prompt should be "". If not
                provided, negative_prompt_embeds will be generated from `negative_prompt` input argument.
            negative_prompt_attention_mask (`torch.FloatTensor`, *optional*):
                Pre-generated attention mask for negative text embeddings.
            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.mochi.MochiPipelineOutput`] 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 `256`):
                Maximum sequence length to use with the `prompt`.

        Examples:

        Returns:
            [`~pipelines.mochi.MochiPipelineOutput`] or `tuple`:
                If `return_dict` is `True`, [`~pipelines.mochi.MochiPipelineOutput`] is returned, otherwise a `tuple`
                is returned where the first element is a list with the generated images.
        )r_   r   r   r   rE   rF   r   r   NFr   r   )
r_   r   r   r`   rE   rF   r   r   ra   r.   )dimg?)totali  r   cond_uncond)hidden_statesencoder_hidden_statestimestepencoder_attention_maskr   r   )r   rD   rE   latentlatents_meanlatents_std   )r   )frames)Aro   r   r   tensor_inputsr[   r\   r   r   r   r   r   rp   r   r;   rw   rn   r   r   rJ   rt   in_channelsr   rb   ru   catr,   nparrayr@   r<   maxorderr   progress_bar	enumerater   expandrs   cache_contextr   chunkr   stepbackendsmpsis_availablelocalspopupdateXLA_AVAILABLExm	mark_steprX   rG   r   r   tensorr}   r.   scaling_factordecoderW   postprocess_videomaybe_free_model_hooksr   )-r^   r_   r   r   r   r   r-   r/   r   r`   r   rD   rE   r   rF   r   r   r   r   r   r   ra   r~   r.   r   r   r0   num_warmup_stepsr   r!   tlatent_model_inputr   
noise_prednoise_pred_uncondnoise_pred_textlatents_dtypecallback_kwargsr   callback_outputsvideohas_latents_meanhas_latents_stdr   r   s-                                                r+   __call__zMochiPipeline.__call__  sU   H *-=?U,VW1E1S1S..4..+++ 	/Q'#9"7+I 	 		
  .!1!% *VS"9JJvt$<VJ&,,Q/J'' +(,(H(H"7'#9"7+I 3  
	
!"*  $//66BB&&.. 

 ++!II'=}&MSTUM$)II/MOd.ekl$m!  *+>P&!);NN*
&	& s9~0CdnnFZFZ0ZZ\]^!)n %89 4	#\!), 3#1>> *.&AEAaAaUYYy1}%=gn"88$6$<$<Q$?@CCGMMR%%33MB !%!1!1&8.;!)/D)9$) "2 " "J (]]5==9
339C9I9I!9L6%!2T5H5HO^oLo5p!pJ !(..--j!WZZ=Vdi-jklm!**]3==M1~~))668")**]";'3&(O? 9-3Xa[*9';D!Q'X$.229gFG$4$8$8-$XM I**A9I/IqSTuX\XfXfXlXlNlpqNq '') LLNg3#4	#l "&("E  'txxGtDHHOOLhLhptLt%dhhoo}Eq$((//JeJemqJqOOLL!=!=>CCAr1aQRSVVW^WeWegngtgtu  LL!<!<=BB1b!QPQRUUV]VdVdfmfsfst  "K/$((//2P2PPS__!DHHOO$B$BBHHOOGO?BE((::5k:ZE 	##%8O"%00O 4	# 4	#s,   B#Z%'ZFZ%Z%Z"Z%%Z/)F)Nr   rP   NN)
NTr   NNNNrP   NN)NNNNNr   )0__name__
__module____qualname____doc__model_cpu_offload_seq_optional_componentsr   r   r   r	   r
   r   rr   rR   r   rp   r   intr   ru   r.   rb   r   Tensorr   r   r   r   r   r   r   propertyr   r   r   r   r   r   no_gradr   EXAMPLE_DOC_STRINGfloat	Generatorr   r   r   r   __classcell__)r:   s   @r+   rC   rC      sr   . =T .3[2[  [ %	[
 #[ -[ '+[B )-%&#&)-'+64c49n%64  #64 !	64
 &64 $64x <@,0%&049=8<AE#&)-'+Qlc49n%Ql "%T#Y"78Ql &*	Ql
  #Ql  -Ql !) 6Ql  (5Ql )1(>Ql !Ql &Ql $Qlp ,0#"'+3j"#!"" < $ $ * * # # & & & &   U]]_12 )-;? $##%# #/0MQ*.048<9=AE%* 59KO9B#&-J1c49n%J1 "%T#Y"78J1 	J1
 }J1 J1 !J1 9J1 J1  (}J1 E%//43H"HIJJ1 %,,'J1  -J1  (5J1 !) 6J1  )1(>!J1" c]#J1$ %J1& #4S>2'J1( 'xc40@$0F'GH)J1* -1I+J1, !-J1 3 J1rA   rC   r   )NNNN)4r5   typingr   r   r   r   r   r   numpyr   ru   transformersr	   r
   	callbacksr   r   loadersr   modelsr   r   
schedulersr   utilsr   r   r   utils.torch_utilsr   rW   r   pipeline_utilsr   pipeline_outputr   torch_xla.core.xla_modelcore	xla_modelr   r   
get_loggerr   rz   r  r,   r  rp   r.   r  r@   rC   r2   rA   r+   <module>r     s     = =   8 A , A 9 
 . - . 0 ))MM 
		H	% $( *.15%)$(8*!#8* U3,-.8* S	"	8*
 T%[!8*v[	1%'< [	1rA   