o
    Giu                     @   sh  d dl mZmZmZmZmZ d dl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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 rnd dl&m'Z' nG dd dZ'e rd dl(m)  m*Z+ dZ,ndZ,e-e.Z/de
j0de1fddZ2	d#de
j0de
j3dB de4fddZ5dZ6d Z7G d!d" d"e#Z8dS )$    )CallableDictListOptionalUnionN)AutoTokenizer"Qwen2_5_VLForConditionalGeneration   )MultiPipelineCallbacksPipelineCallback)PipelineImageInput)AutoencoderKLWanCosmosControlNetModelCosmosTransformer3DModel)UniPCMultistepScheduler)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_cosmos2_5_transfer.py__init__&   s   zCosmosSafetyChecker.__init__N)__name__
__module____qualname__r"   r    r    r    r!   r   %   s    r   TFvideo
num_framesc              	   C   s   || j d  }|dkr0| d d d d dd d d d d f }tj| |dd|ddfdd} | S || j d k rJ| d d d d d |d d d d f } | S )Nr   r   r   dim)shapetorchcatrepeat)r&   r'   n_pad_frames
last_framer    r    r!   _maybe_pad_or_trim_video6   s   & &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_latentsA   s   

r<   a  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.a  
    Examples:
        ```python
        >>> import cv2
        >>> import numpy as np
        >>> import torch
        >>> from diffusers import Cosmos2_5_TransferPipeline, AutoModel
        >>> from diffusers.utils import export_to_video, load_video

        >>> model_id = "nvidia/Cosmos-Transfer2.5-2B"
        >>> # Load a Transfer2.5 controlnet variant (edge, depth, seg, or blur)
        >>> controlnet = AutoModel.from_pretrained(model_id, revision="diffusers/controlnet/general/edge")
        >>> pipe = Cosmos2_5_TransferPipeline.from_pretrained(
        ...     model_id, controlnet=controlnet, revision="diffusers/general", torch_dtype=torch.bfloat16
        ... )
        >>> pipe = pipe.to("cuda")

        >>> # Video2World with edge control: Generate video guided by edge maps extracted from input video.
        >>> prompt = (
        ...     "The video is a demonstration of robotic manipulation, likely in a laboratory or testing environment. It"
        ...     "features two robotic arms interacting with a piece of blue fabric. The setting is a room with a beige"
        ...     "couch in the background, providing a neutral backdrop for the robotic activity. The robotic arms are"
        ...     "positioned on either side of the fabric, which is placed on a yellow cushion. The left robotic arm is"
        ...     "white with a black gripper, while the right arm is black with a more complex, articulated gripper. At the"
        ...     "beginning, the fabric is laid out on the cushion. The left robotic arm approaches the fabric, its gripper"
        ...     "opening and closing as it positions itself. The right arm remains stationary initially, poised to assist."
        ...     "As the video progresses, the left arm grips the fabric, lifting it slightly off the cushion. The right arm"
        ...     "then moves in, its gripper adjusting to grasp the opposite side of the fabric. Both arms work in"
        ...     "coordination, lifting and holding the fabric between them. The fabric is manipulated with precision,"
        ...     "showcasing the dexterity and control of the robotic arms. The camera remains static throughout, focusing"
        ...     "on the interaction between the robotic arms and the fabric, allowing viewers to observe the detailed"
        ...     "movements and coordination involved in the task."
        ... )
        >>> 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."
        ... )
        >>> input_video = load_video(
        ...     "https://github.com/nvidia-cosmos/cosmos-transfer2.5/raw/refs/heads/main/assets/robot_example/robot_input.mp4"
        ... )
        >>> num_frames = 93

        >>> # Extract edge maps from the input video using Canny edge detection
        >>> edge_maps = [
        ...     cv2.Canny(cv2.cvtColor(np.array(frame.convert("RGB")), cv2.COLOR_RGB2BGR), 100, 200)
        ...     for frame in input_video[:num_frames]
        ... ]
        >>> edge_maps = np.stack(edge_maps)[None]  # (T, H, W) -> (1, T, H, W)
        >>> controls = torch.from_numpy(edge_maps).expand(3, -1, -1, -1)  # (1, T, H, W) -> (3, T, H, W)
        >>> controls = [Image.fromarray(x.numpy()) for x in controls.permute(1, 2, 3, 0)]
        >>> export_to_video(controls, "edge_controlled_video_edge.mp4", fps=30)

        >>> # Transfer inference with controls.
        >>> video = pipe(
        ...     controls=controls,
        ...     controls_conditioning_scale=1.0,
        ...     prompt=prompt,
        ...     negative_prompt=negative_prompt,
        ...     num_frames=num_frames,
        ... ).frames[0]
        >>> export_to_video(video, "edge_controlled_video.mp4", fps=30)
        ```
