o
    Gi                  
   @   s  d dl Z d dl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mZ dd
lmZ ddlmZ ddlmZ ddlmZ e rdd dl m!Z! nG dd dZ!e rzd dl"m#  m$Z% dZ&ndZ&e'e(Z)dZ*dZ+				d%de,dB de-ej.B dB de/e, dB de/e0 dB fddZ1	d&dej2dej3dB d e-fd!d"Z4G d#d$ d$eZ5dS )'    N)Callable)T5EncoderModelT5TokenizerFast   )MultiPipelineCallbacksPipelineCallback)PipelineImageInput)AutoencoderKLCosmosCosmosTransformer3DModel)EDMEulerScheduler)is_cosmos_guardrail_availableis_torch_xla_availableloggingreplace_example_docstring)randn_tensor)VideoProcessor   )DiffusionPipeline   )CosmosPipelineOutput)CosmosSafetyCheckerc                   @   s   e Zd Zdd ZdS )r   c                 O   s   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kwargs r   j/home/ubuntu/.local/lib/python3.10/site-packages/diffusers/pipelines/cosmos/pipeline_cosmos_video2world.py__init__&   s   zCosmosSafetyChecker.__init__N)__name__
__module____qualname__r   r   r   r   r   r   %   s    r   TFa  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.aA	  
    Examples:
        Image conditioning:

        ```python
        >>> import torch
        >>> from diffusers import CosmosVideoToWorldPipeline
        >>> from diffusers.utils import export_to_video, load_image

        >>> model_id = "nvidia/Cosmos-1.0-Diffusion-7B-Video2World"
        >>> pipe = CosmosVideoToWorldPipeline.from_pretrained(model_id, torch_dtype=torch.bfloat16)
        >>> pipe.to("cuda")

        >>> prompt = "The video depicts a long, straight highway stretching into the distance, flanked by metal guardrails. The road is divided into multiple lanes, with a few vehicles visible in the far distance. The surrounding landscape features dry, grassy fields on one side and rolling hills on the other. The sky is mostly clear with a few scattered clouds, suggesting a bright, sunny day."
        >>> image = load_image(
        ...     "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/cosmos/cosmos-video2world-input.jpg"
        ... )

        >>> video = pipe(image=image, prompt=prompt).frames[0]
        >>> export_to_video(video, "output.mp4", fps=30)
        ```

        Video conditioning:

        ```python
        >>> import torch
        >>> from diffusers import CosmosVideoToWorldPipeline
        >>> from diffusers.utils import export_to_video, load_video

        >>> model_id = "nvidia/Cosmos-1.0-Diffusion-7B-Video2World"
        >>> pipe = CosmosVideoToWorldPipeline.from_pretrained(model_id, torch_dtype=torch.bfloat16)
        >>> pipe.transformer = torch.compile(pipe.transformer)
        >>> pipe.to("cuda")

        >>> prompt = "The video depicts a winding mountain road covered in snow, with a single vehicle traveling along it. The road is flanked by steep, rocky cliffs and sparse vegetation. The landscape is characterized by rugged terrain and a river visible in the distance. The scene captures the solitude and beauty of a winter drive through a mountainous region."
        >>> video = load_video(
        ...     "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/cosmos/cosmos-video2world-input-vid.mp4"
        ... )[
        ...     :21
        ... ]  # This example uses only the first 21 frames

        >>> video = pipe(video=video, prompt=prompt).frames[0]
        >>> export_to_video(video, "output.mp4", fps=30)
        ```
num_inference_stepsdevice	timestepssigmasc                 K   s  |dur|durt d|dur>dtt| jj v }|s(t d| j d| jd||d| | j}t	|}||fS |durpdtt| jj v }|sZt 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.
    NzYOnly 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_sigmasr   r   r   retrieve_timestepsn   s2   r1   sampleencoder_output	generatorsample_modec                 C   sR   t | dr|dkr| j|S t | dr|dkr| j S t | dr%| jS td)Nlatent_distr2   argmaxlatentsz3Could not access latents of provided encoder_output)hasattrr6   r2   moder8   AttributeError)r3   r4   r5   r   r   r   retrieve_latents   s   

