o
    Gi                     @   s  d dl Z d dlmZ d dlmZ d dlZd dlZd dlZd dl	m
Z
mZmZmZ ddlmZmZ ddlmZ ddl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!m"Z"m#Z# e rsd dl$m%  m&Z' dZ(ndZ(e)e*Z+dZ,eG dd deZ-G dd de!e"e#Z.dej/e0ej/ B fddZ1dej/e0ej/ B ej2j2B e0ej2j2 B de3e4e4f fddZ5dej/e0ej/ B ej2j2B e0ej2j2 B de3e4e4f fddZ6dS )    N)	dataclass)Any)CLIPImageProcessorCLIPTextModelCLIPTokenizerCLIPVisionModelWithProjection   )PipelineImageInputVaeImageProcessor)AutoencoderKL)I2VGenXLUNet)DDIMScheduler)
BaseOutputis_torch_xla_availableloggingreplace_example_docstring)randn_tensor)VideoProcessor   )DeprecatedPipelineMixinDiffusionPipelineStableDiffusionMixinTFa  
    Examples:
        ```py
        >>> import torch
        >>> from diffusers import I2VGenXLPipeline
        >>> from diffusers.utils import export_to_gif, load_image

        >>> pipeline = I2VGenXLPipeline.from_pretrained(
        ...     "ali-vilab/i2vgen-xl", torch_dtype=torch.float16, variant="fp16"
        ... )
        >>> pipeline.enable_model_cpu_offload()

        >>> image_url = (
        ...     "https://huggingface.co/datasets/diffusers/docs-images/resolve/main/i2vgen_xl_images/img_0009.png"
        ... )
        >>> image = load_image(image_url).convert("RGB")

        >>> prompt = "Papers were floating in the air on a table in the library"
        >>> negative_prompt = "Distorted, discontinuous, Ugly, blurry, low resolution, motionless, static, disfigured, disconnected limbs, Ugly faces, incomplete arms"
        >>> generator = torch.manual_seed(8888)

        >>> frames = pipeline(
        ...     prompt=prompt,
        ...     image=image,
        ...     num_inference_steps=50,
        ...     negative_prompt=negative_prompt,
        ...     guidance_scale=9.0,
        ...     generator=generator,
        ... ).frames[0]
        >>> video_path = export_to_gif(frames, "i2v.gif")
        ```
c                   @   s2   e Zd ZU dZejejB eee	j
j
  B ed< dS )I2VGenXLPipelineOutputa  
     Output class for image-to-video pipeline.

    Args:
         frames (`torch.Tensor`, `np.ndarray`, or list[list[PIL.Image.Image]]):
             list of video outputs - It can be a nested list of length `batch_size,` with each sub-list containing
             denoised
     PIL image sequences of length `num_frames.` It can also be a NumPy array or Torch tensor of shape
    `(batch_size, num_frames, channels, height, width)`
    framesN)__name__
__module____qualname____doc__torchTensornpndarraylistPILImage__annotations__ r&   r&   d/home/ubuntu/.local/lib/python3.10/site-packages/diffusers/pipelines/i2vgen_xl/pipeline_i2vgen_xl.pyr   S   s   
 $r   c                ,       s  e Zd ZdZ	 dZdedededede	de
d	ef fd
dZedd Zedd Z				d>dejdB dejdB dedB fddZdd Zd?ddZdd Z			d@ddZdd Z	d?d d!Ze ee			"	#	$	$	%	&		'	(	(					)	*		(dAd+eee B d,ed-edB d.edB d/edB d0ed1ed2e d3eee B dB d4e d5edB d6edB d7ej!eej! B dB d8ejdB dejdB dejdB d9edB d:e"d;e#ee$f dB dedB f(d<d=Z%  Z&S )BI2VGenXLPipelinez0.33.1z&text_encoder->image_encoder->unet->vaevaetext_encoder	tokenizerimage_encoderfeature_extractorunet	schedulerc              	      s^   t    | j|||||||d t| dd r"dt| jjjd  nd| _t	| jdd| _
d S )N)r)   r*   r+   r,   r-   r.   r/   r)   r         F)vae_scale_factor	do_resize)super__init__register_modulesgetattrlenr)   configblock_out_channelsr2   r   video_processor)selfr)   r*   r+   r,   r-   r.   r/   	__class__r&   r'   r5   ~   s   

