o
    GiY                     @   sJ  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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 Z!e rid dl"m#Z# nG dd dZ#e rd dl$m%  m&Z' dZ(ndZ(e)e*Z+dZ,	ddej-dej.dB de/fddZ0dZ1G dd deZ2dS )     )CallableN)AutoTokenizer"Qwen2_5_VLForConditionalGeneration   )MultiPipelineCallbacksPipelineCallback)PipelineImageInput)AutoencoderKLWanCosmosTransformer3DModel)UniPCMultistepScheduler)is_cosmos_guardrail_availableis_torch_xla_availableis_torchvision_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   i/home/ubuntu/.local/lib/python3.10/site-packages/diffusers/pipelines/cosmos/pipeline_cosmos2_5_predict.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.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_distr"   argmaxlatentsz3Could not access latents of provided encoder_output)hasattrr&   r"   moder(   AttributeError)r#   r$   r%   r   r   r   retrieve_latentsI   s   

r,   aR  
    Examples:
        ```python
        >>> import torch
        >>> from diffusers import Cosmos2_5_PredictBasePipeline
        >>> from diffusers.utils import export_to_video, load_image, load_video

        >>> model_id = "nvidia/Cosmos-Predict2.5-2B"
        >>> pipe = Cosmos2_5_PredictBasePipeline.from_pretrained(
        ...     model_id, revision="diffusers/base/post-trained", torch_dtype=torch.bfloat16
        ... )
        >>> pipe = pipe.to("cuda")

        >>> # Common negative prompt reused across modes.
        >>> 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."
        ... )

        >>> # Text2World: generate a 93-frame world video from text only.
        >>> prompt = (
        ...     "As the red light shifts to green, the red bus at the intersection begins to move forward, its headlights "
        ...     "cutting through the falling snow. The snowy tire tracks deepen as the vehicle inches ahead, casting fresh "
        ...     "lines onto the slushy road. Around it, streetlights glow warmer, illuminating the drifting flakes and wet "
        ...     "reflections on the asphalt. Other cars behind start to edge forward, their beams joining the scene. "
        ...     "The stillness of the urban street transitions into motion as the quiet snowfall is punctuated by the slow "
        ...     "advance of traffic through the frosty city corridor."
        ... )
        >>> video = pipe(
        ...     image=None,
        ...     video=None,
        ...     prompt=prompt,
        ...     negative_prompt=negative_prompt,
        ...     num_frames=93,
        ...     generator=torch.Generator().manual_seed(1),
        ... ).frames[0]
        >>> export_to_video(video, "text2world.mp4", fps=16)

        >>> # Image2World: condition on a single image and generate a 93-frame world video.
        >>> prompt = (
        ...     "A high-definition video captures the precision of robotic welding in an industrial setting. "
        ...     "The first frame showcases a robotic arm, equipped with a welding torch, positioned over a large metal structure. "
        ...     "The welding process is in full swing, with bright sparks and intense light illuminating the scene, creating a vivid "
        ...     "display of blue and white hues. A significant amount of smoke billows around the welding area, partially obscuring "
        ...     "the view but emphasizing the heat and activity. The background reveals parts of the workshop environment, including a "
        ...     "ventilation system and various pieces of machinery, indicating a busy and functional industrial workspace. As the video "
        ...     "progresses, the robotic arm maintains its steady position, continuing the welding process and moving to its left. "
        ...     "The welding torch consistently emits sparks and light, and the smoke continues to rise, diffusing slightly as it moves upward. "
        ...     "The metal surface beneath the torch shows ongoing signs of heating and melting. The scene retains its industrial ambiance, with "
        ...     "the welding sparks and smoke dominating the visual field, underscoring the ongoing nature of the welding operation."
        ... )
        >>> image = load_image(
        ...     "https://media.githubusercontent.com/media/nvidia-cosmos/cosmos-predict2.5/refs/heads/main/assets/base/robot_welding.jpg"
        ... )
        >>> video = pipe(
        ...     image=image,
        ...     video=None,
        ...     prompt=prompt,
        ...     negative_prompt=negative_prompt,
        ...     num_frames=93,
        ...     generator=torch.Generator().manual_seed(1),
        ... ).frames[0]
        >>> export_to_video(video, "image2world.mp4", fps=16)

        >>> # Video2World: condition on an input clip and predict a 93-frame world video.
        >>> prompt = (
        ...     "The video opens with an aerial view of a large-scale sand mining construction operation, showcasing extensive piles "
        ...     "of brown sand meticulously arranged in parallel rows. A central water channel, fed by a water pipe, flows through the "
        ...     "middle of these sand heaps, creating ripples and movement as it cascades down. The surrounding area features dense green "
        ...     "vegetation on the left, contrasting with the sandy terrain, while a body of water is visible in the background on the right. "
        ...     "As the video progresses, a piece of heavy machinery, likely a bulldozer, enters the frame from the right, moving slowly along "
        ...     "the edge of the sand piles. This machinery's presence indicates ongoing construction work in the operation. The final frame "
        ...     "captures the same scene, with the water continuing its flow and the bulldozer still in motion, maintaining the dynamic yet "
        ...     "steady pace of the construction activity."
        ... )
        >>> input_video = load_video(
        ...     "https://github.com/nvidia-cosmos/cosmos-predict2.5/raw/refs/heads/main/assets/base/sand_mining.mp4"
        ... )
        >>> video = pipe(
        ...     image=None,
        ...     video=input_video,
        ...     prompt=prompt,
        ...     negative_prompt=negative_prompt,
        ...     num_frames=93,
        ...     generator=torch.Generator().manual_seed(1),
        ... ).frames[0]
        >>> export_to_video(video, "video2world.mp4", fps=16)

        >>> # To produce an image instead of a world (video) clip, set num_frames=1 and
        >>> # save the first frame: pipe(..., num_frames=1).frames[0][0].
        ```
