
    bigS                         d dl Z d dlmZ d dlmZmZmZm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mZ e G d	 d
e             Z	 	 ddZd Z G d dee      Zy)    N)	dataclass)ListOptionalTupleUnion   )ConfigMixinregister_to_config)
BaseOutput   )KarrasDiffusionSchedulersSchedulerMixinc                   X    e Zd ZU dZej
                  ed<   dZeej
                     ed<   y)DDIMSchedulerOutputaq  
    Output class for the scheduler's `step` function output.

    Args:
        prev_sample (`torch.Tensor` of shape `(batch_size, num_channels, height, width)` for images):
            Computed sample `(x_{t-1})` of previous timestep. `prev_sample` should be used as next model input in the
            denoising loop.
        pred_original_sample (`torch.Tensor` of shape `(batch_size, num_channels, height, width)` for images):
            The predicted denoised sample `(x_{0})` based on the model output from the current timestep.
            `pred_original_sample` can be used to preview progress or for guidance.
    prev_sampleNpred_original_sample)	__name__
__module____qualname____doc__torchTensor__annotations__r   r        i/home/cdr/jupyterlab/.venv/lib/python3.12/site-packages/diffusers/schedulers/scheduling_ddim_cogvideox.pyr   r      s'    
 37(5<<07r   r   c           
      $   |dk(  rd }n|dk(  rd }nt        d|       g }t        |       D ]<  }|| z  }|dz   | z  }|j                  t        d ||       ||      z  z
  |             > t	        j
                  |t        j                        S )a  
    Create a beta schedule that discretizes the given alpha_t_bar function, which defines the cumulative product of
    (1-beta) over time from t = [0,1].

    Contains a function alpha_bar that takes an argument t and transforms it to the cumulative product of (1-beta) up
    to that part of the diffusion process.


    Args:
        num_diffusion_timesteps (`int`): the number of betas to produce.
        max_beta (`float`): the maximum beta to use; use values lower than 1 to
                     prevent singularities.
        alpha_transform_type (`str`, *optional*, default to `cosine`): the type of noise schedule for alpha_bar.
                     Choose from `cosine` or `exp`

    Returns:
        betas (`np.ndarray`): the betas used by the scheduler to step the model outputs
    cosinec                 f    t        j                  | dz   dz  t         j                  z  dz        dz  S )NgMb?gT㥛 ?r   )mathcospits    r   alpha_bar_fnz)betas_for_alpha_bar.<locals>.alpha_bar_fnL   s-    88QY%/$''9A=>!CCr   expc                 2    t        j                  | dz        S )Ng      ()r    r&   r#   s    r   r%   z)betas_for_alpha_bar.<locals>.alpha_bar_fnQ   s    88AI&&r   z"Unsupported alpha_transform_type: r   dtype)
ValueErrorrangeappendminr   tensorfloat32)num_diffusion_timestepsmax_betaalpha_transform_typer%   betasit1t2s           r   betas_for_alpha_barr7   3   s    . x'	D 
	&	' =>R=STUUE*+ M((!e..S\"-R0@@@(KLM <<U]]33r   c                     | j                         }|d   j                         }|d   j                         }||z  }||||z
  z  z  }|dz  }|S )a.  
    Rescales betas to have zero terminal SNR Based on https://huggingface.co/papers/2305.08891 (Algorithm 1)


    Args:
        betas (`torch.Tensor`):
            the betas that the scheduler is being initialized with.

    Returns:
        `torch.Tensor`: rescaled betas with zero terminal SNR
    r   r   )sqrtclone)alphas_cumprodalphas_bar_sqrtalphas_bar_sqrt_0alphas_bar_sqrt_T
alphas_bars        r   rescale_zero_terminal_snrrA   _   st     %))+O (*002'+113 ((O (,=@Q,QRRO !!#Jr   c                      e Zd ZdZeD  cg c]  }|j
                   c}} ZdZe	 	 	 	 	 	 	 	 	 	 	 	 	 	 d'de	de
de
dedeeej                  ee
   f      d	ed