r<   c                /       s  e Zd ZdZdZg dZdgZ	dJdedede	d	e
d
edef fddZ				dKdeee B dedejdB dejdB fddZ								dLdeee B deee B dB dededejdB dejdB dedejdB dejdB fddZ					 				dMd!ejd"ed#d$d%ed&ed'eded(edejdB dejdB d)ejeej B dB d*ejdB d+ejfd,d-Z				dNd.d/Zed0d1 Zed2d3 Zed4d5 Zed6d7 Zed8d9 Z e! e"e#d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$d!ee$ deee B deee B dB d%ed&ed'ed@edAe%d(edBe%dCededB d)ejeej B dB d*ejdB dejdB dejdB dDedB dEedFe&eegdf e'B e(B dB dGee def,dHdIZ)  Z*S )OCosmosVideoToWorldPipelinea  
    Pipeline for image-to-world and video-to-world generation using [Cosmos
    Predict-1](https://github.com/nvidia-cosmos/cosmos-predict1).

    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 ([`AutoencoderKLCosmos`]):
            Variational Auto-Encoder (VAE) Model to encode and decode videos to and from latent representations.
    ztext_encoder->transformer->vae)r8   prompt_embedsnegative_prompt_embedssafety_checkerNtext_encoder	tokenizertransformervaer.   c                    sx   t    |d u rt }| j||||||d t| dd r"| jjjnd| _t| dd r0| jjj	nd| _
t| j
d| _d S )N)rD   rA   rB   rC   r.   r@   rD      )vae_scale_factor)superr   r   register_modulesgetattrrD   configtemporal_compression_ratiovae_scale_factor_temporalspatial_compression_ratiovae_scale_factor_spatialr   video_processor)r   rA   rB   rC   rD   r.   r@   r,   r   r   r      s   
	
z#CosmosVideoToWorldPipeline.__init__   promptmax_sequence_lengthr"   dtypec              	   C   s  |p| j }|p
| jj}t|tr|gn|}| j|d|ddddd}|j}|j 	|}| j|dddj}|j
d |j
d kr`t||s`| j|d d |d	 df }	td
| d|	  | j|	||dj}
|
j	||d}
|jd	d }t|D ]\}}d|
||d f< q~|
S )N
max_lengthTptF)paddingrU   
truncationreturn_tensorsreturn_lengthreturn_offsets_mappinglongest)rW   rY   r   zXThe following part of your input was truncated because `max_sequence_length` is set to  z	 tokens: )attention_mask)rT   r"   dimr   )_execution_devicerA   rT   
isinstancestrrB   	input_idsr^   booltoshapetorchequalbatch_decodeloggerwarninglast_hidden_statesumcpu	enumerate)r   rR   rS   r"   rT   text_inputstext_input_idsprompt_attention_maskuntruncated_idsremoved_textr>   lengthsilengthr   r   r   _get_t5_prompt_embeds   sD   
	  
z0CosmosVideoToWorldPipeline._get_t5_prompt_embedsTr   negative_promptdo_classifier_free_guidancenum_videos_per_promptr>   r?   c
              
   C   sb  |p| j }t|tr|gn|}|durt|}
n|jd }
|du r@| j||||	d}|j\}}}|d|d}||
| |d}|r|du r|durL|nt}t|trX|
|g n|}|durut	|t	|urut
dt	| dt	| d|
t|krtd	| d
t| d| d
|
 d	| j||||	d}|j\}}}|d|d}||
| |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_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
        Nr   )rR   rS   r"   rT   r   r]   z?`negative_prompt` should be the same type to `prompt`, but got z != .z`negative_prompt`: z has batch size z, but `prompt`: zT. Please make sure that passed `negative_prompt` matches the batch size of `prompt`.)ra   rb   rc   r-   rg   ry   repeatviewDEFAULT_NEGATIVE_PROMPTtype	TypeErrorr%   )r   rR   rz   r{   r|   r>   r?   rS   r"   rT   
batch_size_seq_lenr   r   r   encode_prompt  sH   
&

z(CosmosVideoToWorldPipeline.encode_prompt     y   Fvideor   num_channels_latents   heightwidth
num_framesinput_frames_guidancer4   r8   returnc              	      s"  t  trt |krtdt  d| dd}||kr9|d j d }d d d d | d f n+|d j d }|| }dd|dd}tj|gdd	t  trw fd
dt	|D }n
 fddD }tj|dd	
