
    +ht                     &   S SK r S SKJrJrJrJrJr  S SKrS SK	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JrJrJr  SS
KJr  SSKJr  SSK J!r!  SSK"J#r#  \" 5       (       a  S SK$J%r%  O
 " S S5      r%\" 5       (       a  S SK&J's  J(r)  Sr*OSr*\RV                  " \,5      r-Sr.    S!S\\/   S\\\0\	Rb                  4      S\\\/      S\\\2      4S jjr3 S"S\	Rh                  S\\	Rj                     S\04S jjr6 " S S \!5      r7g)#    N)CallableDictListOptionalUnion)T5EncoderModelT5TokenizerFast   )MultiPipelineCallbacksPipelineCallback)PipelineImageInput)AutoencoderKLWanCosmosTransformer3DModel)FlowMatchEulerDiscreteScheduler)is_cosmos_guardrail_availableis_torch_xla_availableloggingreplace_example_docstring)randn_tensor)VideoProcessor   )DiffusionPipeline   )CosmosPipelineOutput)CosmosSafetyCheckerc                       \ rS rSrS rSrg)r   %   c                     [        S5      e)Nz|`cosmos_guardrail` is not installed. Please install it to use the safety checker for Cosmos: `pip install cosmos_guardrail`.)ImportError)selfargskwargss      q/home/james-whalen/.local/lib/python3.13/site-packages/diffusers/pipelines/cosmos/pipeline_cosmos2_video2world.py__init__CosmosSafetyChecker.__init__&   s     O      N)__name__
__module____qualname____firstlineno__r$   __static_attributes__r'   r&   r#   r   r   %   s    	r&   r   TFaL  
    Examples:
        ```python
        >>> import torch
        >>> from diffusers import Cosmos2VideoToWorldPipeline
        >>> from diffusers.utils import export_to_video, load_image

        >>> # Available checkpoints: nvidia/Cosmos-Predict2-2B-Video2World, nvidia/Cosmos-Predict2-14B-Video2World
        >>> model_id = "nvidia/Cosmos-Predict2-2B-Video2World"
        >>> pipe = Cosmos2VideoToWorldPipeline.from_pretrained(model_id, torch_dtype=torch.bfloat16)
        >>> pipe.to("cuda")

        >>> prompt = "A close-up shot captures a vibrant yellow scrubber vigorously working on a grimy plate, its bristles moving in circular motions to lift stubborn grease and food residue. The dish, once covered in remnants of a hearty meal, gradually reveals its original glossy surface. Suds form and bubble around the scrubber, creating a satisfying visual of cleanliness in progress. The sound of scrubbing fills the air, accompanied by the gentle clinking of the dish against the sink. As the scrubber continues its task, the dish transforms, gleaming under the bright kitchen lights, symbolizing the triumph of cleanliness over mess."
        >>> negative_prompt = "The video captures a series of frames showing ugly scenes, static with no motion, motion blur, over-saturation, shaky footage, low resolution, grainy texture, pixelated images, poorly lit areas, underexposed and overexposed scenes, poor color balance, washed out colors, choppy sequences, jerky movements, low frame rate, artifacting, color banding, unnatural transitions, outdated special effects, fake elements, unconvincing visuals, poorly edited content, jump cuts, visual noise, and flickering. Overall, the video is of poor quality."
        >>> image = load_image(
        ...     "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/yellow-scrubber.png"
        ... )

        >>> video = pipe(
        ...     image=image, prompt=prompt, negative_prompt=negative_prompt, generator=torch.Generator().manual_seed(1)
        ... ).frames[0]
        >>> export_to_video(video, "output.mp4", fps=16)
        ```
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.   r0   zv's `set_timesteps` does not support custom sigmas schedules. Please check whether you are using the correct scheduler.)r0   r.   r.   r'   )

