
    ܱit                        d dl Z d dlmZ d dlmZmZmZmZmZ d dl	Z
d dlZd dl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 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$  e            rd dl%m&c m'Z( dZ)ndZ) ej*        e+          Z,dZ-d Z.	 	 	 	 d!dee/         deee0ej1        f                  deee/                  deee2                  fdZ3e G d de                      Z4 G d de$          Z5d"dZ6d Z7d Z8de/fdZ9d  Z:dS )#    N)	dataclass)CallableDictListOptionalUnion)CLIPImageProcessorCLIPVisionModelWithProjection)PipelineImageInput)AutoencoderKLTemporalDecoder) UNetSpatioTemporalConditionModel)EulerDiscreteScheduler)
BaseOutputis_torch_xla_availableloggingreplace_example_docstring)is_compiled_modulerandn_tensor)VideoProcessor)DiffusionPipelineTFa  
    Examples:
        ```py
        >>> from diffusers import StableVideoDiffusionPipeline
        >>> from diffusers.utils import load_image, export_to_video

        >>> pipe = StableVideoDiffusionPipeline.from_pretrained(
        ...     "stabilityai/stable-video-diffusion-img2vid-xt", torch_dtype=torch.float16, variant="fp16"
        ... )
        >>> pipe.to("cuda")

        >>> image = load_image(
        ...     "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/svd-docstring-example.jpeg"
        ... )
        >>> image = image.resize((1024, 576))

        >>> frames = pipe(image, num_frames=25, decode_chunk_size=8).frames[0]
        >>> export_to_video(frames, "generated.mp4", fps=7)
        ```
c                 t    || j         z
  }|dk     rt          d| j          d| d          | dd|z  z            S )zNAppends dimensions to the end of a tensor until it has target_dims dimensions.r   z
input has z dims but target_dims is z, which is less).N)ndim
ValueError)xtarget_dimsdims_to_appends      I/data/cameron/vidgen/Ctrl-World/models/pipeline_stable_video_diffusion.py_append_dimsr   F   sR     16)Ncafcc{cccdddVg..//    num_inference_stepsdevice	timestepssigmasc                 f   ||t          d          |dt          t          j        | j                  j                                                  v }|st          d| j         d           | j        d||d| | j        }t          |          }n|dt          t          j        | j                  j                                                  v }|st          d| j         d           | j        d||d	| | j        }t          |          }n | 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   setinspect	signatureset_timesteps
parameterskeys	__class__r#   len)	schedulerr!   r"   r#   r$   kwargsaccepts_timestepsaccept_sigmass           r   retrieve_timestepsr3   O   s   > !3tuuu'3w/@AX/Y/Y/d/i/i/k/k+l+ll  	by/B b b b   	 	M)FMMfMMM'	!)nn		 C(9):Q(R(R(](b(b(d(d$e$ee 	`y/B ` ` `   	 	GvfGGGGG'	!)nn	 3MMFMfMMM'	)))r    c                   p    e Zd ZU dZeeeej        j                          ej	        e
j        f         ed<   dS )"StableVideoDiffusionPipelineOutputaB  
    Output class for Stable Video Diffusion pipeline.

    Args:
        frames (`[List[List[PIL.Image.Image]]`, `np.ndarray`, `torch.Tensor`]):
            List of denoised PIL images of length `batch_size` or numpy array or torch tensor of shape `(batch_size,
            num_frames, height, width, num_channels)`.
    framesN)__name__
__module____qualname____doc__r   r   PILImagenpndarraytorchTensor__annotations__r&   r    r   r5   r5      sH           $tCIO,-rz5<GHHHHHHr    r5   c            )           e Zd ZdZdZdgZdededede	de
f
 fd	Zd
