
    bi                        d dl Z d dl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mZ ddlmZ ddlmZ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#Z# n
 G d d      Z# e       rd dl$m%c m&Z' dZ(ndZ( ejR                  e*      Z+dZ,	 	 	 	 ddee-   deee.e	j^                  f      deee-      deee0      fdZ1 G d de      Z2y)    N)CallableDictListOptionalUnion)T5EncoderModelT5TokenizerFast   )MultiPipelineCallbacksPipelineCallback)AutoencoderKLWanCosmosTransformer3DModel)FlowMatchEulerDiscreteScheduler)is_cosmos_guardrail_availableis_torch_xla_availableloggingreplace_example_docstring)randn_tensor)VideoProcessor   )DiffusionPipeline   )CosmosImagePipelineOutput)CosmosSafetyCheckerc                       e Zd Zd Zy)r   c                     t        d      )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/cdr/jupyterlab/.venv/lib/python3.12/site-packages/diffusers/pipelines/cosmos/pipeline_cosmos2_text2image.py__init__zCosmosSafetyChecker.__init__%   s     O     N)__name__
__module____qualname__r"    r#   r!   r   r   $   s    	r#   r   TFa8  
    Examples:
        ```python
        >>> import torch
        >>> from diffusers import Cosmos2TextToImagePipeline

        >>> # Available checkpoints: nvidia/Cosmos-Predict2-2B-Text2Image, nvidia/Cosmos-Predict2-14B-Text2Image
        >>> model_id = "nvidia/Cosmos-Predict2-2B-Text2Image"
        >>> pipe = Cosmos2TextToImagePipeline.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."

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

ValueErrorsetinspect	signatureset_timesteps
parameterskeys	__class__r*   len)	schedulerr(   r)   r*   r+   r    accepts_timestepsaccept_sigmass           r!   retrieve_timestepsr9   L   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''	)))r#   c            $       P    e Zd ZdZdZg dZdgZ	 d6dedede	d	e
d
edef fdZ	 	 	 	 d7deeee   f   dedeej(                     deej*                     fdZ	 	 	 	 	 	 	 	 d8deeee   f   deeeee   f      dededeej0                     deej0                     dedeej(                     deej*                     fdZ	 	 	 	 	 	 	 d9deddded ed!edeej*                     deej(                     d"eeej4                  eej4                     f      d#eej0                     d$ej0                  fd%Z	 	 d:d&Zed'        Zed(        Zed)        Z ed*        Z!ed+        Z" ejF                          e$e%      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d ed/ed0e&dee   d"eeej4                  eej4                     f      d#eej0                     deej0                     deej0                     d1ee   d2ed3eee'eee(gdf   e)e*f      d4ee   def d5              Z+ xZ,S );Cosmos2TextToImagePipelinea  
    Pipeline for text-to-image 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)latentsprompt_embedsnegative_prompt_embedssafety_checkerNtext_encoder	tokenizertransformervaer6   c                 V   t         |           |
t               }| j                  ||||||       t	        | dd       r"dt        | j                  j                        z  nd| _        t	        | dd       r"dt        | j                  j                        z  nd| _
        t        | j                        | _        d| _        d| _        d	| _        d
| _        | j"                  H| j"                  j%                  | j                  | j                  | j                  | j                          y y )N)rC   r@   rA   rB   r6   r?   rC   r         )vae_scale_factorg      T@gMb`?      ?	sigma_min)	sigma_maxrI   
sigma_datafinal_sigmas_type)superr"   r   register_modulesgetattrsumrC   temperal_downsamplevae_scale_factor_temporalr5   vae_scale_factor_spatialr   video_processorrJ   rI   rK   rL   r6   register_to_config)r   r@   rA   rB   rC   r6   r?   r4   s          r!   r"   z#Cosmos2TextToImagePipeline.__init__   s    	!02N%#) 	 	
 T[[_afhlSmc$((2N2N.O)Ost&RYZ^`egkRlS1M1M-N(Nrs%-t?\?\]!,>>%NN--....??"&"8"8	 .  &r#      promptmax_sequence_lengthr)   dtypec           	      >   |xs | j                   }|xs | j                  j                  }t        |t              r|gn|}| j                  |d|dddd      }|j                  }|j                  j                         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                  |      |      j                   }
|
j                  ||      }
|j#                  d	      j%                         }t'        |      D ]  \  }}d|
||d f<    |
S )N
max_lengthTptF)paddingr[   
truncationreturn_tensorsreturn_lengthreturn_offsets_mappinglongest)r]   r_   r   zXThe following part of your input was truncated because `max_sequence_length` is set to  z	 tokens: )attention_mask)rY   r)   )dimr   )_execution_devicer@   rY   
isinstancestrrA   	input_idsrd   booltoshapetorchequalbatch_decodeloggerwarninglast_hidden_staterP   cpu	enumerate)r   rW   rX   r)   rY   text_inputstext_input_idsprompt_attention_maskuntruncated_idsremoved_textr=   lengthsilengths                 r!   _get_t5_prompt_embedsz0Cosmos2TextToImagePipeline._get_t5_prompt_embeds   s    14110**00'4&&nn *#( % 
 %.. + : : ? ? A D DV L..SW.Xbb  $(<(<R(@@UcetIu>>66qJ]`aJadfJfGf7ghLNN'(	,A
 ))f%6K * 


 	 &((uV(D'+++2668"7+ 	*IAv()M!VW*%	* r#   Tr   negative_promptdo_classifier_free_guidancenum_images_per_promptr=   r>   c
                    |xs | j                   }t        |t              r|gn|}|t        |      }
n|j                  d   }
|N| j                  ||||	      }|j                  \  }}}|j                  d|d      }|j                  |
|z  |d      }|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                  ||||	      }|j                  \  }}}|j                  d|d      }|j                  |
|z  |d      }||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_images_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   )rW   rX   r)   rY   r   rc    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`.)rf   rg   rh   r5   rl   r}   repeatviewtype	TypeErrorr-   )r   rW   r~   r   r   r=   r>   rX   r)   rY   
batch_size_seq_lens                r!   encode_promptz(Cosmos2TextToImagePipeline.encode_prompt   s   L 1411'4&&VJ&,,Q/J  663Fv]b 7 M
 *//MAw)004I1MM)..z<Q/QSZ\^_M&+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  &*%?%?&<OX^fk &@ &"
 388MAw%;%B%B1F[]^%_"%;%@%@NcAcelnp%q"444r#      P  r   num_channels_latents   heightwidth
num_frames	generatorr<   returnc
                    |	4|	j                  ||      | j                  j                  j                  z  S |dz
  | j                  z  dz   }
|| j
                  z  }|| j
                  z  }|||
||f}t        |t              r)t        |      |k7  rt        dt        |       d| d      t        ||||      }	|	| j                  j                  j                  z  S )N)r)   rY   r   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.)r   r)   rY   )rk   r6   configrJ   rR   rS   rg   listr5   r-   r   )r   r   r   r   r   r   rY   r)   r   r<   num_latent_frameslatent_heightlatent_widthrl   s                 r!   prepare_latentsz*Cosmos2TextToImagePipeline.prepare_latentsI  s     ::V5:9DNN<Q<Q<[<[[['!^0N0NNQRR$"?"?? = ==13DmUabi&3y>Z+GA#i.AQ R&<'gi 
 u	&PUV..8888r#   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      |9t        |t              s(t        |t
              st        dt        |             y y y c c}w )Nr   r   z8`height` and `width` have to be divisible by 16 but are z and r   c              3   :   K   | ]  }|j                   v   y wN)_callback_tensor_inputs).0kr   s     r!   	<genexpr>z:Cosmos2TextToImagePipeline.check_inputs.<locals>.<genexpr>r  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 )r-   allr   rg   rh   r   r   )r   rW   r   r   r=   "callback_on_step_end_tensor_inputsr   s   `      r!   check_inputsz'Cosmos2TextToImagePipeline.check_inputsg  s_    B;!urzQWX^W__dejdkklmnn-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 Jb)@ pHs   C%Cc                     | j                   S r   _guidance_scaler   s    r!   guidance_scalez)Cosmos2TextToImagePipeline.guidance_scale  s    ###r#   c                      | j                   dkD  S )NrH   r   r   s    r!   r   z6Cosmos2TextToImagePipeline.do_classifier_free_guidance  s    ##c))r#   c                     | j                   S r   )_num_timestepsr   s    r!   num_timestepsz(Cosmos2TextToImagePipeline.num_timesteps  s    """r#   c                     | j                   S r   )_current_timestepr   s    r!   current_timestepz+Cosmos2TextToImagePipeline.current_timestep  s    %%%r#   c                     | j                   S r   )