c                -       s  e Zd ZdZdZg dZdgZdgZ	dMdede	de
d	ed
edef fddZ				dNdeee B dedejdB dejdB fddZ								dOd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				 	 					dPd!ejdB d"ed#e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		dQd-d.Zed/d0 Zed1d2 Zed3d4 Zed5d6 Z ed7d8 Z!e" e#e$ddddddd d9d:dddddd;ddd)gdd<d=fd>e%dB d!ee% dB deee B dB deee B dB d$ed%ed?ed@edAe&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 dBedB dCedDe'eedge(e)B f dB dEee dedFe&dGef*dHdIZ*d!ejdJed*ejfdKdLZ+  Z,S )RCosmos2_5_PredictBasePipelinea'  
    Pipeline for [Cosmos Predict2.5](https://github.com/nvidia-cosmos/cosmos-predict2.5) base model.

    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 ([`Qwen2_5_VLForConditionalGeneration`]):
            Frozen text-encoder. Cosmos Predict2.5 uses the [Qwen2.5
            VL](https://huggingface.co/Qwen/Qwen2.5-VL-7B-Instruct) encoder.
        tokenizer (`AutoTokenizer`):
            Tokenizer associated with the Qwen2.5 VL encoder.
        transformer ([`CosmosTransformer3DModel`]):
            Conditional Transformer to denoise the encoded image latents.
        scheduler ([`UniPCMultistepScheduler`]):
            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)r(   prompt_embedsnegative_prompt_embedssafety_checkerNtext_encoder	tokenizertransformervae	schedulerc           	         s,  t    |d u rt }| j||||||d t| dd r%dt| jj nd| _t| dd r6dt	| jj nd| _
t| j
d| _t| jjdd d ur^t| jjjd| jjjddd nd }t| jjd	d d ur~t| jjjd| jjjddd nd }|| _|| _| jd u s| jd u rtd
d S )N)r4   r1   r2   r3   r5   r0   r4   r         )vae_scale_factorlatents_meanr   latents_stdzDVAE configuration must define both `latents_mean` and `latents_std`.)superr   r   register_modulesgetattrsumr4   temperal_downsamplevae_scale_factor_temporallenvae_scale_factor_spatialr   video_processorconfigtorchtensorr9   viewz_dimfloatr:   
ValueError)	r   r1   r2   r3   r4   r5   r0   r9   r:   	__class__r   r   r      s6   
	"	"((z&Cosmos2_5_PredictBasePipeline.__init__   promptmax_sequence_lengthdevicedtypec              
   C   sN  |p| j }|p
| jj}t|tr|gn|}g }tt|D ]<}ddddgddd|| dgdg}| jj|ddd|dd	d
}t|t	sMd|v rM|d n|}t
|}|| qt
j|dd}| j||dd}	|	j}
g }tdt|
D ]}|
| |
| jddd |
| jdddd  }|| qwt
j|dd}|j||d}|S )NsystemtextzKYou are a helpful assistant who will provide prompts to an image generator.)typerS   )rolecontentuserTF
max_length)tokenizeadd_generation_promptadd_vision_idrX   
truncationpadding	input_idsr   dim)output_hidden_statesr   )r`   keepdimg:0yE>rQ   rP   )_execution_devicer1   rQ   
isinstancestrrangerA   r2   apply_chat_templatelistrE   
LongTensorappendstacktohidden_statesmeanstdcat)r   rN   rO   rP   rQ   input_ids_batch
sample_idxconversationsr^   outputsro   normalized_hidden_states	layer_idxnormalized_stater.   r   r   r   _get_prompt_embeds   s\   



z0Cosmos2_5_PredictBasePipeline._get_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   )rN   rO   rP   rQ   r   rb   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`.)re   rf   rg   rA   shaperz   repeatrG   DEFAULT_NEGATIVE_PROMPTrT   	TypeErrorrJ   )r   rN   r{   r|   r}   r.   r/   rO   rP   rQ   
batch_size_seq_lenr   r   r   encode_promptD  sH   
&