|	}jjjd urjjjjjj}}t|djjjdddd d d d d |df 
|}t|djjjdddd d d d d |df 
|}|| jjj | }n|jjj }|d j d }|j }|j }|||||f}|d u rt| |
|	d}n|j
|
|	d}|jjj }|d|||f}||}||}|dd|ddd}d|d d d d d |f< || d| |  }d  }}|r|dd|ddd}d|d d d d d |f< |}|s|| d| |  }||||||fS )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   r   r      r_   c                    s.   g | ]}t j| d  | dqS )r   )r4   r<   rD   encode	unsqueeze).0rw   r4   r   r   r   r   
<listcomp>  s     z>CosmosVideoToWorldPipeline.prepare_latents.<locals>.<listcomp>c                    s$   g | ]}t j|d  qS )r   r   )r   vid)r4   r   r   r   r     s   $ r]   r4   r"   rT   r"   rT         ?)rb   listr-   r%   sizerL   	new_zerosrh   catrangerf   rD   rJ   latents_meanlatents_stdtensorr   latent_channelsr.   
sigma_datarN   r   	sigma_maxnew_ones)r   r   r   r   r   r   r   r{   r   rT   r"   r4   r8   num_cond_framesnum_cond_latent_framesnum_padding_framesrW   init_latentsr   r   num_latent_frameslatent_heightlatent_widthrg   padding_shapeones_paddingzeros_paddingcond_indicator	cond_maskuncond_indicatoruncond_maskr   r   r   prepare_latentsp  sp   
*
..




z*CosmosVideoToWorldPipeline.prepare_latentsc                    s  |d dks|d dkrt d| d| d|d ur8t fdd|D s8t d j d	 fd
d|D  |d urK|d urKt d| d| d|d u rW|d u rWt d|d urnt|tsnt|tsnt dt| |d u rz|d u rzt d|d ur|d urt dd S d S )Nr   r   z8`height` and `width` have to be divisible by 16 but are z and r}   c                 3   s    | ]}| j v V  qd S N_callback_tensor_inputsr   kr   r   r   	<genexpr>  s    