(	zI2VGenXLPipeline.__init__c                 C   s   | j S N_guidance_scaler<   r&   r&   r'   guidance_scale   s   zI2VGenXLPipeline.guidance_scalec                 C   s
   | j dkS )Nr0   r@   rB   r&   r&   r'   do_classifier_free_guidance   s   
z,I2VGenXLPipeline.do_classifier_free_guidanceNprompt_embedsnegative_prompt_embeds	clip_skipc              
   C   sd  |durt |trd}n|durt |trt|}n|jd }|du r| j|d| jjddd}	|	j}
| j|ddd	j}|jd
 |
jd
 krjt	|
|sj| j
|dd| jjd d
f }td| jj d|  t| jjdr}| jjjr}|	j|}nd}|du r| j|
||d}|d }n| j|
||dd}|d
 |d   }| jj|}| jdur| jj}n| jdur| jj}n|j}|j||d}|j\}}}|d|d}||| |d
}| jr|du r|du rdg| }nC|durt|t|urtdt| dt| dt |tr|g}n|t|kr5td| dt| d| d| d	|}|jd }| j|d|ddd}t| jjdr[| jjjr[|j|}nd}|du rr| j|j||d}|d }n| j|j||dd}|d
 |d   }| jj|}| jr|jd }|j||d}|d|d}||| |d
}||fS )ab  
        Encodes the prompt into text encoder hidden states.

        Args:
            prompt (`str` or `list[str]`, *optional*):
                prompt to be encoded
            device: (`torch.device`):
                torch device
            num_videos_per_prompt (`int`):
                number of images that should be generated per prompt
            do_classifier_free_guidance (`bool`):
                whether to use classifier free guidance or not
            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`).
            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.
            clip_skip (`int`, *optional*):
                Number of layers to be skipped from CLIP while computing the prompt embeddings. A value of 1 means that
                the output of the pre-final layer will be used for computing the prompt embeddings.
        Nr0   r   
max_lengthTpt)paddingrH   
truncationreturn_tensorslongest)rJ   rL   z\The following part of your input was truncated because CLIP can only handle sequences up to z	 tokens: use_attention_mask)attention_mask)rP   output_hidden_states)dtypedevice 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`.)
isinstancestrr"   r8   shaper+   model_max_length	input_idsr   equalbatch_decodeloggerwarninghasattrr*   r9   rO   rP   to
text_modelfinal_layer_normrR   r.   repeatviewrD   type	TypeError
ValueError)r<   promptrS   num_videos_per_promptnegative_promptrE   rF   rG   
batch_sizetext_inputstext_input_idsuntruncated_idsremoved_textrP   prompt_embeds_dtypebs_embedseq_len_uncond_tokensrH   uncond_inputr&   r&   r'   encode_prompt   s   %











zI2VGenXLPipeline.encode_promptc           
      C   s   t | j j}t|tjs&| j|}| j	|}| j