edeeej        f         dededej        f
dZd
ej        deeej        f         dedefdZdedededej        dededefdZd9dej        dedefdZd Z	 d:dedededededej        deeej        f         d ej        deej                 fd!Zed"             Zed#             Z ed$             Z! ej"                     e#e$          d%d&dd'dd(d)d*d+d,dd-ddd.ddgd/fd
ee%j&        j&        e'e%j&        j&                 ej        f         dededee         d0ed1ee'e                  d2ed3ededededee         dee         d eeej        e'ej                 f                  deej                 d4ee         d5ee(eee)gdf                  d6e'e         d7ef&d8                        Z* xZ+S );StableVideoDiffusionPipelineae  
    Pipeline to generate video from an input image using Stable Video Diffusion.

    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:
        vae ([`AutoencoderKLTemporalDecoder`]):
            Variational Auto-Encoder (VAE) model to encode and decode images to and from latent representations.
        image_encoder ([`~transformers.CLIPVisionModelWithProjection`]):
            Frozen CLIP image-encoder
            ([laion/CLIP-ViT-H-14-laion2B-s32B-b79K](https://huggingface.co/laion/CLIP-ViT-H-14-laion2B-s32B-b79K)).
        unet ([`UNetSpatioTemporalConditionModel`]):
            A `UNetSpatioTemporalConditionModel` to denoise the encoded image latents.
        scheduler ([`EulerDiscreteScheduler`]):
            A scheduler to be used in combination with `unet` to denoise the encoded image latents.
        feature_extractor ([`~transformers.CLIPImageProcessor`]):
            A `CLIPImageProcessor` to extract features from generated images.
    zimage_encoder->unet->vaelatentsvaeimage_encoderunetr/   feature_extractorc                 *   t                                                       |                     |||||           t          | dd           r$dt	          | j        j        j                  dz
  z  nd| _        t          d| j                  | _
        d S )N)rE   rF   rG   r/   rH   rE            T)	do_resizevae_scale_factor)super__init__register_modulesgetattrr.   rE   configblock_out_channelsrN   r   video_processor)selfrE   rF   rG   r/   rH   r-   s         r   rP   z%StableVideoDiffusionPipeline.__init__   s     	'/ 	 	
 	
 	
 W^^bdikoVpVp wc$(/*L&M&MPQ&Q R Rvw-tOdeeer    imager"   num_videos_per_promptdo_classifier_free_guidancereturnc                    t          | j                                                  j        }t	          |t
          j                  sT| j                            |          }| j        	                    |          }|dz  dz
  }t          |d          }|dz   dz  }|                     |ddddd          j        }|                    ||          }|                     |          j        }|                    d	          }|j        \  }}}	|                    d	|d	          }|                    ||z  |d
          }|r*t          j        |          }
t          j        |
|g          }|S )N       @      ?)   r^   TFpt)imagesdo_normalizedo_center_croprM   
do_rescalereturn_tensorsr"   dtyperK   )nextrF   r+   rf   
isinstancer?   r@   rU   pil_to_numpynumpy_to_pt_resize_with_antialiasingrH   pixel_valuestoimage_embeds	unsqueezeshaperepeatview
zeros_likecat)rV   rW   r"   rX   rY   rf   image_embeddingsbs_embedseq_len_negative_image_embeddingss              r   _encode_imagez*StableVideoDiffusionPipeline._encode_image   s    T'224455;%.. 	((55e<<E(44U;;E CK#%E-eZ@@ES[C'E &&  ' 
 
  	 e44--e44A+55a88  05'1+2216KQOO+00<Q1QSZ\^__& 	X(-(89I(J(J%
  %y*CEU)VWWr    c                    |                     |          }| j                            |          j                                        }|                    |ddd          }|r*t          j        |          }t          j        ||g          }|S )N)r"   rK   )	rn   rE   encodelatent_distmoderr   r?   rt   ru   )rV   rW   r"   rX   rY   image_latentsnegative_image_latentss          r   _encode_vae_imagez.StableVideoDiffusionPipeline._encode_vae_image   s     ''..:??AA &,,-BAq!LL& 	O%*%5m%D%D"
 "I'=}&MNNMr    fpsmotion_bucket_idnoise_aug_strengthrf   
batch_sizec                 F   |||g}| j         j        j        t          |          z  }	| j         j        j        j        }
|
|	k    rt          d|
 d|	 d          t          j	        |g|          }|
                    ||z  d          }|rt          j        ||g          }|S )Nz7Model expects an added time embedding vector of length z, but a vector of z was created. The model has an incorrect config. Please check `unet.config.time_embedding_type` and `text_encoder_2.config.projection_dim`.rf   rK   )rG   rS   addition_time_embed_dimr.   add_embeddinglinear_1in_featuresr   r?   tensorrr   ru   )rV   r   r   r   rf   r   rX   rY   add_time_idspassed_add_embed_dimexpected_add_embed_dims              r   _get_add_time_idsz.StableVideoDiffusionPipeline._get_add_time_ids  s     -/AB#y/G#lJ[J[[!%!8!A!M!%999 VJ`  V  V  uI  V  V  V   |\N%@@@#**:8M+MqQQ& 	C 9lL%ABBLr       
num_framesdecode_chunk_sizec                    |                     dd          }d| j        j        j        z  |z  }t	          | j                  r| j        j        j        n| j        j        }dt          t          j	        |          j
                                                  v }g }t          d|j        d         |          D ][}||||z            j        d         }i }	|r||	d<    | j        j        ||||z            fi |	j        }
|                    |
           \t#          j        |d          } |j        d|g|j        dd          R                      ddddd          }|                                }|S )	Nr   rK   r   dimrg   rJ         )flattenrE   rS   scaling_factorr   	_orig_modforwardr'   r(   r)   r+   r,   rangerq   decodesampleappendr?   ru   reshapepermutefloat)rV   rD   r   r   forward_vae_fnaccepts_num_framesr6   inum_frames_indecode_kwargsframes              r   decode_latentsz+StableVideoDiffusionPipeline.decode_latents'  s   //!Q''dho44w>7I$(7S7Si+33Y]YaYi)S1B>1R1R1]1b1b1d1d-e-ee q'-*,=>> 	! 	!A#A,=(=$=>DQGMM! <.;l+#DHOGA4E0E,E$FXX-XX_EMM%    6q)))  JBabb1ABBBJJ1aQRTUWXYY r    c                 0   t          |t          j                  sSt          |t          j        j                  s4t          |t
                    st          dt          |                     |dz  dk    s	|dz  dk    rt          d| d| d          d S )Nz``image` has to be of type `torch.Tensor` or `PIL.Image.Image` or `List[PIL.Image.Image]` but is rL   r   z7`height` and `width` have to be divisible by 8 but are z and .)ri   r?   r@   r;   r<   listr   type)rV   rW   heightwidths       r   check_inputsz)StableVideoDiffusionPipeline.check_inputsD  s    5%,//	ucio66	 ud++	
 "KK" "  
 A:??eai1nnlW]lldilllmmm -nr    Nnum_channels_latentsr   r   	generatorc
                 D   |||dz  || j         z  || j         z  f}
t          |t                    r6t          |          |k    r#t	          dt          |           d| d          |	t          |
|||          }	n|	                    |          }	|	| j        j        z  }	|	S )NrJ   z/You have passed a list of generators of length z+, but requested an effective batch size of z@. Make sure the batch size matches the length of the generators.r   r"   rf   )	rN   ri   r   r.   r   r   rn   r/   init_noise_sigma)rV   r   r   r   r   r   rf   r"   r   rD   rq   s              r   prepare_latentsz,StableVideoDiffusionPipeline.prepare_latentsR  s      A%d++T**
 i&& 	3y>>Z+G+Gi#i.. i i&i i i  
 ?"5IfTYZZZGGjj((G DN;;r    c                     | j         S r   )_guidance_scalerV   s    r   guidance_scalez+StableVideoDiffusionPipeline.guidance_scalet  s    ##r    c                     t          | j        t          t          f          r| j        dk    S | j                                        dk    S )NrK   )ri   r   intr   maxr   s    r   rY   z8StableVideoDiffusionPipeline.do_classifier_free_guidance{  sC    d)C<88 	+&**"&&((1,,r    c                     | j         S r   )_num_timestepsr   s    r   num_timestepsz*StableVideoDiffusionPipeline.num_timesteps  s    ""r    i@  i      r]   g      @      g{Gz?rK   pilTr!   r$   min_guidance_scalemax_guidance_scaleoutput_typecallback_on_step_end"callback_on_step_end_tensor_inputsreturn_dictc                 $   |p| j         j        j        | j        z  }|p| j         j        j        | j        z  }||n| j         j        j        }||n|}|                     |||           t          |t          j        j                  rd}n2t          |t                    rt          |          }n|j        d         }| j        }|| _        |                     |||| j                  }|	dz
  }	| j                            |||                              |          }t'          |j        |||j                  }|||z  z   }| j        j        t,          j        k    o| j        j        j        }|r%| j                            t,          j                   |                     |||| j                  }|                    |j                  }|r%| j                            t,          j                   |                    d                              d|ddd          }|                     |	|
||j        ||| j                  }|                    |          }t=          | j        ||d|          \  }}| j         j        j         }| !                    ||z  |||||j        |||	  	        }t-          j"        |||                              d          }|                    ||j                  }|                    ||z  d          }tG          ||j$                  }|| _        t          |          || j        j%        z  z
  }t          |          | _&        | '                    |          5 }tQ          |          D ]q\  } }!| j        rt-          j)        |gd	z            n|}"| j        *                    |"|!          }"t-          j)        |"|gd	
          }"|                      |"|!||d          d         }#| j        r(|#+                    d	          \  }$}%|$| j,        |%|$z
  z  z   }#| j        -                    |#|!|          j.        }|Bi }&|D ]}'t_                      |'         |&|'<    || | |!|&          }(|(0                    d|          }| t          |          dz
  k    s| dz   |k    r*| dz   | j        j%        z  dk    r|1                                 td          rtg          j4                     s	 ddd           n# 1 swxY w Y   |dk    s[|r%| j                            t,          j                   | 5                    |||          })| j        6                    |)|          })n|})| 7                                 |s|)S tq          |)          S )a  
        The call function to the pipeline for generation.

        Args:
            image (`PIL.Image.Image` or `List[PIL.Image.Image]` or `torch.Tensor`):
                Image(s) to guide image generation. If you provide a tensor, the expected value range is between `[0,
                1]`.
            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.
            num_frames (`int`, *optional*):
                The number of video frames to generate. Defaults to `self.unet.config.num_frames` (14 for
                `stable-video-diffusion-img2vid` and to 25 for `stable-video-diffusion-img2vid-xt`).
            num_inference_steps (`int`, *optional*, defaults to 25):
                The number of denoising steps. More denoising steps usually lead to a higher quality video at the
                expense of slower inference. This parameter is modulated by `strength`.
            sigmas (`List[float]`, *optional*):
                Custom sigmas to use for the denoising process with schedulers which support a `sigmas` argument in
                their `set_timesteps` method. If not defined, the default behavior when `num_inference_steps` is passed
                will be used.
            min_guidance_scale (`float`, *optional*, defaults to 1.0):
                The minimum guidance scale. Used for the classifier free guidance with first frame.
            max_guidance_scale (`float`, *optional*, defaults to 3.0):
                The maximum guidance scale. Used for the classifier free guidance with last frame.
            fps (`int`, *optional*, defaults to 7):
                Frames per second. The rate at which the generated images shall be exported to a video after
                generation. Note that Stable Diffusion Video's UNet was micro-conditioned on fps-1 during training.
            motion_bucket_id (`int`, *optional*, defaults to 127):
                Used for conditioning the amount of motion for the generation. The higher the number the more motion
                will be in the video.
            noise_aug_strength (`float`, *optional*, defaults to 0.02):
                The amount of noise added to the init image, the higher it is the less the video will look like the
                init image. Increase it for more motion.
            decode_chunk_size (`int`, *optional*):
                The number of frames to decode at a time. Higher chunk size leads to better temporal consistency at the
                expense of more memory usage. By default, the decoder decodes all frames at once for maximal quality.
                For lower memory usage, reduce `decode_chunk_size`.
            num_videos_per_prompt (`int`, *optional*, defaults to 1):
                The number of videos 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 video
                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`.
            output_type (`str`, *optional*, defaults to `"pil"`):
                The output format of the generated image. Choose between `pil`, `np` or `pt`.
            callback_on_step_end (`Callable`, *optional*):
                A function that is called at the end of each denoising step during inference. The function is called
                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.
            return_dict (`bool`, *optional*, defaults to `True`):
                Whether or not to return a [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] instead of a
                plain tuple.

        Examples:

        Returns:
            [`~pipelines.stable_diffusion.StableVideoDiffusionPipelineOutput`] or `tuple`:
                If `return_dict` is `True`, [`~pipelines.stable_diffusion.StableVideoDiffusionPipelineOutput`] is
                returned, otherwise a `tuple` of (`List[List[PIL.Image.Image]]` or `np.ndarray` or `torch.Tensor`) is
                returned.
        NrK   r   )r   r   r   r   )r"   rX   rY   )totalrJ   r   F)encoder_hidden_statesadded_time_idsr   rD   latent)videor   )r6   )9rG   rS   sample_sizerN   r   r   ri   r;   r<   r   r.   rq   _execution_devicer   r{   rY   rU   
preprocessrn   r   rf   rE   r?   float16force_upcastfloat32r   rp   rr   r   r3   r/   in_channelsr   linspacer   r   orderr   progress_bar	enumerateru   scale_model_inputchunkr   stepprev_samplelocalspopupdateXLA_AVAILABLExm	mark_stepr   postprocess_videomaybe_free_model_hooksr5   )*rV   rW   r   r   r   r!   r$   r   r   r   r   r   r   rX   r   rD   r   r   r   r   r   r"   rv   noiseneeds_upcastingr   r   r#   r   r   num_warmup_stepsr   r   tlatent_model_input
noise_prednoise_pred_uncondnoise_pred_condcallback_kwargskcallback_outputsr6   s*                                             r   __call__z%StableVideoDiffusionPipeline.__call__  sK   @ O49+7$:OOM)58MM#-#9ZZty?O?Z
1B1N--T^ 	%/// eSY_-- 	(JJt$$ 	(UJJQJ'  2  --eV=RTXTtuu Ag $//fE/RRUUV\]]U[IfTYT_```*U22(.EM9Zdho>Z 	-HKKemK,,,.."7(,(H	 / 
 
 &(()9)?@@  	-HKKemK,,, &//2299!ZAqQQ //"!,
 
 (**622 *<DNL_agimou)v)v&	&  $y/;&&.. "

 

 (:<NPZ[[eefghh'**67=AA'..z<Q/QSTUU%nglCC- y>>,?$.BV,VV!)nn%899 &	#\!),, %# %#1AEAa%nUYy1}%=%=%=gn"%)^%E%EFXZ[%\%\" &+Y0BM/RXY%Z%Z%Z" "YY&*:#1 % '   
 3 q9C9I9I!9L9L6%!2T5HO^oLo5p!pJ .--j!WEEQ'3&(O? 9 9-3XXa[**';';D!Q'X'X$.229gFFGI***A9I/I/IqSTuX\XfXlNlpqNqNq '')))  #LNNNK%#&	# &	# &	# &	# &	# &	# &	# &	# &	# &	# &	# &	# &	# &	# &	#P h&& 1%-000((*>OPPF);;&Va;bbFFF##%%% 	M1@@@@s   ,FS<<T T )r   r   ),r7   r8   r9   r:   model_cpu_offload_seq_callback_tensor_inputsr   r
   r   r   r	   rP   r   r   strr?   r"   r   boolr@   r{   r   r   rf   r   r   r   	Generatorr   r   propertyr   rY   r   no_gradr   EXAMPLE_DOC_STRINGr;   r<   r   r   r   r   __classcell__)r-   s   @r   rC   rC      s        ( 7(kf)f 5f /	f
 *f .f f f f f f(. !.  c5<'(.   #	. 
 &*.  
.  .  .  . `| c5<'(  #	
 &*   .  "	
 {   # &*   8 el  X[    :n n n0 +/       "	 
     {  c5<'(  ?  %,'       D $ $ X$ - - X-
 # # X# U]__122 $(#%(,$'$' #$(+//0MQ*.%*KO9B )rA rASY_d39?&;U\IJrA rA 	rA
 SMrA !rA e%rA "rA "rA rA rA "rA $C=rA  (}rA E%/43H"HIJrA  %,'!rA" c]#rA$ 'xc40@$0F'GH%rA& -1I'rA( )rA rA rA 32 _rA rA rA rA rAr    rC   bicubicc                 X   | j         dd          \  }}||d         z  ||d         z  f}t          |d         dz
  dz  d          t          |d         dz
  dz  d          f}t          t          d|d         z  d                    t          t          d|d         z  d                    f}|d         d	z  dk    r|d         dz   |d         f}|d         d	z  dk    r|d         |d         dz   f}t          | ||          } t          j        j                            | |||
          }	|	S )Nr   rK   r]   r\   gMbP?g      @r   rJ   )sizer   align_corners)rq   r   r   _gaussian_blur2dr?   nn
functionalinterpolate)
inputr  interpolationr  hwfactorsr$   ksoutputs
             r   rl   rl   ~  s=   ;rssDAq47{AQK(G
 	WQZ#$e,,WQZ#$e,,F 
S6!9$a((	)	)3s7VAY3F/J/J+K+K	KB 	1	aUQY1
1	aUBqEAIUB//EX ,,UMan,ooFMr    c                 $   t          |           dk     rt          |           d | D             }dt          |           z  dgz  }t          t          |                     D ].}||dz             }|dz  }||z
  }||d|z  dz   <   ||d|z  dz   <   /|S )zCompute padding tuple.rJ   c                     g | ]}|d z
  S )rK   r&   ).0r   s     r   
<listcomp>z$_compute_padding.<locals>.<listcomp>  s    +++!A+++r    r   rK   )r.   AssertionErrorr   )kernel_sizecomputedout_paddingr   computed_tmp	pad_frontpad_rears          r   _compute_paddingr    s     ;![)))++{+++H c+&&&!,K3{##$$ * *!a%) A%	)+!*AEAI!)AEAIr    c                    | j         \  }}}}|d d d df                             | j        | j                  }|                    d|dd          }|j         dd          \  }}t          ||g          }	t          j        j        	                    | |	d          } |
                    dd||          }|                     d|                    d          |                     d          |                     d                    } t          j        j                            | ||                    d          dd	          }
|
                    ||||          }|S )
N.re   rg   r  reflect)r   rK   r   )groupspaddingstride)rq   rn   r"   rf   expandr  r?   r  r  padr   rs   r  conv2d)r  kernelbcr
  r  
tmp_kernelr   r   padding_shaper  outs               r   	_filter2dr)    s<   JAq!Q4%((EK(PPJ""2q"b11J$RSS)MFE/@@MH##E=y#IIE ##B6599JJJr:??1--uzz"~~uzz"~~NNE X ''z*//RSBTBT^_hi'jjF
++aAq
!
!CJr    window_sizec                    t          |t                    rt          j        |gg          }|j        d         }t          j        | |j        |j                  | dz  z
                      |d          }| dz  dk    r|dz   }t          j	        |
                    d           d|
                    d          z  z            }||                    dd          z  S )	Nr   re   rJ   rg   g      ?r\   T)keepdim)ri   r   r?   r   rq   aranger"   rf   r   exppowsum)r*  sigmar   r   gausss        r   	_gaussianr3    s    % (ugY''QJ	k%,ek	J	J	J[\]M]	]eefprtuuAQ!GIquuSzzkQ3%7899E599R9....r    c                 (   t          |t                    rt          j        |g| j                  }n|                    | j                  }t          |d                   t          |d                   }}|j        d         }t          ||d d df         	                    |d                    }t          ||d d df         	                    |d                    }t          | |dd d d f                   }t          ||d                   }	|	S )Nr   r   rK   .).N)ri   tupler?   r   rf   rn   r   rq   r3  rs   r)  )