_interruptr   s    r!   	interruptz$Cosmos2TextToImagePipeline.interrupt  s    r#   #   g      @pilr(   r   output_typereturn_dictcallback_on_step_endr   c                    | j                   t        d| j                   d      t        |t        t
        f      r|j                  }d}| j                  ||||
|       || _        d| _	        d| _
        | j                  }| j                   ~| j                   j                  |       |Ft        |t              r|gn|}|D ],  }| j                   j                  |      rt        d| d       | j                   j                  d       |t        |t              rd}n-|t        |t              rt!        |      }n|
j"                  d	   }| j%                  ||| j&                  ||
|||
      \  }
}t(        j*                  j,                  j/                         rt(        j0                  nt(        j2                  }t)        j4                  d	d||      }t7        | j8                  ||      \  }}| j8                  j:                  j=                  dd      dk(  r0| j8                  j>                  d   | j8                  j>                  d<   | j@                  jB                  }| j@                  j:                  jD                  }| jG                  ||z  ||||t(        j0                  |||		      }	|	jI                  dd|||      }t!        |      || j8                  jJ                  z  z
  }t!        |      | _&        | jO                  |      5 }tQ        |      D ]  \  }}| jR                  r|| _	        | j8                  j>                  |   } | | dz   z  }!d|!z
  }"d|!z
  }#|! }$|!jU                  |	j"                  d	         j                  |      }%|	|"z  }&|&j                  |      }&| jA                  |&|%|