|ddddddj}|j||d}| |j}|d}|j\}}}|d|d}||| |d}| jr]t|}	t|	|g}|S )NTFrI   )imagesdo_normalizedo_center_cropr3   
do_rescalerL   rS   rR   r0   rN   )nextr,   
parametersrR   rV   r   r   r;   pil_to_numpynumpy_to_ptr-   pixel_valuesr`   image_embeds	unsqueezerX   rc   rd   rD   
zeros_likecat)
r<   imagerS   ri   rR   image_embeddingsrq   rr   rs   negative_image_embeddingsr&   r&   r'   _encode_imageK  s0   	

zI2VGenXLPipeline._encode_imagec                 C   s   d| j jj | }|j\}}}}}|ddddd|| |||}|d urNg }td|jd |D ]}	| j ||	|	|  j}
|	|
 q1t
j|dd}n| j |j}||df|jdd   }|d d d f |ddddd}| }|S )Nr0   r   r   r      dimrN   )r)   r9   scaling_factorrX   permutereshaperangedecodesampleappendr   r   float)r<   latentsdecode_chunk_sizerk   channels
num_framesheightwidthr   iframer   decode_shapevideor&   r&   r'   decode_latentsk  s   "$zI2VGenXLPipeline.decode_latentsc                 C   sX   dt t| jjj v }i }|r||d< dt t| jjj v }|r*||d< |S )Neta	generator)setinspect	signaturer/   stepr}   keys)r<   r   r   accepts_etaextra_step_kwargsaccepts_generatorr&   r&   r'   prepare_extra_step_kwargs  s   z*I2VGenXLPipeline.prepare_extra_step_kwargsc                 C   s8  |d dks|d dkrt d| d| d|d ur*|d ur*t d| d| d|d u r6|d u r6t d	|d urMt|tsMt|tsMt d
t| |d ur`|d ur`t d| d| d|d ur{|d ur{|j|jkr{t d|j d|j dt|tjst|tj	j	st|tst dt| d S d S d S )Nr1   r   z7`height` and `width` have to be divisible by 8 but are z and rU   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'Cannot forward both `negative_prompt`: z and `negative_prompt_embeds`: zu`prompt_embeds` and `negative_prompt_embeds` must have the same shape when passed directly, but got: `prompt_embeds` z != `negative_prompt_embeds` z``image` has to be of type `torch.Tensor` or `PIL.Image.Image` or `list[PIL.Image.Image]` but is )
rg   rV   rW   r"   re   rX   r   r   r#   r$   )r<   rh   r   r   r   rj   rE   rF   r&   r&   r'   check_inputs  sN   

zI2VGenXLPipeline.check_inputsc           	   
   C   s   |j |d}| j|j }|| jjj }|d}g }t|d D ]}|d |d  }|	t