r  r  r1  kykxbskernel_xkernel_yout_xr(  s
             r   r  r    s    % ,eWEK888u{++Q  #k!n"5"5B	QBU111a4[--b!4455HU111a4[--b!4455HeXc4l344E
E8I.
/
/CJr    )NNNN)r   T);r(   dataclassesr   typingr   r   r   r   r   numpyr=   	PIL.Imager;   r?   transformersr	   r
   diffusers.image_processorr   diffusers.modelsr   %models.unet_spatio_temporal_conditionr   diffusers.schedulersr   diffusers.utilsr   r   r   r   diffusers.utils.torch_utilsr   r   diffusers.video_processorr   "diffusers.pipelines.pipeline_utilsr   torch_xla.core.xla_modelcore	xla_modelr   r   
get_loggerr7   loggerr   r   r   r   r"   r   r3   r5   rC   rl   r  r)  r3  r  r&   r    r   <module>rN     s    ! ! ! ! ! ! 8 8 8 8 8 8 8 8 8 8 8 8 8 8          J J J J J J J J 8 8 8 8 8 8 : 9 9 9 9 9 R R R R R R 7 7 7 7 7 7 b b b b b b b b b b b b H H H H H H H H 4 4 4 4 4 4 @ @ @ @ @ @  )))))))))MMM		H	%	% ,0 0 0 *.15%)$(8* 8*!#8* U3,-.8* S	"	8*
 T%[!8* 8* 8* 8*v 
I 
I 
I 
I 
I 
I 
I 
IaA aA aA aA aA#4 aA aA aAL   :  .  ./3 / / / /     r    