|d      d	   }'|#|	z  |$|'jW                         z  z   j                  |      }'| j&                  rV| jA                  |&|%||d      d	   }(|#|	z  |$|(jW                         z  z   j                  |      }(|'| jX                  |'|(z
  z  z   }'|	|'z
  | z  }'| j8                  j[                  |'||	d      d	   }	|Zi })|D ]  }*t]               |*   |)|*<     || |||)      }+|+j_                  d|	      }	|+j_                  d|
      }
|+j_                  d|      }|t!        |      dz
  k(  s'|dz   |kD  r/|dz   | j8                  jJ                  z  d	k(  r|ja                          tb        ste        jf                           	 ddd       d| _	        |dk(  sFt)        jh                  | jj                  j:                  jl                        jo                  d| jj                  j:                  jp                  ddd      j                  |	jr                  |	jB                        },dt)        jh                  | jj                  j:                  jt                        jo                  d| jj                  j:                  jp                  ddd      j                  |	jr                  |	jB                        z  }-|	|-z  | j8                  j:                  jv                  z  |,z   }	| jj                  jy                  |	j                  | jj                  jB                        d      d	   }.| j                   +| j                   j                  |       | jz                  j}                  |.d      }.|.dz  j                  t        j                        }.g }/|.D ].  }0| j                   j                  |0      }0|/j                  |0       0 t        j                  |/      j                  t        j0                        dz  dz  dz
  }.t)        j                  |.      j                  d	dddd       }.| jz                  j}                  |.|      }.| j                   j                  d       n| jz                  j}                  |.|      }.|.D 1cg c]  }1|1d	   	 }2}1t        |.t(        j                        rt)        j                  |2      }2n<t        |.t        j                        r"t        j                  |2      }2n|	ddddd	f   }2| j                          |s|2fS t        |2!      S # 1 sw Y   xY wc c}1w )"a  
        The call function to 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`, defaults to `768`):
                The height in pixels of the generated image.
            width (`int`, defaults to `1360`):
                The width in pixels of the generated image.
            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`.
            num_images_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 [`CosmosImagePipelineOutput`] 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.

        Examples:

        Returns:
            [`~CosmosImagePipelineOutput`] or `tuple`:
                If `return_dict` is `True`, [`CosmosImagePipelineOutput`] 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.r   Fz5Cosmos Guardrail detected unsafe text in the prompt: zR. Please ensure that the prompt abides by the NVIDIA Open Model License Agreement.rs   r   )rW   r~   r   r   r=   r>   r)   rX   )rY   )r)   r+   rL   zerorI   rc   )total)hidden_statestimestepencoder_hidden_statespadding_maskr   )r   r<   r=   r>   latentrH   np)r      g     o@r   rE   r
   )images)Kr?   r-   r4   rg   r   r   tensor_inputsr   r   r   r   rf   rk   rh   check_text_safetyr   r5   rl   r   r   rm   backendsmpsis_availablefloat32float64linspacer9   r6   r   getr+   rB   rY   in_channelsr   	new_zerosorderr   progress_barrt   r   expandfloatr   steplocalspopupdateXLA_AVAILABLExm	mark_steptensorrC   latents_meanr   z_dimr)   latents_stdrK   decoderT   postprocess_videoastyper   uint8check_video_safetyappendstack