z:CosmosVideoToWorldPipeline.check_inputs.<locals>.<genexpr>z2`callback_on_step_end_tensor_inputs` has to be in z, but found c                    s   g | ]	}| j vr|qS r   r   r   r   r   r   r     s    z;CosmosVideoToWorldPipeline.check_inputs.<locals>.<listcomp>zCannot forward both `prompt`: z and `prompt_embeds`: z2. Please make sure to only forward one of the two.zeProvide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined.z2`prompt` has to be of type `str` or `list` but is z-Either `image` or `video` has to be provided.z2Only one of `image` or `video` has to be provided.)r%   allr   rb   rc   r   r   )r   rR   r   r   r>   "callback_on_step_end_tensor_inputsimager   r   r   r   check_inputs  s.   
z'CosmosVideoToWorldPipeline.check_inputsc                 C      | j S r   _guidance_scaler   r   r   r   guidance_scale     z)CosmosVideoToWorldPipeline.guidance_scalec                 C   s
   | j dkS )Nr   r   r   r   r   r   r{     s   
z6CosmosVideoToWorldPipeline.do_classifier_free_guidancec                 C   r   r   )_num_timestepsr   r   r   r   num_timesteps  r   z(CosmosVideoToWorldPipeline.num_timestepsc                 C   r   r   )_current_timestepr   r   r   r   current_timestep  r   z+CosmosVideoToWorldPipeline.current_timestepc                 C   r   r   )
_interruptr   r   r   r   	interrupt  r   z$CosmosVideoToWorldPipeline.interrupt$   g      @gMbP?   pilr   r!   r   augment_sigmafpsoutput_typereturn_dictcallback_on_step_endr   c           ?      C   sB  | j du rtd| j dt|ttfr|j}| ||||||| |	| _d| _	d| _
| j}| j dura| j | |dur[t|trF|gn|}|D ]}| j |sZtd| dqJ| j d |durmt|trmd}n|dur{t|tr{t|}n|jd	 }| j||| j|||||d
\}}t| j||\}}| jj}| jj}|dur| j|||d}n| j|||}|j||d}| jjjd }| ||| ||||| j|
t j!|||\}}} }!}"}#|"|}"| jr|#|}#t j"|g|t j!d}|j#dd|||d}$t||| jj$  }%t|| _%| j&|d}&t'|D ]\}'}(| j(r(q|(| _	|()|jd	 |})| jj*|' }*||*k}+| j+|},| j+|*}-|+rS| d	 n| }.t,|j||t j!d}/||/|ddddddf   }0|0|, |- }0|.|0 d|. |  }0| j-|0|(}0|0|}0| j|0|)|||"|$ddd	 }1|}2| jr|+r|!d	 n|!}3t,|j||t j!d}4||4|ddddddf   }5|5|, |- }5|3|5 d|3 |  }5| j-|5|(}5|5|}5| j|5|)|||#|$ddd	 }6t .|6|1g}1t .|2|2g}2| jj/|1|(|2ddd }1| j j0d8  _0| jr7|1j1dd	d\}6}7|3| d|3 |6  }6|.| d|. |7  }7|7| j2|7|6   }1n
|.| d|. |1  }1| jj/|1|(|d|1dd	 }|dur{i }8|D ]
}9t3 |9 |8|9< qW|| |'|(|8}:|:4d|}|:4d|}|:4d|}|'t|d ks|'d |%kr|'d | jj$ d	kr|&5  t6rt78  qW d   n	1 sw   Y  d| _	|dks| jjj9dur| jjj9| jjj:};}<t "|;;d| jjj<dddddddd|=df |};t "|<;d| jjj<dddddddd|=df |}<||< | jjj> |; }n|| jjj> }| jj?||ddd	 }| j dur| j | | jj@|dd}|d AtBjC}g }=|D ]}>| j D|>}>|=E|> qNtBF|=AtBj!d d d }t G|Hd	dddd}| jj@||d}| j d n| jj@||d}n|}| I  |s|fS tJ|dS ) 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 `720`):
                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 `121`):
                The number of frames in the generated video.
            num_inference_steps (`int`, defaults to `36`):
                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 `30`):
                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.

        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.ro   r   r   )rR   rz   r{   r|   r>   r?   r"   rS   r   r   )rT   )totalr   )hidden_statestimestepencoder_hidden_statesr   condition_maskpadding_maskr   )r   r_   )r   pred_original_sampler8   r>   r?   latentr]   np)r      g     o@r   r   )frames)Kr@   r%   r,   rb   r   r   tensor_inputsr   r   r   r   ra   rf   rc   check_text_safetyr   r-   rg   r   r{   r1   r.   rD   rT   rC   rO   
preprocessr   preprocess_videorJ   in_channelsr   rh   float32r   r   orderr   progress_barrp   r   expandr$   _get_conditioning_c_inr   scale_model_inputr   step_step_indexchunkr   localspopupdateXLA_AVAILABLExm	mark_stepr   r   r   r   r   r   decodepostprocess_videoastyper   uint8check_video_safetyappendstack
from_numpypermutemaybe_free_model_hooksr   )?r   r   r   rR   rz   r   r   r   r!   r   r   r   r   r|   r4   r8   r>   r?   r   r   r   r   rS   r"   prompt_listpr   r#   	vae_dtypetransformer_dtyper   conditioning_latentsr   r   r   r   r   num_warmup_stepsr   rw   tr   current_sigmais_augment_sigma_greaterc_in_augmentc_in_originalcurrent_cond_indicator
cond_noisecond_latent
noise_predr2   current_uncond_indicatoruncond_noiseuncond_latentnoise_pred_uncondnoise_pred_condcallback_kwargsr   callback_outputsr   r   video_batchr   r   r   r   __call__  sv  
X









	


6_
..
z#CosmosVideoToWorldPipeline.__call__r   )NrQ   NN)NTr   NNrQ   NN)	r   r   r   TFNNNNNNNN)+r   r   r    __doc__model_cpu_offload_seqr   _optional_componentsr   r   r
   r	   r   r   r   rc   r   intrh   r"   rT   ry   re   Tensorr   	Generatorr   r   propertyr   r{   r   r   r   no_gradr   EXAMPLE_DOC_STRINGr   floatr   r   r   r  __classcell__r   r   rP   r   r=      sf   	 

.
	

X	

]
%





	
r=   r  )Nr2   )6r'   typingr   numpyr   rh   transformersr   r   	callbacksr   r   image_processorr   modelsr	   r
   
schedulersr   utilsr   r   r   r   utils.torch_utilsr   rO   r   pipeline_utilsr   pipeline_outputr   cosmos_guardrailr   torch_xla.core.xla_modelcore	xla_modelr   r   
get_loggerr   rk   r   r   r  rc   r"   r   r!  r1   r  r  r<   r=   r   r   r   r   <module>   s^   
	2


=