|d d d d d df |  q#|rUt
j|dd}t
j||gdd}||dddd}| jrit
|gd }|S )NrS   r   r0   r   )r`   r)   encodelatent_distr   r9   r   r   r   r   r   	ones_liker   rc   rD   )	r<   r   rS   r   ri   image_latentsframe_position_mask	frame_idxscaler&   r&   r'   prepare_image_latents  s   
,z&I2VGenXLPipeline.prepare_image_latentsc
                 C   s~   ||||| j  || j  f}
t|tr%t||kr%tdt| d| d|	d u r2t|
|||d}	n|	|}	|	| jj }	|	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   rS   rR   )	r2   rV   r"   r8   rg   r   r`   r/   init_noise_sigma)r<   rk   num_channels_latentsr   r   r   rR   rS   r   r   rX   r&   r&   r'   prepare_latents  s"   
z I2VGenXLPipeline.prepare_latents        2         "@        r0   pilTrh   r   r   r   
target_fpsr   num_inference_stepsrC   rj   r   ri   r   r   r   output_typereturn_dictcross_attention_kwargsc           +      C   s  |p	| j jj| j }|p| j jj| j }| |||||	|| |dur+t|tr+d}n|dur9t|tr9t|}n|j	d }| j
}|| _| j||||	|||d\}}| jr\t||g}t|||f}t|| jjd | jjd f}| |||}t|||f}| j|j||jd}| j||||d}| jrt||g|}n	t|g|}||| d }| jj||d	 | jj}| j jj }| !|| |||||j|||	}| "||
}t||| jj#  }| j$|d
} t%|D ]\}!}"| jrt|gd n|}#| j&|#|"}#| j |#|"|||||ddd }$| jr-|$'d\}%}&|%||&|%   }$|j	\}}'}(}}|(ddddd)||( |'||}|$(ddddd)||( |'||}$| jj*|$|"|fi |j+}|dddf )||(|'||(ddddd}|!t|d ks|!d |kr|!d | jj# dkr| ,  t-rt./  qW d   n	1 sw   Y  |dkr|})n| j0||d}*| jj1|*|d})| 2  |s|)fS t3|)dS )uz  
        The call function to the pipeline for image-to-video generation with [`I2VGenXLPipeline`].

        Args:
            prompt (`str` or `list[str]`, *optional*):
                The prompt or prompts to guide image generation. If not defined, you need to pass `prompt_embeds`.
            image (`PIL.Image.Image` or `list[PIL.Image.Image]` or `torch.Tensor`):
                Image or images to guide image generation. If you provide a tensor, it needs to be compatible with
                [`CLIPImageProcessor`](https://huggingface.co/lambdalabs/sd-image-variations-diffusers/blob/main/feature_extractor/preprocessor_config.json).
            height (`int`, *optional*, defaults to `self.unet.config.sample_size * self.vae_scale_factor`):
                The height in pixels of the generated image.
            width (`int`, *optional*, defaults to `self.unet.config.sample_size * self.vae_scale_factor`):
                The width in pixels of the generated image.
            target_fps (`int`, *optional*):
                Frames per second. The rate at which the generated images shall be exported to a video after
                generation. This is also used as a "micro-condition" while generation.
            num_frames (`int`, *optional*):
                The number of video frames to generate.
            num_inference_steps (`int`, *optional*):
                The number of denoising steps.
            guidance_scale (`float`, *optional*, defaults to 7.5):
                A higher guidance scale value encourages the model to generate images closely linked to the text
                `prompt` at the expense of lower image quality. Guidance scale is enabled when `guidance_scale > 1`.
            negative_prompt (`str` or `list[str]`, *optional*):
                The prompt or prompts to guide what to not include in image generation. If not defined, you need to
                pass `negative_prompt_embeds` instead. Ignored when not using guidance (`guidance_scale < 1`).
            eta (`float`, *optional*):
                Corresponds to parameter eta (η) from the [DDIM](https://huggingface.co/papers/2010.02502) paper. Only
                applies to the [`~schedulers.DDIMScheduler`], and is ignored in other schedulers.
            num_videos_per_prompt (`int`, *optional*):
                The number of images to generate per prompt.
            decode_chunk_size (`int`, *optional*):
                The number of frames to decode at a time. The higher the chunk size, the higher the temporal
                consistency between frames, but also the higher the memory consumption. By default, the decoder will
                decode all frames at once for maximal quality. Reduce `decode_chunk_size` to reduce memory usage.
            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 (prompt weighting). If not
                provided, text embeddings are generated from the `prompt` input argument.
            negative_prompt_embeds (`torch.Tensor`, *optional*):
                Pre-generated negative text embeddings. Can be used to easily tweak text inputs (prompt weighting). If
                not provided, `negative_prompt_embeds` are generated from the `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 [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] instead of a
                plain tuple.
            cross_attention_kwargs (`dict`, *optional*):
                A kwargs dictionary that if specified is passed along to the [`AttentionProcessor`] as defined in
                [`self.processor`](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
            clip_skip (`int`, *optional*):
                Number of layers to be skipped from CLIP while computing the prompt embeddings. A value of 1 means that
                the output of the pre-final layer will be used for computing the prompt embeddings.

        Examples:

        Returns:
            [`pipelines.i2vgen_xl.pipeline_i2vgen_xl.I2VGenXLPipelineOutput`] or `tuple`:
                If `return_dict` is `True`, [`pipelines.i2vgen_xl.pipeline_i2vgen_xl.I2VGenXLPipelineOutput`] is
                returned, otherwise a `tuple` is returned where the first element is a list with the generated frames.
        Nr0   r   )rE   rF   rG   r   r   r{   )rS   r   ri   r   )totalr   F)encoder_hidden_statesfpsr   r   r   r   r   r   latent)r   )r   r   )r   )4r.   r9   sample_sizer2   r   rV   rW   r"   r8   rX   _execution_devicerA   rv   rD   r   r   _center_crop_wide_resize_bilinearr-   	crop_sizer   r;   
preprocessr`   rR   r   tensorrc   ravelr/   set_timesteps	timestepsin_channelsr   r   orderprogress_bar	enumeratescale_model_inputchunkr   r   r   prev_sampleupdateXLA_AVAILABLExm	mark_stepr   postprocess_videomaybe_free_model_hooksr   )+r<   rh   r   r   r   r   r   r   rC   rj   r   ri   r   r   r   rE   rF   r   r   r   rG   rk   rS   cropped_imager   resized_imager   
fps_tensorr   r   r   num_warmup_stepsr   r   tlatent_model_input
noise_prednoise_pred_uncondnoise_pred_textchannelr   r   video_tensorr&   r&   r'   __call__  s   ]



	"",6
)
zI2VGenXLPipeline.__call__)NNNNr?   )NNN)NNr   r   r   r   r   r   Nr   r0   r0   NNNNr   TNr0   )'r   r   r   _last_supported_versionmodel_cpu_offload_seqr   r   r   r   r   r   r   r5   propertyrC   rD   r   r   intrv   r   r   r   r   r   r   no_gradr   EXAMPLE_DOC_STRINGrW   r"   r	   r   	Generatorbooldictr   r   __classcell__r&   r&   r=   r'   r(   c   s    


 *
 
1"

	
r(   r   c                 C   sb   t | trt | d tjrt| d} t | tjr/| jdkr#| d} t| }t	|}|} | S )Nr   r   )
rV   r"   r   r   r   ndimr   r
   pt_to_numpynumpy_to_pil)r   image_numpy	image_pilr&   r&   r'   _convert_pt_to_pil  s   