ValueErrorsetinspect	signatureset_timesteps
parameterskeys	__class__r/   len)	schedulerr-   r.   r/   r0   r"   accepts_timestepsaccept_sigmass           r#   retrieve_timestepsr>   Q   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&   encoder_output	generatorsample_modec                    [        U S5      (       a!  US:X  a  U R                  R                  U5      $ [        U S5      (       a   US:X  a  U R                  R                  5       $ [        U S5      (       a  U R                  $ [        S5      e)Nlatent_distsampleargmaxlatentsz3Could not access latents of provided encoder_output)hasattrrC   rD   moderF   AttributeError)r?   r@   rA   s      r#   retrieve_latentsrJ      s}     ~}--+2I))00;;		/	/K84K))..00		+	+%%%RSSr&   c            -         ^  \ rS rSrSrSr/ SQrS/r S>S\S\	S	\
S
\S\S\4U 4S jjjr    S?S\\\\   4   S\S\\R*                     S\\R,                     4S jjr        S@S\\\\   4   S\\\\\   4      S\S\S\\R2                     S\\R2                     S\S\\R*                     S\\R,                     4S jjr        SAS\R2                  S\S S!S"\S#\S$\S\S\\R,                     S\\R*                     S%\\\R6                  \\R6                     4      S&\\R2                     S'\R2                  4S( jjr  SBS) jr\S* 5       r\S+ 5       r \S, 5       r!\S- 5       r"\S. 5       r#\RH                  " 5       \%" \&5      SSSSSSSS/S0S!SSSSSS1SSS&/SS24S3\'S\\'   S\\\\   4   S\\\\\   4      S"\S#\S$\S4\S5\(S6\S\\   S%\\\R6                  \\R6                     4      S&\\R2                     S\\R2                     S\\R2                     S7\\   S8\S9\\\)\\\*/S4   \+\,4      S:\\   S\S;\(4*S< jj5       5       r-S=r.U =r/$ )CCosmos2VideoToWorldPipeline   a  
Pipeline for video-to-world generation using [Cosmos Predict2](https://github.com/nvidia-cosmos/cosmos-predict2).

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

Args:
    text_encoder ([`T5EncoderModel`]):
        Frozen text-encoder. Cosmos uses
        [T5](https://huggingface.co/docs/transformers/model_doc/t5#transformers.T5EncoderModel); specifically the
        [t5-11b](https://huggingface.co/google-t5/t5-11b) variant.
    tokenizer (`T5TokenizerFast`):
        Tokenizer of class
        [T5Tokenizer](https://huggingface.co/docs/transformers/model_doc/t5#transformers.T5Tokenizer).
    transformer ([`CosmosTransformer3DModel`]):
        Conditional Transformer to denoise the encoded image latents.
    scheduler ([`FlowMatchEulerDiscreteScheduler`]):
        A scheduler to be used in combination with `transformer` to denoise the encoded image latents.
    vae ([`AutoencoderKLWan`]):
        Variational Auto-Encoder (VAE) Model to encode and decode videos to and from latent representations.
ztext_encoder->transformer->vae)rF   prompt_embedsnegative_prompt_embedssafety_checkerNtext_encoder	tokenizertransformervaer;   c           	      \  > [         TU ]  5         Uc
  [        5       nU R                  UUUUUUS9  [	        U SS 5      (       a"  S[        U R                  R                  5      -  OSU l        [	        U SS 5      (       a"  S[        U R                  R                  5      -  OSU l
        [        U R                  S9U l        SU l        SU l        S	U l        S
U l        U R"                  bE  U R"                  R%                  U R                  U R                  U R                  U R                   S9  g g )N)rT   rQ   rR   rS   r;   rP   rT   r         )vae_scale_factorg      T@gMb`?      ?	sigma_min)	sigma_maxrZ   
sigma_datafinal_sigmas_type)superr$   r   register_modulesgetattrsumrT   temperal_downsamplevae_scale_factor_temporalr:   vae_scale_factor_spatialr   video_processorr[   rZ   r\   r]   r;   register_to_config)r    rQ   rR   rS   rT   r;   rP   r9   s          r#   r$   $Cosmos2VideoToWorldPipeline.__init__   s    	!02N%#) 	 	
 T[[_afhlSmSmc$((2N2N.O)Ost&RYZ^`egkRlRlS1M1M-N(Nrs%-t?\?\]!,>>%NN--....??"&"8"8	 .  &r&      promptmax_sequence_lengthr.   dtypec           
      H   U=(       d    U R                   nU=(       d    U R                  R                  n[        U[        5      (       a  U/OUnU R                  USUSSSSS9nUR                  nUR                  R                  5       R                  U5      nU R                  USSS9R                  nUR                  S   UR                  S   :  a]  [        R                  " Xh5      (       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      US9R                   n
U
R                  XCS9n
UR#                  S	S9R%                  5       n['        U5       H  u  pSXUS 24'   M     U
$ )N
max_lengthTptF)paddingrm   
truncationreturn_tensorsreturn_lengthreturn_offsets_mappinglongest)ro   rq   r   zXThe following part of your input was truncated because `max_sequence_length` is set to  z	 tokens: )attention_maskrk   r.   dimr   )_execution_devicerQ   rk   
isinstancestrrR   	input_idsrv   booltoshapetorchequalbatch_decodeloggerwarninglast_hidden_statera   cpu	enumerate)r    ri   rj   r.   rk   text_inputstext_input_idsprompt_attention_maskuntruncated_idsremoved_textrN   lengthsilengths                 r#   _get_t5_prompt_embeds1Cosmos2VideoToWorldPipeline._get_t5_prompt_embeds   s    14110**00'44&&nn *#( % 
 %.. + : : ? ? A D DV L..SW.Xbb  $(<(<R(@@UcIuIu>>66qJ]`aJadfJfGf7ghLNN'(	,A
 ))f%6K * 


 	 &((u(D'+++2668"7+IA()MVW*% , r&   Tr   negative_promptdo_classifier_free_guidancenum_videos_per_promptrN   rO   c
                    U=(       d    U R                   n[        U[        5      (       a  U/OUnUb  [        U5      n
OUR                  S   n
UcG  U R                  XXS9nUR                  u  pnUR                  SUS5      nUR                  X-  US5      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                  X'XS9nUR                  u  pnUR                  SUS5      nUR                  X-  US5      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   )ri   rj   r.   rk   r   ru    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`.)rz   r{   r|   r:   r   r   repeatviewtype	TypeErrorr2   )r    ri   r   r   r   rN   rO   rj   r.   rk   
batch_size_seq_lens                r#   encode_prompt)Cosmos2VideoToWorldPipeline.encode_prompt	  s   L 1411'44&&VJ&,,Q/J  66v 7 M
 *//MA)004I1MM)..z/QSZ\^_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  &*%?%?&X^ &@ &"
 388MA%;%B%B1F[]^%_"%;%@%@Acelnp%q"44r&        ]   videor   num_channels_latents   heightwidth
num_framesr@   rF   returnc           
         [        U
[        5      (       a*  [        U
5      U:w  a  [        S[        U
5       SU S35      eUR	                  S5      nX:  a%  US-
  U R
                  -  S-   nUS S 2S S 2U* S 24   nOSUS-
  U R
                  -  S-   nXl-
  nUS S 2S S 2SS 24   nUR                  SSUSS5      n[        R                  " UU/SS9n[        U
[        5      (       aR  [        U5       Vs/ s H;  n[        U R                  R                  UU   R                  S5      5      U
U   S	9PM=     nnODU Vs/ s H7  n[        U R                  R                  UR                  S5      5      U
5      PM9     nn[        R                  " USS9R                  U5      n[        R                  " U R                  R                   R"                  5      R%                  SU R                  R                   R&                  SSS5      R                  X5      n[        R                  " U R                  R                   R(                  5      R%                  SU R                  R                   R&                  SSS5      R                  X5      nUU-
  U-  U R*                  R                   R,                  -  nUS-
  U R
                  -  S-   nX@R.                  -  nXPR.                  -  nX#UUU4nUc  [1        UXUS
9nOUR                  XS9nXR*                  R                   R2                  -  nUSUUU4nUR5                  U5      nUR7                  U5      nUR7                  SSUR	                  S5      SS5      nSUS S 2S S 2S U24'   UU-  SU-
  U-  -   nS =nn U(       a@  UR7                  SSUR	                  S5      SS5      nSUS S 2S S 2S U24'   UU-  SU-
  U-  -   n UUUUUU 4$ s  snf s  snf )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   r   ru   rx   r   )r@   )r@   r.   rk   r.   rk   rY   )r{   listr:   r2   sizerc   r   r   catrangerJ   rT   encode	unsqueezer   tensorconfiglatents_meanr   z_dimlatents_stdr;   r\   rd   r   r[   new_ones	new_zeros)!r    r   r   r   r   r   r   r   rk   r.   r@   rF   num_cond_framesnum_cond_latent_framesnum_padding_frames
last_framero   r   init_latentsvidr   r   num_latent_frameslatent_heightlatent_widthr   padding_shapeones_paddingzeros_paddingcond_indicator	cond_maskuncond_indicatoruncond_masks!                                    r#   prepare_latents+Cosmos2VideoToWorldPipeline.prepare_latents\  s    i&&3y>Z+GA#i.AQ R&<'gi 
  **Q-(&01n9W9W%WZ[%["!Q,-E&5&9d>\>\%\_`%`"!+!=q!RSy)J ''1.@!QGGIIug.A6Ei&& z**A !q1C1CA1F!GS\]^S_`*  L
 gllfk_b,TXX__S]]1=M-NPYZfkLlyy1588? LL556;;Atxx?T?TVWYZ\]^aabhp 	 LL445::1dhhoo>S>SUVXY[\]``ago 	 %|3{BT^^EZEZEeEee'!^0N0NNQRR"?"?? = ==3DmUab?"5ITYZGjjj<GNN11;;;#Q(9=,W''6))-8 **1aa!QG8;q!44445"\1Q5G=4XX	)--;&&00Aw||A1M>AQ#:$:#::;*\9QAQ=QUb<bbKn6F	S^^^W
 ms   0AO!9>O&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  ofT 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bC  [        U[        5      (       d-  [        U[
        5      (       d  [        S[        U5       35      eg g g s  snf )Nr   r   z8`height` and `width` have to be divisible by 16 but are z and r   c              3   @   >#    U  H  oTR                   ;   v   M     g 7fN)_callback_tensor_inputs).0kr    s     r#   	<genexpr>;Cosmos2VideoToWorldPipeline.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 )r2   allr   r{   r|   r   r   )r    ri   r   r   rN   "callback_on_step_end_tensor_inputsr   s   `      r#   check_inputs(Cosmos2VideoToWorldPipeline.check_inputs  sr    B;!urzQWX^W__dejdkklmnn-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 Jb)@ pHs   C01C0c                     U R                   $ r   _guidance_scaler    s    r#   guidance_scale*Cosmos2VideoToWorldPipeline.guidance_scale  s    ###r&   c                      U R                   S:  $ )NrY   r   r   s    r#   r   7Cosmos2VideoToWorldPipeline.do_classifier_free_guidance  s    ##c))r&   c                     U R                   $ r   )_num_timestepsr   s    r#   num_timesteps)Cosmos2VideoToWorldPipeline.num_timesteps  s    """r&   c                     U R                   $ r   )_current_timestepr   s    r#   current_timestep,Cosmos2VideoToWorldPipeline.current_timestep  s    %%%r&   c                     U R                   $ r   )
_interruptr   s    r#   	interrupt%Cosmos2VideoToWorldPipeline.interrupt  s    r&   #   g      @pilg-C6?imager-   r   fpsoutput_typereturn_dictcallback_on_step_endr   sigma_conditioningc                    U R                   c  [        SU R                   S35      e[        U[        [
        45      (       a  UR                  nU R                  X5XnU5        Xl        SU l	        SU l
        U R                  nU R                   b  U R                   R                  U5        UbR  [        U[        5      (       a  U/OUnU H2  nU R                   R                  U5      (       a  M%  [        SU S35      e   U R                   R                  S5        Ub  [        U[        5      (       a  SnO3Ub!  [        U[        5      (       a  [!        U5      nOUR"                  S	   nU R%                  UUU R&                  UUUUUS
9u  nn[(        R*                  R,                  R/                  5       (       a  [(        R0                  O[(        R2                  n[(        R4                  " S	SUUS9n[7        U R8                  UUS9u  nnU R8                  R:                  R<                  S:X  a0  U R8                  R>                  S   U R8                  R>                  S'   U R@                  RB                  nU RD                  RB                  nUb,  U RF                  RI                  XU5      RK                  S5      nOU RF                  RM                  X%U5      nUR                  UUS9nU RD                  R:                  RN                  S-
  nU RQ                  UUU-  UUUUU R&                  [(        R0                  UUU5      u  nn n!n"n#n$Sn%U#R                  U5      n#U R&                  (       a  U$R                  U5      n$U n%URS                  SSXVUS9n&[(        RT                  " U[(        R0                  US9nUUS-   -  n'[!        U5      XR8                  RV                  -  -
  n([!        U5      U l,        U R[                  US9 n)[]        U5       GH  u  n*n+U R^                  (       a  M  U+U l	        U R8                  R>                  U*   n,U,U,S-   -  n-SU--
  n.SU--
  n/U-* n0U-Ra                  SSSSS5      Rc                  URe                  S	5      SURe                  S5      SS5      n1UU.-  n2U!U -  SU!-
  U2-  -   n2U2R                  U5      n2U!U'-  SU!-
  U1-  -   n3U3R                  U5      n3U RE                  U2U3UU
U#U&SS9S	   n4U/U-  U0U4Rg                  5       -  -   R                  U5      n4U!U -  SU!-
  U4-  -   n4U R&                  (       a  UU.-  n5U"U%-  SU"-
  U5-  -   n5U5R                  U5      n5U"U'-  SU"-
  U1-  -   n6U6R                  U5      n6U RE                  U5U6UU
U$U&SS9S	   n7U/U-  U0U7Rg                  5       -  -   R                  U5      n7U"U%-  SU"-
  U7-  -   n7U4U Rh                  U4U7-
  -  -   n4UU4-
  U,-  n4U R8                  Rk                  U4U+USS9S	   nUb\  0 n8U H  n9[m        5       U9   U8U9'   M     U" U U*U+U85      n:U:Ro                  SU5      nU:Ro                  SU5      nU:Ro                  SU5      nU*[!        U5      S-
  :X  d)  U*S-   U(:  a0  U*S-   U R8                  RV                  -  S	:X  a  U)Rq                  5         [r        (       d  GM  [t        Rv                  " 5         GM     SSS5        SU l	        US:X  Gd  [(        RT                  " U R@                  R:                  Rx                  5      Ra                  SU R@                  R:                  Rz                  SSS5      R                  UR|                  URB                  5      n;[(        RT                  " U R@                  R:                  R~                  5      Ra                  SU R@                  R:                  Rz                  SSS5      R                  UR|                  URB                  5      n<UU<-  U R8                  R:                  R                  -  U;-   nU R@                  R                  UR                  U R@                  RB                  5      SS9S	   nU R                   Gb)  U R                   R                  U5        U RF                  R                  USS9nUS-  R                  [        R                  5      n/ n=U H/  n>U R                   R                  U>5      n>U=R                  U>5        M1     [        R                  " U=5      R                  [        R0                  5      S-  S-  S-
  n[(        R                  " U5      R                  S	SSSS5      nU RF                  R                  UUS9nU R                   R                  S5        OU RF                  R                  UUS9nOUnU R                  5         U(       d  U4$ [        US 9$ ! , (       d  f       GN= f)!a	  
The call function to the pipeline for generation.

Args:
    image (`PIL.Image.Image`, `np.ndarray`, `torch.Tensor`, *optional*):
        The image to be used as a conditioning input for the video generation.
    video (`List[PIL.Image.Image]`, `np.ndarray`, `torch.Tensor`, *optional*):
        The video to be used as a conditioning input for the video generation.
    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`, defaults to `704`):
        The height in pixels of the generated image.
    width (`int`, defaults to `1280`):
        The width in pixels of the generated image.
    num_frames (`int`, defaults to `93`):
        The number of frames in the generated video.
    num_inference_steps (`int`, defaults to `35`):
        The number of denoising steps. More denoising steps usually lead to a higher quality image at the
        expense of slower inference.
    guidance_scale (`float`, defaults to `7.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`.
    fps (`int`, defaults to `16`):
        The frames per second of the generated video.
    num_videos_per_prompt (`int`, *optional*, defaults to 1):
        The number of images to generate per prompt.
    generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
        A [`torch.Generator`](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 is 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.
    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.
    output_type (`str`, *optional*, defaults to `"pil"`):
        The output format of the generated image. Choose between `PIL.Image` or `np.array`.
    return_dict (`bool`, *optional*, defaults to `True`):
        Whether or not to return a [`CosmosPipelineOutput`] instead of a plain tuple.
    callback_on_step_end (`Callable`, `PipelineCallback`, `MultiPipelineCallbacks`, *optional*):
        A function or a subclass of `PipelineCallback` or `MultiPipelineCallbacks` that is called at the end of
        each denoising step during the inference. 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 `512`):
        The maximum number of tokens in the prompt. If the prompt exceeds this length, it will be truncated. If
        the prompt is shorter than this length, it will be padded.
    sigma_conditioning (`float`, defaults to `0.0001`):
        The sigma value used for scaling conditioning latents. Ideally, it should not be changed or should be
        set to a small value close to zero.

Examples:

Returns:
    [`~CosmosPipelineOutput`] or `tuple`:
        If `return_dict` is `True`, [`CosmosPipelineOutput`] is returned, otherwise a `tuple` is returned where
        the first element is a list with the generated images and the second element is a list of `bool`s
        indicating whether the corresponding generated image contains "not-safe-for-work" (nsfw) content.
Nz)You have disabled the safety checker for z. This is in violation of the [NVIDIA Open Model License Agreement](https://www.nvidia.com/en-us/agreements/enterprise-software/nvidia-open-model-license). Please ensure that you are compliant with the license agreement.Fz5Cosmos Guardrail detected unsafe text in the prompt: zR. Please ensure that the prompt abides by the NVIDIA Open Model License Agreement.r   r   r   )ri   r   r   r   rN   rO   r.   rj   )rk   )r.   r0   rZ   ru   r   r   rw   )total)hidden_statestimestepencoder_hidden_statesr   condition_maskpadding_maskr   )r   rF   rN   rO   latentnp)r      g     o@rV   r
   )frames)MrP   r2   r9   r{   r   r   tensor_inputsr   r   r   r   rz   r   r|   check_text_safetyr   r:   r   r   r   r   backendsmpsis_availablefloat32float64linspacer>   r;   r   r]   r0   rT   rk   rS   re   
preprocessr   preprocess_videoin_channelsr   r   r   orderr   progress_barr   r   r   expandr   floatr   steplocalspopupdateXLA_AVAILABLExm	mark_stepr   r   r.   r   r\   decodepostprocess_videoastyper   uint8check_video_safetyappendstack
from_numpypermutemaybe_free_model_hooksr   )?r    r   r   ri   r   r   r   r   r-   r   r   r   r@   rF   rN   rO   r   r   r   r   rj   r   r.   prompt_listpr   sigmas_dtyper0   r/   	vae_dtypetransformer_dtyper   conditioning_latentsr   r   r   r   unconditioning_latentsr   t_conditioningnum_warmup_stepsr  r   tcurrent_sigma	current_tc_inc_skipc_outr   cond_latentcond_timestep
noise_preduncond_latentuncond_timestepnoise_pred_uncondcallback_kwargsr   callback_outputsr   r   video_batchr   s?                                                                  r#   __call__$Cosmos2VideoToWorldPipeline.__call__  s	   F &;DNN;K LS T  *-=?U,VWW1E1S1S. 	&%@bc-!%''*""6*!*4VS*A*Avhv$A..@@CC(STUSV WX Y  % ""5) *VS"9"9JJvt$<$<VJ&,,Q/J +(,(H(H"7'#9 3  	
	
" ).(:(:(G(G(I(Iu}}u}}1&9N);DNNSYbh)i&	&>>  22kA(,(=(=b(ADNN!!"% HHNN	 ,,22((33E5ISSTUVE((99%OEi8#//66BBQFbfbvbv.. ,,MMc
_%~7GT_ "&LL!23	++%..):;K%9"((AvDU(V"\\*<EMMZ`a+/AA/EF y>,?..BVBV,VV!)n%89\!),1>>)*& $ 5 5a 8)]Q->?	9}Y"
$>>!Q1a8??LLORa"b &n,/CCq>GY]hFhh)nn->? . ?1~CUYaBa a - 0 01B C!--"-**7#,!- % .  
 %w.9I9I9K1KKOOPab
+.BBa.FX\fEff
33$+dNM$47M$MQRUeQeivPv$vM$1$4$45F$GM&6&G1O_K_ckJk&kO&5&8&89J&KO(,(8(8&3!0.D'2%1$) )9 ) )% *0')9EDUD[D[D]<])](a(abs(t%(+AAQIYEY]nDnn & ",d.A.AZRcEc.d!dJ%
2mC
..--j!WRW-XYZ['3&(O?-3Xa[* @';D!Q'X$.229gFG$4$8$8-$XM-=-A-ABZ\r-s* I**A9I/IqSTuX\XfXfXlXlNlpqNq '') =LLNS - :X "&h&TXX__99:a..1a8GNNGMM2  TXX__889a..1a8GNNGMM2 
 +dnn.C.C.N.NNQ]]GHHOOGJJtxx~~$>EORSTUE"".##&&v.,,>>uRV>W,,RXX6  C--@@EC&&s+ ! -44RZZ@5H1LqP((/771aAF,,>>uR]>^##&&u-,,>>uR]>^E 	##%8O#511g :9s   9Kg#g##
g2)r   r   r   r   r]   r\   r[   rZ   rd   rc   re   r   )Nrh   NN)NTr   NNrh   NN)r   r   r   TNNNN)NN)0r(   r)   r*   r+   __doc__model_cpu_offload_seqr   _optional_componentsr   r	   r   r   r   r   r$   r   r|   r   intr   r   r.   rk   r   r~   Tensorr   	Generatorr   r   propertyr   r   r   r   r   no_gradr   EXAMPLE_DOC_STRINGr   r  r   r   r   r   r9  r,   __classcell__)r9   s   @r#   rL   rL      s   , =T,- /3%$% #% .	%
 % 3% ,% %T )-#&)-'+(c49n%( !( &	(
 $(\ <@,0%&049=#&)-'+Q5c49n%Q5 "%T#Y"78Q5 &*	Q5
  #Q5  -Q5 !) 6Q5 !Q5 &Q5 $Q5p ,0'+)-MQ*.L_||L_ L_ !	L_
 L_ L_ L_ &*L_ $L_ &L_ E%//43H"HIJL_ %,,'L_ 
L_h +/b< $ $ * * # # & &   ]]_12 %)*.(,;?#% #/0MQ*.049=%*  9B#&$*1y2!y2 &'y2 c49n%	y2
 "%T#Y"78y2 y2 y2 y2 !y2 y2 y2  (}y2 E%//43H"HIJy2 %,,'y2  -y2  !) 6!y2" c]#y2$ %y2& '(Cd+T124DF\\]
'y2, -1I-y2. !/y20 "1y2 3 y2r&   rL   )NNNN)NrD   )8r4   typingr   r   r   r   r   numpyr   r   transformersr   r	   	callbacksr   r   image_processorr   modelsr   r   
schedulersr   utilsr   r   r   r   utils.torch_utilsr   re   r   pipeline_utilsr   pipeline_outputr   cosmos_guardrailr   torch_xla.core.xla_modelcore	xla_modelr  r  
get_loggerr(   r   rC  r>  r|   r.   r  r>   r?  r@  rJ   rL   r'   r&   r#   <module>rU     s)    8 8   8 A 1 @ 9 n n - - . 1 !""4  ))MM			H	% : *.15%)$(8*!#8* U3,-.8* S	"	8*
 T%[!8*z ck
TLL
T-5eoo-F
T\_
T~	2"3 ~	2r&   