c                2       s  e Zd ZdZdZg dZdgZdgZ	dPdede	de
d	ed
ededee f fddZ				dQdeeee f dedejdB dejdB fddZ								dRdeeee f deeeee f  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			 	!	!						"dSd#eej d$ed%ed&ed'ed(ed)ededeej deej d*eeejeej f  d+eej d,ed-ejfd.d/Z							0dTd1d2Zed3d4 Z ed5d6 Z!ed7d8 Z"ed9d: Z#ed;d< Z$e% e&e'd=de(dddd!d>d?dddddd@ddd+gdd0ddfdAe)ee) B dBee*ee* f deeee f dB deeee f d&ed'ee dCee dDedEedFe*ded*eeejeej f  d+eej deej deej dGee dHedIeee+eee,gdf e-e.f  dJee dedKe*dLee dMee f.dNdOZ/  Z0S )UCosmos2_5_TransferPipelinea  
    Pipeline for Cosmos Transfer2.5, supporting auto-regressive inference.

    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 Transfer2.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.
        controlnet ([`CosmosControlNetModel`]):
            ControlNet used to condition generation on control inputs.
    z*text_encoder->transformer->controlnet->vae)r8   prompt_embedsnegative_prompt_embedssafety_checkerNtext_encoder	tokenizertransformervae	scheduler
controlnetc           
   	      s.  t    |d u rt }| j|||||||d t| dd r&dt| jj nd| _t| dd r7d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)rD   rA   rB   rC   rF   rE   r@   rD   r         )vae_scale_factorlatents_meanr   latents_stdzDVAE configuration must define both `latents_mean` and `latents_std`.)superr"   r   register_modulesgetattrsumrD   temperal_downsamplevae_scale_factor_temporallenvae_scale_factor_spatialr   video_processorconfigr,   tensorrJ   viewz_dimfloatrK   
ValueError)
r   rA   rB   rC   rD   rE   rF   r@   rJ   rK   	__class__r    r!   r"      s8   

"
"((z#Cosmos2_5_TransferPipeline.__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.)typerc   )rolecontentuserTF
max_length)tokenizeadd_generation_promptadd_vision_idrh   
truncationpadding	input_idsr   r)   )output_hidden_statesr   r(   )r*   keepdimg:0yE>ra   r`   )_execution_devicerA   ra   
isinstancestrrangerR   rB   apply_chat_templatelistr,   
LongTensorappendstacktohidden_statesmeanstdr-   )r   r^   r_   r`   ra   input_ids_batch
sample_idxconversationsrn   outputsr|   normalized_hidden_states	layer_idxnormalized_stater>   r    r    r!   _get_prompt_embeds   s\   



z-Cosmos2_5_TransferPipeline._get_prompt_embedsTr   negative_promptdo_classifier_free_guidancenum_videos_per_promptr>   r?   c
              
   C   sZ  |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|pId}t|trT|
|g n|}|durqt|t|urqt	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   )r^   r_   r`   ra   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`.)rr   rs   rt   rR   r+   r   r.   rW   rd   	TypeErrorrZ   )r   r^   r   r   r   r>   r?   r_   r`   ra   
batch_size_seq_lenr    r    r!   encode_prompt%  sH   
&

z(Cosmos2_5_TransferPipeline.encode_prompt        ]   r   r&   r   num_channels_latentsheightwidthnum_frames_innum_frames_outr4   r8   num_cond_latent_framesreturnc                    s<  t  trt |krtdt  d| d|}|}|d j d }|j }|j }|||||f}|d ur[|jdd  |dd  krStd|j d| d|j|
|	d}nt| |
|	d	}|d
krt	j
|d|||f|j|jd}t	j
|d|ddf|j|jd}t	|}||||fS d u rtd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|||f}||}||}||d|d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   z Unexpected `latents` shape, got z, expected r   r`   ra   )r4   r`   ra   r   rq   z@`video` must be provided when `num_frames_in` is greater than 0.c                    s.   g | ]}t j| d  | dqS r   )r4   r<   rD   encode	unsqueeze.0ir4   r   r&   r    r!   
<listcomp>       z>Cosmos2_5_TransferPipeline.prepare_latents.<locals>.<listcomp>c                    s$   g | ]}t j|d  qS )r   r   r   vidr4   r   r    r!   r     s   $ r)   r         ?)rs   rw   rR   rZ   rQ   rS   r+   r{   r   r,   zerosra   r`   
zeros_likerD   ru   r-   rJ   rK   new_ones	new_zerossize)r   r&   r   r   r   r   r   r   r   ra   r`   r4   r8   r   BCTHWr+   	cond_maskcond_indicatorcond_latentsrJ   rK   padding_shapeones_paddingzeros_paddingr    r   r!   prepare_latentsz  sb   





&z*Cosmos2_5_TransferPipeline.prepare_latents皙?c                    s\  |dks|dks|d dks|d dkrt d| d| d|	d ur/|	dkr/t d|	 d|
dk s7|
dkr?t d|
 d|d ur`t fd	d