ede	dede
de
dedede
fd       Zd Zd(dej*                  dee	   dej*                  fdZd(de	deeej.                  f   fdZ	 	 	 	 	 d)dej*                  de	dej*                  de
dedeej*                     dedeeef   fd Zd!ej*                  d"ej*                  d#ej8                  dej*                  fd$Zdej*                  d"ej*                  d#ej8                  dej*                  fd%Zd& Zyc c}} w )*CogVideoXDDIMSchedulera@  
    `DDIMScheduler` extends the denoising procedure introduced in denoising diffusion probabilistic models (DDPMs) with
    non-Markovian guidance.

    This model inherits from [`SchedulerMixin`] and [`ConfigMixin`]. Check the superclass documentation for the generic
    methods the library implements for all schedulers such as loading and saving.

    Args:
        num_train_timesteps (`int`, defaults to 1000):
            The number of diffusion steps to train the model.
        beta_start (`float`, defaults to 0.0001):
            The starting `beta` value of inference.
        beta_end (`float`, defaults to 0.02):
            The final `beta` value.
        beta_schedule (`str`, defaults to `"linear"`):
            The beta schedule, a mapping from a beta range to a sequence of betas for stepping the model. Choose from
            `linear`, `scaled_linear`, or `squaredcos_cap_v2`.
        trained_betas (`np.ndarray`, *optional*):
            Pass an array of betas directly to the constructor to bypass `beta_start` and `beta_end`.
        clip_sample (`bool`, defaults to `True`):
            Clip the predicted sample for numerical stability.
        clip_sample_range (`float`, defaults to 1.0):
            The maximum magnitude for sample clipping. Valid only when `clip_sample=True`.
        set_alpha_to_one (`bool`, defaults to `True`):
            Each diffusion step uses the alphas product value at that step and at the previous one. For the final step
            there is no previous alpha. When this option is `True` the previous alpha product is fixed to `1`,
            otherwise it uses the alpha value at step 0.
        steps_offset (`int`, defaults to 0):
            An offset added to the inference steps, as required by some model families.
        prediction_type (`str`, defaults to `epsilon`, *optional*):
            Prediction type of the scheduler function; can be `epsilon` (predicts the noise of the diffusion process),
            `sample` (directly predicts the noisy sample`) or `v_prediction` (see section 2.4 of [Imagen
            Video](https://imagen.research.google/video/paper.pdf) paper).
        thresholding (`bool`, defaults to `False`):
            Whether to use the "dynamic thresholding" method. This is unsuitable for latent-space diffusion models such
            as Stable Diffusion.
        dynamic_thresholding_ratio (`float`, defaults to 0.995):
            The ratio for the dynamic thresholding method. Valid only when `thresholding=True`.
        sample_max_value (`float`, defaults to 1.0):
            The threshold value for dynamic thresholding. Valid only when `thresholding=True`.
        timestep_spacing (`str`, defaults to `"leading"`):
            The way the timesteps should be scaled. Refer to Table 2 of the [Common Diffusion Noise Schedules and
            Sample Steps are Flawed](https://huggingface.co/papers/2305.08891) for more information.
        rescale_betas_zero_snr (`bool`, defaults to `False`):
            Whether to rescale the betas to have zero terminal SNR. This enables the model to generate very bright and
            dark samples instead of limiting it to samples with medium brightness. Loosely related to
            [`--offset_noise`](https://github.com/huggingface/diffusers/blob/74fd735eb073eb1d774b1ab4154a0876eb82f055/examples/dreambooth/train_dreambooth.py#L506).
    r   Nnum_train_timesteps
beta_startbeta_endbeta_scheduletrained_betasclip_sampleset_alpha_to_onesteps_offsetprediction_typeclip_sample_rangesample_max_valuetimestep_spacingrescale_betas_zero_snrsnr_shift_scalec                    |+t        j                  |t         j                        | _        n|dk(  r-t        j                  |||t         j                        | _        nk|dk(  r6t        j                  |dz  |dz  |t         j
                        dz  | _        n0|dk(  rt        |      | _        nt        | d| j                         d| j                  z
  | _	        t        j                  | j                  d	
      | _        | j                  |d|z
  | j                  z  z   z  | _        |rt        | j                        | _        |rt        j                  d      n| j                  d	   | _        d| _        d | _        t        j                   t#        j$                  d	|      d d d   j'                         j)                  t"        j*                              | _        y )Nr(   linearscaled_linear      ?r   squaredcos_cap_v2z is not implemented for       ?r   )dimr   r9   )r   r.   r/   r3   linspacefloat64r7   NotImplementedError	__class__alphascumprodr<   rA   final_alpha_cumprodinit_noise_sigmanum_inference_steps
from_numpynparangecopyastypeint64	timesteps)selfrD   rE   rF   rG   rH   rI   rJ   rK   rL   rM   rN   rO   rP   rQ   s                  r   __init__zCogVideoXDDIMScheduler.__init__   s   $ $m5==IDJh&
H>QY^YfYfgDJo-
C3H[chcpcpquvvDJ11,-@ADJ%7OPTP^P^O_&`aaDJJ&#mmDKKQ? #11_OH[_c_r_rGr5rs "";D<O<O"PD 9I5<<#4dNaNabcNd  !$ $( ))"))A7J*KDbD*Q*V*V*X*_*_`b`h`h*ijr   c                     | j                   |   }|dk\  r| j                   |   n| j                  }d|z
  }d|z
  }||z  d||z  z
  z  }|S )Nr   r   )r<   r_   )ri   timestepprev_timestepalpha_prod_talpha_prod_t_prevbeta_prod_tbeta_prod_t_prevvariances           r   _get_variancez$CogVideoXDDIMScheduler._get_variance   si    **84BOSTBTD//>Z^ZrZr,&00${2q<J[;[7[\r   samplerl   returnc                     |S )a  
        Ensures interchangeability with schedulers that need to scale the denoising model input depending on the
        current timestep.

        Args:
            sample (`torch.Tensor`):
                The input sample.
            timestep (`int`, *optional*):
                The current timestep in the diffusion chain.

        Returns:
            `torch.Tensor`:
                A scaled input sample.
        r   )ri   rt   rl   s      r   scale_model_inputz(CogVideoXDDIMScheduler.scale_model_input   s	     r   ra   devicec           	         || j                   j                  kD  r=t        d| d| j                   j                   d| j                   j                   d      || _        | j                   j                  dk(  rot        j                  d| j                   j                  dz
  |      j                         ddd	   j                         j                  t
        j                        }nn| j                   j                  d
k(  r| j                   j                  | j                  z  }t        j                  d|      |z  j                         ddd	   j                         j                  t
        j                        }|| j                   j                  z  }n| j                   j                  dk(  r| j                   j                  | j                  z  }t        j                  t        j                  | j                   j                  d|             j                  t
        j                        }|dz  }n"t        | j                   j                   d      t        j                  |      j                  |      | _        y)a  
        Sets the discrete timesteps used for the diffusion chain (to be run before inference).

        Args:
            num_inference_steps (`int`):
                The number of diffusion steps used when generating samples with a pre-trained model.
        z`num_inference_steps`: z6 cannot be larger than `self.config.train_timesteps`: zG as the unet model trained with this scheduler can only handle maximal z timesteps.rY   r   r   Nr9   leadingtrailingzM is not supported. Please make sure to choose one of 'leading' or 'trailing'.)configrD   r*   ra   rO   rc   rY   roundre   rf   rg   rd   rK   r   rb   torh   )ri   ra   rx   rh   