z+Cosmos2_5_PredictBasePipeline.encode_prompt        ]   videor   num_channels_latentsheightwidthnum_frames_innum_frames_outr$   r(   returnc                    sb  t  trt |krtdt  d| d|}|}|d j d }|j }|j }|||||f}|dkro|d u rFt| |
|	d}tj|d|||f|j	|j
d}tj|d|ddf|j	|j
d}t|}||||fS d u rwtdt tjojd	kojd d
k }|rj||j|
jj	dt  tr fddt|D }n
 fddD }tj|dd|	}jj|
|	d}jj|
|	d}|| | }|d u rt| |
|	d}n|j|
|	d}|d|||f}||}||}|d j d }|dd|ddd}d|d d d d d|f< || 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$   rP   rQ   rd   z@`video` must be provided when `num_frames_in` is greater than 0.   r   rP   rQ   c                    s.   g | ]}t j| d  | dqS )r   )r$   r,   r4   encode	unsqueeze).0ir$   r   r   r   r   
<listcomp>  s     zACosmos2_5_PredictBasePipeline.prepare_latents.<locals>.<listcomp>c                    s$   g | ]}t j|d  qS )r   r   )r   vid)r$   r   r   r   r     s   $ r_   r         ?)rf   rj   rA   rJ   r@   rB   r   rE   zerosrQ   rP   
zeros_likeTensorndimr   rC   preprocess_videorn   r4   rh   rr   r9   r:   new_ones	new_zerossize)r   r   r   r   r   r   r   r   r|   rQ   rP   r$   r(   BCTHWr   	cond_maskcond_indicatorcond_latentsneeds_preprocessingr9   r:   padding_shapeones_paddingzeros_paddingnum_cond_latent_framesr   r   r   prepare_latents  sj   


&


z-Cosmos2_5_PredictBasePipeline.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spt|tsrt dt| d S 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=Cosmos2_5_PredictBasePipeline.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>Cosmos2_5_PredictBasePipeline.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 )rJ   allr   rf   rg   rj   rT   )r   rN   r   r   r.   "callback_on_step_end_tensor_inputsr   r   r   check_inputs  s&   z*Cosmos2_5_PredictBasePipeline.check_inputsc                 C      | j S r   _guidance_scaler   r   r   r   guidance_scale     z,Cosmos2_5_PredictBasePipeline.guidance_scalec                 C   s
   | j dkS )Nr   r   r   r   r   r   r|     s   