|D s`t d j d fdd|D  |d urs|d urst d| d| d|d u r|d u rt d|d urt|tst|tst dt| |d ur|d urt d|d u r|d u rt d|d ur|dk rt d|d ur|dk rt d|d urtd|d  j d } jd }||k rt	
d|d|d |}d }t jjdd d urtdd
 t jjj jjjD }||krt d|d|d||kr,t d|d |d!|S )"Nr   r   zE`height` and `width` have to be divisible by 16 (& positive) but are z and r   z?`num_frames` has to be a positive integer when provided but is r   zM`conditional_frame_timestep` has to be a float in the [0, 1] interval but is c                 3   s    | ]}| j v V  qd S N_callback_tensor_inputsr   kr   r    r!   	<genexpr>  s    

z:Cosmos2_5_TransferPipeline.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_TransferPipeline.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`Provide only one of `num_ar_conditional_frames` or `num_ar_latent_conditional_frames`, not both.zQProvide either `num_ar_conditional_frames` or `num_ar_latent_conditional_frames`.z0`num_ar_latent_conditional_frames` must be >= 0.z)`num_ar_conditional_frames` must be >= 0.znum_frames_per_chunk=z# must be larger than min_chunk_len=z, setting to min_chunk_lenmax_sizec                 s   s    | ]	\}}|| V  qd S r   r    )r   r   patchr    r    r!   r     s
    
z3 is too large for RoPE setting (max_frames_by_rope=z(). Please reduce `num_frames_per_chunk`.znum_ar_conditional_frames=z+ must be smaller than num_frames_per_chunk=z for chunked generation.)rZ   allr   rs   rt   rw   rd   maxrQ   loggerwarningrN   rC   rU   zipr   
patch_size)r   r^   r   r   r>   "callback_on_step_end_tensor_inputsnum_ar_conditional_frames num_ar_latent_conditional_framesnum_frames_per_chunkr'   conditional_frame_timestepmin_chunk_lenmax_frames_by_roper    r   r!   check_inputs  sx   (


z'Cosmos2_5_TransferPipeline.check_inputsc                 C      | j S r   _guidance_scaler   r    r    r!   guidance_scale"     z)Cosmos2_5_TransferPipeline.guidance_scalec                 C   s
   | j dkS )Nr   r   r   r    r    r!   r   &  s   