from_numpypermuteTensorndarraymaybe_free_model_hooksr   )3r   rW   r~   r   r   r(   r   r   r   r<   r=   r>   r   r   r   r   rX   r   r)   prompt_listpr   sigmas_dtyper+   r*   transformer_dtyper   r   num_warmup_stepsr   r{   tcurrent_sigma	current_tc_inc_skipc_outr   latent_model_input
noise_prednoise_pred_uncondcallback_kwargsr   callback_outputsr   r   videovideo_batchvidbatchimages3                                                      r!   __call__z#Cosmos2TextToImagePipeline.__call__  sb   ` &;DNN;K LS T  *-=?U,VW1E1S1S.
 	&&%@bc-!%''*""6*!*4VS*Avhv$ A..@@C(STUSV WX Y  ""5) *VS"9JJvt$<VJ&,,Q/J +(,(H(H"7'#9 3  	
	
" ).(:(:(G(G(Iu}}u}}1&9N);DNNSYbh)i&	&>>  $$%8&A[P(,(=(=b(ADNN!!"% !,,22#//66BB&&.. MM

 ((AvuDU(V y>,?$..BVBV,VV!)n%89 7	#\!), 6#1>>)*& $ 5 5a 8)]Q->?	9}Y"
$++GMM!,<=@@ARS%,t^"%7%:%:;L%M"!--"4%*7!- % .  
 %w.9I9I9K1KKOOPab
33(,(8(8&8!).D%1$) )9 ) )% *0')9EDUD[D[D]<])](a(abs(t%!+d.A.AZRcEc.d!dJ%
2mC
..--j!WRW-XYZ['3&(O? 9-3Xa[*9';D!Q'X$.229gFG$4$8$8-$XM-=-A-ABZ\r-s* I**A9I/IqSTuX\XfXfXlXlNlpqNq '') LLNm6#7	#r "&h&TXX__99:a..1a8GNNGMM2 
 TXX__-H-H I N NqRVRZRZRaRaRgRgijlmop q t t! K +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]>^+01%U1X1E1%.E*E2::.Aq!G$E 	##%8O(66G7	# 7	#j 2s   Hb5b5c5b?r   )NrV   NN)NTr   NNrV   NN)r   r   r   NNNN)NN)-r$   r%   r&   __doc__model_cpu_offload_seqr   _optional_componentsr   r	   r   r   r   r   r"   r   rh   r   intr   rm   r)   rY   r}   rj   r   r   	Generatorr   r   propertyr   r   r   r   r   no_gradr   EXAMPLE_DOC_STRINGr   r   r   r   r   r  __classcell__)r4   s   @r!   r;   r;      sH   , =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5n '+)-MQ*.99 !9 	9
 9 9 $9 &9 E%//43H"HIJ9 %,,'9 
9F +/b< $ $ * * # # & &   U]]_12 )-;?#% #/0MQ*.049=%*  9B#&'F7c49n%F7 "%T#Y"78F7 	F7
 F7 !F7 F7  (}F7 E%//43H"HIJF7 %,,'F7  -F7 !) 6F7 c]F7 F7 '(Cd+T124DF\\]
F7$ -1I%F7& !'F7 3 F7r#   r;   )NNNN)3r/   typingr   r   r   r   r   numpyr   rm   transformersr   r	   	callbacksr   r   modelsr   r   
schedulersr   utilsr   r   r   r   utils.torch_utilsr   rT   r   pipeline_utilsr   pipeline_outputr   cosmos_guardrailr   torch_xla.core.xla_modelcore	xla_modelr   r   
get_loggerr$   rp   r	  r  rh   r)   r   r9   r;   r'   r#   r!   <module>r     s     8 8   8 A @ 9 n n - - . 6 !"4  ))MM			H	% 2 *.15%)$(8*!#8* U3,-.8* S	"	8*
 T%[!8*vZ7!2 Z7r#   