step_ratios        r   set_timestepsz$CogVideoXDDIMScheduler.set_timesteps  s    !@!@@)*=)> ?KK334 5 KK;;<KI  $7  ;;'':5At{{>>BDWX2!	  [[))Y688D<T<TTJ 1&9:ZGNNPQUSUQUV[[]ddegememnI111I[[))Z7884;S;SSJ 4;;+J+JAPZ{![\ccdfdldlmINI;;//00}~  )))477?r   model_outputetause_clipped_model_outputvariance_noisereturn_dictc	                    | j                   t        d      || j                  j                  | j                   z  z
  }	| j                  |   }
|	dk\  r| j                  |	   n| j
                  }d|
z
  }| j                  j                  dk(  r||dz  |z  z
  |
dz  z  }nj| j                  j                  dk(  r|}nN| j                  j                  dk(  r|
dz  |z  |dz  |z  z
  }n#t        d| j                  j                   d	      d|z
  d|
z
  z  dz  }|dz  |
dz  |z  z
  }||z  ||z  z   }|s||fS t        ||
      S )a  
        Predict the sample from the previous timestep by reversing the SDE. This function propagates the diffusion
        process from the learned model outputs (most often the predicted noise).

        Args:
            model_output (`torch.Tensor`):
                The direct output from learned diffusion model.
            timestep (`float`):
                The current discrete timestep in the diffusion chain.
            sample (`torch.Tensor`):
                A current instance of a sample created by the diffusion process.
            eta (`float`):
                The weight of noise for added noise in diffusion step.
            use_clipped_model_output (`bool`, defaults to `False`):
                If `True`, computes "corrected" `model_output` from the clipped predicted original sample. Necessary
                because predicted original sample is clipped to [-1, 1] when `self.config.clip_sample` is `True`. If no
                clipping has happened, "corrected" `model_output` would coincide with the one provided as input and
                `use_clipped_model_output` has no effect.
            generator (`torch.Generator`, *optional*):
                A random number generator.
            variance_noise (`torch.Tensor`):
                Alternative to generating noise with `generator` by directly providing the noise for the variance
                itself. Useful for methods such as [`CycleDiffusion`].
            return_dict (`bool`, *optional*, defaults to `True`):
                Whether or not to return a [`~schedulers.scheduling_ddim.DDIMSchedulerOutput`] or `tuple`.

        Returns:
            [`~schedulers.scheduling_ddim.DDIMSchedulerOutput`] or `tuple`:
                If return_dict is `True`, [`~schedulers.scheduling_ddim.DDIMSchedulerOutput`] is returned, otherwise a
                tuple is returned where the first element is the sample tensor.

        zaNumber of inference steps is 'None', you need to run 'set_timesteps' after creating the schedulerr   r   epsilonrU   rt   v_predictionzprediction_type given as z6 must be one of `epsilon`, `sample`, or `v_prediction`)r   r   )ra   r*   r|   rD   r<   r_   rL   r   )ri   r   rl   rt   r   r   	generatorr   r   rm   rn   ro   rp   r   a_tb_tr   s                    r   stepzCogVideoXDDIMScheduler.step1  s   V ##+s   !4;;#B#BdF^F^#^^ **84BOSTBTD//>Z^ZrZr,&
 ;;&&)3$*[S-AL-P$PT`ehTi#i [[((H4#/ [[((N:$0#$5#?;PSCSWcBc#c  +DKK,G,G+H I" " 
 %%!l*:;C$|S'83'>>FlS+?%??$ 
 #{Qeffr   original_samplesnoiserh   c                    | j                   j                  |j                        | _         | j                   j                  |j                        }|j                  |j                        }||   dz  }|j	                         }t        |j                        t        |j                        k  r=|j                  d      }t        |j                        t        |j                        k  r=d||   z
  dz  }|j	                         }t        |j                        t        |j                        k  r=|j                  d      }t        |j                        t        |j                        k  r=||z  ||z  z   }|S N)rx   r(   rU   r9   r   r<   r~   rx   r)   flattenlenshape	unsqueeze)ri   r   r   rh   r<   sqrt_alpha_prodsqrt_one_minus_alpha_prodnoisy_sampless           r   	add_noisez CogVideoXDDIMScheduler.add_noise  sa    #1144<L<S<S4T,,//6F6L6L/MLL!1!8!89	(3s:)113/''(3/?/E/E+FF-77;O /''(3/?/E/E+FF &'	)B%Bs$J!$=$E$E$G!+112S9I9O9O5PP(A(K(KB(O% +112S9I9O9O5PP (*::=VY^=^^r   c                    | j                   j                  |j                        | _         | j                   j                  |j                        }|j                  |j                        }||   dz  }|j	                         }t        |j                        t        |j                        k  r=|j                  d      }t        |j                        t        |j                        k  r=d||   z
  dz  }|j	                         }t        |j                        t        |j                        k  r=|j                  d      }t        |j                        t        |j                        k  r=||z  ||z  z
  }|S r   r   )ri   rt   r   rh   r<   r   r   velocitys           r   get_velocityz#CogVideoXDDIMScheduler.get_velocity  sG   "1144FMM4J,,//fll/CLL/	(3s:)113/''(3v||+<<-77;O /''(3v||+<< &'	)B%Bs$J!$=$E$E$G!+112S5FF(A(K(KB(O% +112S5FF #U*-F-OOr   c                 .    | j                   j                  S N)r|   rD   )ri   s    r   __len__zCogVideoXDDIMScheduler.__len__  s    {{...r   )i  g_QK?g~jt?rT   NTTr   r   rW   rW   rz   Fg      @r   )g        FNNT) r   r   r   r   r   name_compatiblesorderr
   intfloatstrr   r   rc   ndarrayr   boolrj   rs   r   r   rw   rx   r   r   r   r   	IntTensorr   r   r   ).0es   00r   rC   rC   ~   sv   /b %>>qAFF>LE $(# ,BF !%(#&"% )',!$3k 3k 3k 	3k
 3k  bjj$u+&= >?3k 3k 3k 3k 3k !3k  3k 3k !%3k 3k 3kj  Y^YeYe "+@ +@eCDU>V +@d ).15 agllag ag 	ag
 ag #'ag !.ag ag 
"E)	*agH,, || ??	
 
65<<  QVQ`Q` ejeqeq &/g ?s   ErC   )g+?r   )r    dataclassesr   typingr   r   r   r   numpyrc   r   configuration_utilsr	   r
   utilsr   scheduling_utilsr   r   r   r7   rA   rC   r   r   r   <module>r      s`   &  ! / /   A  G 8* 8 8( !)4X>F/^[ F/r   