z6Cosmos2_5_TransferPipeline.do_classifier_free_guidancec                 C   r   r   )_num_timestepsr   r    r    r!   num_timesteps*  r   z(Cosmos2_5_TransferPipeline.num_timestepsc                 C   r   r   )_current_timestepr   r    r    r!   current_timestep.  r   z+Cosmos2_5_TransferPipeline.current_timestepc                 C   r   r   )
_interruptr   r    r    r!   	interrupt2  r   z$Cosmos2_5_TransferPipeline.interruptr   $   g      @pilcontrolscontrols_conditioning_scaler'   r   num_inference_stepsr   output_typereturn_dictcallback_on_step_endr   r   r   r   c           J         s	  	j du rtd	j dt|ttfr|j}|du ryt|tr%|d n|}t|tr0|d }t|tj	t
jfrL|jdkrC|d }n	|jdkrL|d }t|tjjr`t|d |j|j  }n|jd	kritd
t|d |jd |jd   }	||||||||
|dur|tdd 	j d ntdd 	j d |
	_d	_d	_	j	j durވ	j  |durt|tr|gn|}|D ]}	j |std| dq|durt|trd}n|durt|trt|}n|jd }	j||	j||||d\}}	j j!}	j"j!}t#	j"j$ddrDtj%|	j"j$j&	j"j$j'|j(|d}|dkr;|j)|dd}||f}||f} n|}|} 	j*+|||}!|!jd |krx|!jd dkrj|!,|dddd}!ntd| d|!jd  d|!jd |durt-|t.|!}!d 	j d }" }#fddt/d |#D }$g }%	j0j|d	j1j|d	fdd}&|}'d}(g })t|$}*|	|* }+	j2|+d},t3|$D ]\}-\}.}/|-dkrtj%|d	||f|d}0	j*+|0||}0n7|%d 4 }0dkr1|0dddd df |0dddddf< d|0dddddf< n|05d |0j|d}1t.|1}1	j6|1|| 	j"j$j7d |||1jd 	jtj8|-dkrb|(n|'d\}}2}3}4|3|}3t9|4| }5|j:dd|||d}6|!dddd|.|/d f j	j j!d t.  ttr 	fd!dt/ jd D }7n
	fd"d D }7tj;|7dd|}7|7  }7	j<j=|	d# 	j<j>}8t|8	_?||2 |3 }9t3|8D ]\}:};	j@rq|;A B 	_tC	j<jD|: B Edj|d}<|3|2 d|3 |  }=|=|}=|4|5 d|4 |<  }>	jF|7|=|>||3||6dd$}?|?d }@	j"|=|>||@|3|6dd%d }A|9|Ad|3   }A	jr	jF|7|=|>| |3||6dd$}?|?d }@	j"|=|>| |@|3|6dd%d }B|9|Bd|3   }B|A	jG|A|B   }A	j<jH|A|;|dd&d }|duri }C|D ]
}DtI |D |C|D< q|	|:|;|C}E|EJd'|}|EJd(|}|EJd)|}|:|+d ks|:d 	j<jK dkr|,L  tMrtNO  q|%P|&|Q A  |)P|Q A  qW d   n	1 sw   Y  d	_|d*ksfd+dt3|%D }%tj;|%dd}F|Fdddddd f }F	j dus-J 	j  	j*jR|Fd,d-}F|Fd. St
jT}Fg }G|FD ]}H	j U|H}H|Hdu r`|GPt
V|Fd  qG|GP|H qGt
W|GSt
j8d/ d d }FtX|FYddddd	}F	j*jR|F|d-}Fn)d 	j d }Ifd0dt3|)D })tj;|)dd}F|Fddddd|Id f }F	Z  |s|FfS t[|Fd1S )2ad  
        `controls` drive the conditioning through ControlNet. Controls are assumed to be pre-processed, e.g. edge maps
        are pre-computed.

        Setting `num_frames` will restrict the total number of frames output, if not provided or assigned to None
        (default) then the number of output frames will match the input `controls`.

        Auto-regressive inference is supported and thus a sliding window of `num_frames_per_chunk` frames are used per
        denoising loop. In addition, when auto-regressive inference is performed, the previous
        `num_ar_latent_conditional_frames` or `num_ar_conditional_frames` are used to condition the following denoising
        inference loops.

        Args:
            controls (`PipelineImageInput`, `List[PipelineImageInput]`):
                Control image or video input used by the ControlNet.
            controls_conditioning_scale (`float` or `List[float]`, *optional*, defaults to `1.0`):
                The scale factor(s) for the ControlNet outputs. A single float is broadcast to all control blocks.
            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`, *optional*):
                The width in pixels of the generated image. If not provided, this will be determined based on the
                aspect ratio of the input and the provided height.
            num_frames (`int`, *optional*):
                Number of output frames. Defaults to `None` to output the same number of frames as the input
                `controls`.
            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 `3.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. 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_ar_conditional_frames (`int`, *optional*, defaults to `1`):
                Number of frames to condition on subsequent inference loops in auto-regressive inference, i.e. for the
                second chunk and onwards. Only used if `num_ar_latent_conditional_frames` is `None`.

                This is only used when auto-regressive inference is performed, i.e. when the number of frames in
                controls is > num_frames_per_chunk
            num_ar_latent_conditional_frames (`int`, *optional*):
                Number of latent frames to condition on subsequent inference loops in auto-regressive inference, i.e.
                for the second chunk and onwards. Only used if `num_ar_conditional_frames` is `None`.

                This is only used when auto-regressive inference is performed, i.e. when the number of frames in
                controls is > num_frames_per_chunk
        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.r      )r   r   rG   r   r	   z0`controls` must contain 3D frames in CHW format.r   r   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   r   r>   r?   r`   r_   img_context_dim_inr   r)   zExpected controls batch size z% to match prompt batch size, but got r   c                    s   g | ]}|t |  fqS r    )min)r   	start_idx)r   r   r    r!   r   '  s    z7Cosmos2_5_TransferPipeline.__call__.<locals>.<listcomp>rq   c                    s2   |   } j j| jj j dddd }|S )Nrq   Fr   r   )rD   decoder{   ra   )r8   r&   )r`   rJ   rK   r   r    r!   decode_latents0  s   "z;Cosmos2_5_TransferPipeline.__call__.<locals>.decode_latents)total)ra   r(   )r&   r   r   r   r   r   r   r   ra   r`   r4   r   r8   .c                    s.   g | ]}t j | d | dqS r   r   r   )chunk_control_videor4   r   r    r!   r   c  r   c                    s&   g | ]}t j|d  dqS r   r   r   r   r    r!   r   h  s    )r`   )controls_latentsr8   timestepencoder_hidden_statescondition_maskconditioning_scalepadding_maskr   )r|   r   r   block_controlnet_hidden_statesr   r   r   r   r8   r>   r?   latentc                    8   g | ]\}}|d kr|dddd ddf n|qS r   N.r    r   	chunk_idxchunk)r   r    r!   r         &np)r      g     o@c                    r   r   r    r   )r   r    r!   r     r   )frames)\r@   rZ   r\   rs   r   r
   tensor_inputsrw   r,   Tensorr   ndarrayndimPILImageintr   r   r+   r   r   rQ   r   r   r   rr   r{   rt   check_text_safetyrR   r   r   rD   ra   rC   rN   rU   r   img_context_num_tokensr   r`   repeat_interleaverT   preprocess_videor.   r   r1   ru   rJ   rK   progress_bar	enumerateclonefill_r   in_channelsfloat32	ones_liker   r-   rE   set_timesteps	timestepsr   r   cpuitemrV   sigmasr   rF   r   steplocalspoporderupdateXLA_AVAILABLExm	mark_stepry   detachpostprocess_videoastypeuint8check_video_safetyr   rz   
from_numpypermutemaybe_free_model_hooksr   )Jr   r   r   r^   r   r   r   r'   r   r   r   r   r4   r8   r>   r?   r   r   r   r   r_   r   r   r   frameprompt_listpr   	vae_dtypetransformer_dtypeimg_contextr   neg_encoder_hidden_statescontrol_videonum_latent_frames_per_chunkchunk_stride
chunk_idxsvideo_chunksr   latents_arginitial_num_cond_latent_frameslatent_chunks
num_chunkstotal_stepsr  r   r   end_idxprev_outputchunk_videocond_latentr   r   cond_timestepr   r   r  gt_velocityr   tsigma_t
in_latentsin_timestepcontrol_outputcontrol_blocks
noise_prednoise_pred_negcallback_kwargsr   callback_outputsr&   video_batchr   latent_Tr    )
r   r`   r4   rJ   rK   r   r   r   r   r   r!   __call__6  s  
t




 











2







	


$  




z#Cosmos2_5_TransferPipeline.__call__r   )Nr]   NN)NTr   NNr]   NN)r   r   r   r   r   TNNNNr   )NNNNNNr   )1r#   r$   r%   __doc__model_cpu_offload_seqr   _optional_components_exclude_from_cpu_offloadr   r   r   r   r   r   r   r   r"   r   rt   r   r  r,   r`   ra   r   boolr  r   	Generatorr   r   propertyr   r   r   r   r   no_gradr   EXAMPLE_DOC_STRINGDEFAULT_NEGATIVE_PROMPTr   rY   r   r   r   r
   rK  __classcell__r    r    r[   r!   r=      s   
/
I	

Y	

W
V





	
r=   )Nr2   )9typingr   r   r   r   r   numpyr   	PIL.Imager  r,   transformersr   r   	callbacksr
   r   image_processorr   modelsr   r   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#   r   r  r  r1   rQ  rt   r<   rU  rT  r=   r    r    r    r!   <module>   sD   

E