r   
resolutionc                    s<   t | } t| tr fdd| D } | S |  tjj} | S )Nc                    s   g | ]
}|  tjjqS r&   )resizer#   r$   BILINEAR.0ur   r&   r'   
<listcomp>  s    z$_resize_bilinear.<locals>.<listcomp>)r   rV   r"   r   r#   r$   r   r   r   r&   r   r'   r     s   
r   c                    s2  t | } t| trLt| d jd  d  | d jd  d  fdd| D } | d j d  d | d j d  d  fdd| D } | S t| jd  d  | jd  d  | jt| j t| j ft	j
jd} | j d  d | j d  d |  d   d  f} | S )Nr   r0   c                    s6   g | ]}|j t|j  t|j  ftjjd qS )resample)r   roundr   r   r#   r$   BOXr   )r   r&   r'   r    s   6 z%_center_crop_wide.<locals>.<listcomp>r   c              
      s.   g | ]}|  d    d  fqS )r   r0   )cropr   )r   x1y1r&   r'   r    s   . r  )r   rV   r"   minsizer   r   r   r  r#   r$   r  r  r  r&   )r   r   r  r	  r'   r     s   
.&*"r   )7r   dataclassesr   typingr   numpyr    r#   r   transformersr   r   r   r   image_processorr	   r
   modelsr   models.unets.unet_i2vgen_xlr   
schedulersr   utilsr   r   r   r   utils.torch_utilsr   r;   r   pipeline_utilsr   r   r   torch_xla.core.xla_modelcore	xla_modelr   r   
get_loggerr   r]   r   r   r(   r   r"   r   r$   tupler   r   r   r&   r&   r&   r'   <module>   sX   
"
     "

"