z9Cosmos2_5_PredictBasePipeline.do_classifier_free_guidancec                 C   r   r   )_num_timestepsr   r   r   r   num_timesteps  r   z+Cosmos2_5_PredictBasePipeline.num_timestepsc                 C   r   r   )_current_timestepr   r   r   r   current_timestep  r   z.Cosmos2_5_PredictBasePipeline.current_timestepc                 C   r   r   )
_interruptr   r   r   r   	interrupt  r   z'Cosmos2_5_PredictBasePipeline.interrupt$   g      @pilg?r   image
num_framesnum_inference_stepsr   output_typereturn_dictcallback_on_step_endr   conditional_frame_timestepnum_latent_conditional_framesc           ;      C   s  | j du rtd| j dt|ttfr|j}| ||||| |	| _d| _	d| _
| j}| j durY| j | |durYt|trD|gn|}|D ]}| j |sXtd| dqH|duret|tred}n|durst|trst|}n|jd }| j||| j|
||||d	\}}| jj}| jj}d}|dur|dkrtd
| dtjj|d}tj|t||d dddgdd}|d}d}nH|du rtj ||d||tj!d}d}n5|dkrtd| d|dvrtd| d|d  d }t|}||k rtd| d| d|}|dusJ | j"#|||}|du rE|dkrE||jd k rE|dddd| dddddf }|}|jd |k r{||jd  } |ddddddddddf }!|!dd| dd}"tj||"fdd}||ksJ d|d|d|j||d}| jj$j%d }#| j&|||
 |#||||| jtj'|||d\}}$}%}&t(|&| }'|%|}%|j)dd|||d}(| j*j+||d | j*j,})t|)| _-t|)|| j*j.  }*||$ |% }+| j/|d},t0|)D ]\}-}.| j1rq|.2 3 | _	t4| j*j5|- 3 dj||d}/|%|$ d|% |  }0|0|}0|&|' d|& |/  }1| j|0|%|1||(ddd }2|+|2d|%   }2| jrh| j|0|%|1||(ddd }3|+|3d|%   }3|2| j6|2|3   }2| j*j7|2|.|ddd }|duri }4|D ]
}5t8 |5 |4|5< q}|| |-|.|4}6|69d |}|69d!|}|69d"|}|-t|)d ks|-d |*kr|-d | j*j. dkr|,:  t;rt<=  qW d   n	1 sw   Y  d| _	|d#ksc| j>|j?|j}7| j@|j?|j}8||8 |7 }| jjA|| jjddd }| B||}| j dusJ | j | | j"jC|d$d%}|d& DtEj!}g }9|D ]}:| j F|:}:|9G|: q0tEH|9DtEj'd' d d }tI|Jddddd}| j"jC||d%}n|}| K  |so|fS tL|d(S ))a  
        The call function to the pipeline for generation. Supports three modes:

        - **Text2World**: `image=None`, `video=None`, `prompt` provided. Generates a world clip.
        - **Image2World**: `image` provided, `video=None`, `prompt` provided. Conditions on a single frame.
        - **Video2World**: `video` provided, `image=None`, `prompt` provided. Conditions on an input clip.

        Set `num_frames=93` (default) to produce a world video, or `num_frames=1` to produce a single image frame (the
        above in "*2Image mode").

        Outputs follow `output_type` (e.g., `"pil"` returns a list of `num_frames` PIL images per prompt).

        Args:
            image (`PIL.Image.Image`, `np.ndarray`, `torch.Tensor`, *optional*):
                Optional single image for Image2World conditioning. Must be `None` when `video` is provided.
            video (`list[PIL.Image.Image]`, `np.ndarray`, `torch.Tensor`, *optional*):
                Optional input video for Video2World conditioning. Must be `None` when `image` is provided.
            prompt (`str` or `list[str]`, *optional*):
                The prompt or prompts to guide generation. Required unless `prompt_embeds` is supplied.
            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`):
                Number of output frames. Use `93` for world (video) generation; set to `1` to return a single frame.
            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_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.
            num_latent_conditional_frames (`int`, defaults to `2`):
                Number of latent conditional frames to use for Video2World conditioning. The number of pixel frames
                extracted from the input video is calculated as `4 * (num_latent_conditional_frames - 1) + 1`. Set to 1
                for Image2World-like behavior (single frame conditioning).

        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   )rN   r{   r|   r}   r.   r/   rP   rO   z,batch_size must be 1 for image input (given )r_   r   )rQ   z,batch_size must be 1 for video input (given )r   r   z6num_latent_conditional_frames must be 1 or 2, but got r6   zInput video has only z* frames but Video2World requires at least z frames for conditioning.r   rb   zexpected (num_frames_in=z) <= (num_frames_out=r   )r   r   r   r   r   r   r   r|   rQ   rP   r$   r(   )rP   )total)ro   condition_masktimestepencoder_hidden_statespadding_maskr   )r   r(   r.   r/   latentnp)r      g     o@)frames)Mr0   rJ   rL   rf   r   r   tensor_inputsr   r   r   r   re   rn   rg   check_text_safetyrj   rA   r   r   r|   r4   rQ   r3   torchvision
transforms
functional	to_tensorr   rE   rr   r   r   r   uint8rC   r   rD   in_channelsr   float32	ones_liker   r5   set_timesteps	timestepsr   orderprogress_bar	enumerater   cpuitemrF   sigmasr   steplocalspopupdateXLA_AVAILABLExm	mark_stepr9   rP   r:   decode_match_num_framespostprocess_videoastyper   check_video_safetyrl   rm   
from_numpypermutemaybe_free_model_hooksr   );r   r   r   rN   r{   r   r   r   r   r   r}   r$   r(   r.   r/   r   r   r   r   rO   r   r   rP   prompt_listpr   	vae_dtypetransformer_dtyper   frames_to_extracttotal_input_framesr   n_pad_frames
last_frame
pad_framesr   cond_latentr   r   cond_timestepr   r   num_warmup_stepsgt_velocityr   r   tsigma_t
in_latentsin_timestep
noise_prednoise_pred_negcallback_kwargsr   callback_outputsr9   r:   video_batchr   r   r   r   __call__!  sd  
g



(

$(& 


		
6<

z&Cosmos2_5_PredictBasePipeline.__call__target_num_framesc                 C   s   |dks|j d |kr|S t| jd}tj||dd}|j d }||k rK|d d d d dd d d d d f dd|| dd}tj||gdd}|S ||kr\|d d d d d |f }|S )Nr   r   r   )repeatsr`   rb   r_   )r   maxr@   rE   repeat_interleaver   rr   )r   r   r  frames_per_latentcurrent_framespadr   r   r   r   j  s   
8z/Cosmos2_5_PredictBasePipeline._match_num_framesr   )NrM   NN)NTr   NNrM   NN)
r   r   r   r   r   TNNNN)NN)-r   r    r!   __doc__model_cpu_offload_seqr   _optional_components_exclude_from_cpu_offloadr   r   r
   r	   r   r   r   rg   rj   intrE   rP   rQ   rz   boolr   r   	Generatorr   r   propertyr   r|   r   r   r   no_gradr   EXAMPLE_DOC_STRINGr   rI   r   r   r   r  r   __classcell__r   r   rK   r   r-      sf   	-

I
	

Y	

[






	
  "Ir-   )Nr"   )3typingr   numpyr   rE   transformersr   r   	callbacksr   r   image_processorr   modelsr	   r
   
schedulersr   utilsr   r   r   r   r   utils.torch_utilsr   rC   r   pipeline_utilsr   pipeline_outputr   !torchvision.transforms.functionalr   cosmos_guardrailr   torch_xla.core.xla_modelcore	xla_modelr   r   
get_loggerr   loggerr   r   r!  rg   r,   r$  r-   r   r   r   r   <module>   sF   

b