
    
3j              	           S SK r S SKJr  S SKrS SKrSSKJrJr  SSK	J
r
Jr  SSKJrJrJr  \" 5       (       a  S SKr  SS\S	\S
\S   S\R(                  4S jjr " S S\\5      rg)    N)Literal   )ConfigMixinregister_to_config)	deprecateis_scipy_available   )KarrasDiffusionSchedulersSchedulerMixinSchedulerOutputnum_diffusion_timestepsmax_betaalpha_transform_type)cosineexplaplacereturnc           
      :   US:X  a  S nO"US:X  a  S nOUS:X  a  S nO[        SU 35      e/ n[        U 5       H<  nXP-  nUS-   U -  nUR                  [        SU" U5      U" U5      -  -
  U5      5        M>     [        R
                  " U[        R                  S	9$ )
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`, defaults to `0.999`):
        The maximum beta to use; use values lower than 1 to avoid numerical instability.
    alpha_transform_type (`str`, defaults to `"cosine"`):
        The type of noise schedule for `alpha_bar`. Choose from `cosine`, `exp`, or `laplace`.

Returns:
    `torch.Tensor`:
        The betas used by the scheduler to step the model outputs.
r   c                 h    [         R                  " U S-   S-  [         R                  -  S-  5      S-  $ )NgMb?gT㥛 ?r   )mathcospits    h/home/wildlama/miniconda3/lib/python3.13/site-packages/diffusers/schedulers/scheduling_deis_multistep.pyalpha_bar_fn)betas_for_alpha_bar.<locals>.alpha_bar_fn<   s-    88QY%/$''9A=>!CC    r   c           	         S[         R                  " SSU -
  5      -  [         R                  " SS[         R                  " SU -
  5      -  -
  S-   5      -  n[         R                  " U5      n[         R
                  " USU-   -  5      $ )Ng      r	         ?r   gư>)r   copysignlogfabsr   sqrt)r   lmbsnrs      r   r   r   A   sm    q#'22TXXa!diiPSVWPWFXBX>X[_>_5``C((3-C99SAG_--r   r   c                 4    [         R                  " U S-  5      $ )Ng      ()r   r   r   s    r   r   r   H   s    88AI&&r   z"Unsupported alpha_transform_type: r	   dtype)
ValueErrorrangeappendmintorchtensorfloat32)r   r   r   r   betasit1t2s           r   betas_for_alpha_barr5   "   s    0 x'	D 
	*	.
 
	&	' =>R=STUUE*+(!e..S\"-R0@@@(KL , <<U]]33r   c            0          \ rS rSrSr\ V Vs/ s H  oR                  PM     snn rSr\	                      SKS\
S	\S
\S\S   S\R                  \\   -  S-  S\
S\S   S\S\S\S\S   S\S   S\S\S\S\S\S\S\S   S\
S\S \S   S!S4.S" jj5       r\S!\
4S# j5       r\S!\
4S$ j5       rSLS%\
S!S4S& jjrSMS'\
S(\\R0                  -  S)\S-  4S* jjrS+\R4                  S!\R4                  4S, jrS-\R                  S.\R                  S!\R                  4S/ jrS-\R4                  S!\\R4                  \R4                  4   4S0 jrS1\R4                  S'\
S!\R4                  4S2 jrS1\R4                  S'\
S!\R4                  4S3 jr  SNS1\R4                  S'\
S4\S5\S!\R4                  4
S6 jjr!SS7.S8\R4                  S+\R4                  S!\R4                  4S9 jjr"SS7.S8\R4                  S+\R4                  S!\R4                  4S: jjr#SS7.S;\\R4                     S+\R4                  S!\R4                  4S< jjr$SS7.S;\\R4                     S+\R4                  S!\R4                  4S= jjr% SOS>\
\R4                  -  S?\R4                  S-  S!\
4S@ jjr&S>\
\R4                  -  S!S4SA jr' SPS8\R4                  S>\
\R4                  -  S+\R4                  SB\S!\(\-  4
SC jjr)S+\R4                  S!\R4                  4SD jr*SE\R4                  SF\R4                  SG\RV                  S!\R4                  4SH jr,S!\
4SI jr-SJr.gs  snn f )QDEISMultistepSchedulerV   u(  
`DEISMultistepScheduler` is a fast high order solver for diffusion ordinary differential equations (ODEs).

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 (`"linear"`, `"scaled_linear"`, or `"squaredcos_cap_v2"`, 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` or `list[float]`, *optional*):
        Pass an array of betas directly to the constructor to bypass `beta_start` and `beta_end`.
    solver_order (`int`, defaults to `2`):
        The DEIS order which can be `1` or `2` or `3`. It is recommended to use `solver_order=2` for guided
        sampling, and `solver_order=3` for unconditional sampling.
    prediction_type (`"epsilon"`, `"sample"`, `"v_prediction"`, or `"flow_prediction"`, defaults to `"epsilon"`):
        Prediction type of the scheduler function; can be `epsilon` (predicts the noise of the diffusion process),
        `sample` (directly predicts the noisy sample`), `v_prediction` (see section 2.4 of [Imagen
        Video](https://huggingface.co/papers/2210.02303) paper), or `flow_prediction`.
    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`.
    algorithm_type (`"deis"`, defaults to `"deis"`):
        The algorithm type for the solver.
    solver_type (`"logrho"`, defaults to `"logrho"`):
        Solver type for DEIS.
    lower_order_final (`bool`, defaults to `True`):
        Whether to use lower-order solvers in the final steps. Only valid for < 15 inference steps.
    use_karras_sigmas (`bool`, *optional*, defaults to `False`):
         Whether to use Karras sigmas for step sizes in the noise schedule during the sampling process. If `True`,
         the sigmas are determined according to a sequence of noise levels {σi}.
    use_exponential_sigmas (`bool`, *optional*, defaults to `False`):
        Whether to use exponential sigmas for step sizes in the noise schedule during the sampling process.
    use_beta_sigmas (`bool`, *optional*, defaults to `False`):
        Whether to use beta sigmas for step sizes in the noise schedule during the sampling process. Refer to [Beta
        Sampling is All You Need](https://huggingface.co/papers/2407.12173) for more information.
    use_flow_sigmas (`bool`, *optional*, defaults to `False`):
        Whether to use flow sigmas for step sizes in the noise schedule during the sampling process.
    flow_shift (`float`, *optional*, defaults to `1.0`):
        The flow shift parameter for flow-based models.
    timestep_spacing (`"linspace"`, `"leading"`, or `"trailing"`, defaults to `"linspace"`):
        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.
    steps_offset (`int`, defaults to `0`):
        An offset added to the inference steps, as required by some model families.
    use_dynamic_shifting (`bool`, defaults to `False`):
        Whether to use dynamic shifting for the noise schedule.
    time_shift_type (`"exponential"`, defaults to `"exponential"`):
        The type of time shifting to apply.
r	   Ndeislogrhoexponentialnum_train_timesteps
beta_startbeta_endbeta_schedule)linearscaled_linearsquaredcos_cap_v2trained_betassolver_orderprediction_type)epsilonsamplev_predictionflow_predictionthresholdingdynamic_thresholding_ratiosample_max_valuealgorithm_typesolver_typelower_order_finaluse_karras_sigmasuse_exponential_sigmasuse_beta_sigmasuse_flow_sigmas
flow_shifttimestep_spacing)linspaceleadingtrailingsteps_offsetuse_dynamic_shiftingtime_shift_typer   c                    U R                   R                  (       a  [        5       (       d  [        S5      e[	        U R                   R                  U R                   R
                  U R                   R                  /5      S:  a  [        S5      eUb)  [        R                  " U[        R                  S9U l        OUS:X  a*  [        R                  " X#U[        R                  S9U l        OkUS:X  a4  [        R                  " US-  US-  U[        R                  S9S-  U l        O1US	:X  a  [        U5      U l        O[        U S
U R                   35      eSU R                  -
  U l        [        R"                  " U R                   SS9U l        [        R&                  " U R$                  5      U l        [        R&                  " SU R$                  -
  5      U l        [        R,                  " U R(                  5      [        R,                  " U R*                  5      -
  U l        SU R$                  -
  U R$                  -  S-  U l        SU l        US;  a0  US;   a  U R5                  SS9  O[        U S
U R                   35      eUS;  a1  US;   a  U R5                  SS9  O[        SU S
U R                   35      eS U l        [8        R                  " SUS-
  U[8        R                  S9S S S2   R;                  5       n[        R<                  " U5      U l        S /U-  U l         SU l!        S U l"        S U l#        U R0                  RI                  S5      U l        g )Nz:Make sure to install scipy if you want to use beta sigmas.r	   znOnly one of `config.use_beta_sigmas`, `config.use_exponential_sigmas`, `config.use_karras_sigmas` can be used.r(   r@   rA   r    r   rB   z is not implemented for       ?r   dim)r9   )	dpmsolverzdpmsolver++r9   )rM   )r:   )midpointheunbh1bh2r:   )rN   zsolver type cpu)%configrR   r   ImportErrorsumrQ   rP   r*   r.   r/   r0   r1   rV   r5   NotImplementedError	__class__alphascumprodalphas_cumprodr$   alpha_tsigma_tr"   lambda_tsigmasinit_noise_sigmar   num_inference_stepsnpcopy
from_numpy	timestepsmodel_outputslower_order_nums_step_index_begin_indexto)selfr<   r=   r>   r?   rC   rD   rE   rJ   rK   rL   rM   rN   rO   rP   rQ   rR   rS   rT   rU   rY   rZ   r[   rx   s                           r   __init__DEISMultistepScheduler.__init__   s   4 ;;&&/A/C/CZ[[KK//KK66KK11   A  $m5==IDJh&
>QY^YfYfgDJo- OcM'--	  J 11,-@ADJ%7OPTP^P^O_&`aaDJJ&#mmDKKQ?zz$"5"56zz!d&9&9"9:		$,,/%))DLL2IID///43F3FF3N !$ )!==''v'>)^,<<TUYUcUcTd*effj(@@''H'=)LE]^b^l^l]m*noo $( KK#6#:<OWYWaWabcgegcghmmo	)))4"Vl2 ! kknnU+r   c                     U R                   $ )zW
The index counter for current timestep. It will increase 1 after each scheduler step.
)r{   r~   s    r   
step_index!DEISMultistepScheduler.step_index   s    
 r   c                     U R                   $ )za
The index for the first timestep. It should be set from pipeline with `set_begin_index` method.
r|   r   s    r   begin_index"DEISMultistepScheduler.begin_index   s    
    r   r   c                     Xl         g)z
Sets the begin index for the scheduler. This function should be run from pipeline before the inference.

Args:
    begin_index (`int`, defaults to `0`):
        The begin index for the scheduler.
Nr   )r~   r   s     r   set_begin_index&DEISMultistepScheduler.set_begin_index  s
     (r   rt   devicemuc           	         Ub\  U R                   R                  (       a  U R                   R                  S:X  d   e[        R                  " U5      U R                   l        U R                   R                  S:X  av  [        R                  " SU R                   R                  S-
  US-   5      R                  5       SSS2   SS R                  5       R                  [        R                  5      nGOoU R                   R                  S:X  a  U R                   R                  US-   -  n[        R                  " SUS-   5      U-  R                  5       SSS2   SS R                  5       R                  [        R                  5      nX@R                   R                  -  nOU R                   R                  S:X  a  U R                   R                  U-  n[        R                  " U R                   R                  SU* 5      R                  5       R                  5       R                  [        R                  5      nUS-  nO"[        U R                   R                   S	35      e[        R                   " SU R"                  -
  U R"                  -  S
-  5      n[        R$                  " U5      nU R                   R&                  (       a  [        R(                  " U5      R                  5       nU R+                  XaS9n[        R                   " U Vs/ s H  oR-                  X5      PM     sn5      R                  5       n[        R.                  " XfSS /5      R                  [        R0                  5      nGOU R                   R2                  (       a  [        R(                  " U5      R                  5       nU R5                  XaS9n[        R                   " U Vs/ s H  oR-                  X5      PM     sn5      n[        R.                  " XfSS /5      R                  [        R0                  5      nGOZU R                   R6                  (       a  [        R(                  " U5      R                  5       nU R9                  XaS9n[        R                   " U Vs/ s H  oR-                  X5      PM     sn5      n[        R.                  " XfSS /5      R                  [        R0                  5      nGOU R                   R:                  (       a  [        R                  " SSU R                   R                  -  US-   5      n	SU	-
  n[        R(                  " U R                   R
                  U-  SU R                   R
                  S-
  U-  -   -  5      SS R                  5       nX`R                   R                  -  R                  5       n[        R.                  " XfSS /5      R                  [        R0                  5      nO[        R<                  " U[        R                  " S[?        U5      5      U5      nSU R"                  S   -
  U R"                  S   -  S
-  n
[        R.                  " Xj//5      R                  [        R0                  5      n[@        RB                  " U5      U l"        [@        RB                  " U5      RG                  U[@        R                  S9U l$        [?        U5      U l%        S/U R                   RL                  -  U l'        SU l(        SU l)        SU l*        U RD                  RG                  S5      U l"        gs  snf s  snf s  snf )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.
    device (`str` or `torch.device`, *optional*):
        The device to which the timesteps should be moved to. If `None`, the timesteps are not moved.
    mu (`float`, *optional*):
        The mu parameter for dynamic shifting. Only used when `use_dynamic_shifting=True` and
        `time_shift_type="exponential"`.
Nr;   rV   r   r	   re   rW   rX   zY is not supported. Please make sure to choose one of 'linspace', 'leading' or 'trailing'.r    )	in_sigmasrt   r]   r   r)   rf   )+rg   rZ   r[   ru   r   rT   rU   rV   r<   roundrv   astypeint64arangerY   r*   arrayrn   r"   rP   flip_convert_to_karras_sigma_to_tconcatenater0   rQ   _convert_to_exponentialrR   _convert_to_betarS   interplenr.   rw   rr   r}   rx   rt   rD   ry   rz   r{   r|   )r~   rt   r   r   rx   
step_ratiorr   
log_sigmassigmarl   
sigma_lasts              r   set_timesteps$DEISMultistepScheduler.set_timesteps  s    >;;338S8SWd8ddd%'VVBZDKK";;'':5At{{>>BDWZ[D[\2"$!	  [[))Y688=PST=TUJ 1&9A&=>KRRTUYWYUYZ[^\^_ddfmmnpnvnvwI111I[[))Z788;NNJ 		$++"A"A1zkRXXZ__ahhikiqiqrINI;;//0  1J  K  A 3 33t7J7JJsRSVVF^
;;((WWV_))+F,,v,gFSY!ZSY%"2"25"ESY!Z[aacI^^VBC[$9:AA"**MF[[//WWV_))+F11F1lFSY!ZSY%"2"25"ESY!Z[I^^VBC[$9:AA"**MF[[((WWV_))+F**V*eFSY!ZSY%"2"25"ESY!Z[I^^VBC[$9:AA"**MF[[(([[A(G(G$GI\_`I`aF6\FWWT[[33f<T[[E[E[^_E_ciDi@ijklomopuuwF++"A"AAGGII^^VBC[$9:AA"**MFYYy"))As6{*CVLFt221559L9LQ9OOTWWJ^^V\$:;BB2::NF&&v.)))477vU[[7Y#&y>  
KK$$% !"   kknnU+I "[
 "[
 "[s   
\?]]	rG   c                 X   UR                   nUR                  tp4nU[        R                  [        R                  4;  a  UR                  5       nUR                  X4[        R                  " U5      -  5      nUR                  5       n[        R                  " X`R                  R                  SS9n[        R                  " USU R                  R                  S9nUR                  S5      n[        R                  " X* U5      U-  nUR                  " X4/UQ76 nUR!                  U5      nU$ )a
  
Apply dynamic thresholding to the predicted sample.

"Dynamic thresholding: At each sampling step we set s to a certain percentile absolute pixel value in xt0 (the
prediction of x_0 at timestep t), and if s > 1, then we threshold xt0 to the range [-s, s] and then divide by
s. Dynamic thresholding pushes saturated pixels (those near -1 and 1) inwards, thereby actively preventing
pixels from saturation at each step. We find that dynamic thresholding results in significantly better
photorealism as well as better image-text alignment, especially when using very large guidance weights."

https://huggingface.co/papers/2205.11487

Args:
    sample (`torch.Tensor`):
        The predicted sample to be thresholded.

Returns:
    `torch.Tensor`:
        The thresholded sample.
r	   r^   )r-   max)r)   shaper.   r0   float64floatreshaperu   prodabsquantilerg   rK   clamprL   	unsqueezer}   )r~   rG   r)   
batch_sizechannelsremaining_dims
abs_sampless           r   _threshold_sample(DEISMultistepScheduler._threshold_samplee  s    ( 06-
~66\\^F 
rww~7N,NOZZ\
NN:{{'M'MSTUKK1$++66
 KKNVR+a/
F~F5!r   r   r   c                    [         R                  " [         R                  " US5      5      nX2SS2[         R                  4   -
  n[         R                  " US:  SS9R                  SS9R                  UR                  S   S-
  S9nUS-   nX%   nX&   nXs-
  Xx-
  -  n	[         R                  " U	SS5      n	SU	-
  U-  X-  -   n
U
R                  UR                  5      n
U
$ )at  
Convert sigma values to corresponding timestep values through interpolation.

Args:
    sigma (`np.ndarray`):
        The sigma value(s) to convert to timestep(s).
    log_sigmas (`np.ndarray`):
        The logarithm of the sigma schedule used for interpolation.

Returns:
    `np.ndarray`:
        The interpolated timestep value(s) corresponding to the input sigma(s).
g|=Nr   )axisr   )r   r	   )	ru   r"   maximumnewaxiscumsumargmaxclipr   r   )r~   r   r   	log_sigmadistslow_idxhigh_idxlowhighwr   s              r   r   "DEISMultistepScheduler._sigma_to_t  s     FF2::eU34	 q"**}55 ))UaZq188a8@EE*JZJZ[\J]`aJaEbQ;!# _,GGAq! Ug,IIekk"r   c                 v    U R                   R                  (       a
  SU-
  nUnX#4$ SUS-  S-   S-  -  nX-  nX#4$ )z
Convert sigma values to alpha_t and sigma_t values.

Args:
    sigma (`torch.Tensor`):
        The sigma value(s) to convert.

Returns:
    `tuple[torch.Tensor, torch.Tensor]`:
        A tuple containing (alpha_t, sigma_t) values.
r	   r   r    )rg   rS   )r~   r   ro   rp   s       r   _sigma_to_alpha_sigma_t.DEISMultistepScheduler._sigma_to_alpha_sigma_t  sS     ;;&&%iGG
  E1HqLS01GoGr   r   c                    [        U R                  S5      (       a  U R                  R                  nOSn[        U R                  S5      (       a  U R                  R                  nOSnUb  UOUS   R	                  5       nUb  UOUS   R	                  5       nSn[
        R                  " SSU5      nUSU-  -  nUSU-  -  nXXx-
  -  -   U-  n	U	$ )a  
Construct the noise schedule as proposed in [Elucidating the Design Space of Diffusion-Based Generative
Models](https://huggingface.co/papers/2206.00364).

Args:
    in_sigmas (`torch.Tensor`):
        The input sigma values to be converted.
    num_inference_steps (`int`):
        The number of inference steps to generate the noise schedule for.

Returns:
    `torch.Tensor`:
        The converted sigma values following the Karras noise schedule.
	sigma_minN	sigma_maxre   r   g      @r	   )hasattrrg   r   r   itemru   rV   )
r~   r   rt   r   r   rhorampmin_inv_rhomax_inv_rhorr   s
             r   r   )DEISMultistepScheduler._convert_to_karras  s    $ 4;;,,--II4;;,,--II!*!6IIbM<N<N<P	!*!6IIaL<M<M<O	{{1a!45AG,AG,(A BBsJr   c                    [        U R                  S5      (       a  U R                  R                  nOSn[        U R                  S5      (       a  U R                  R                  nOSnUb  UOUS   R	                  5       nUb  UOUS   R	                  5       n[
        R                  " [
        R                  " [        R                  " U5      [        R                  " U5      U5      5      nU$ )aP  
Construct an exponential noise schedule.

Args:
    in_sigmas (`torch.Tensor`):
        The input sigma values to be converted.
    num_inference_steps (`int`):
        The number of inference steps to generate the noise schedule for.

Returns:
    `torch.Tensor`:
        The converted sigma values following an exponential schedule.
r   Nr   re   r   )
r   rg   r   r   r   ru   r   rV   r   r"   )r~   r   rt   r   r   rr   s         r   r   .DEISMultistepScheduler._convert_to_exponential  s    " 4;;,,--II4;;,,--II!*!6IIbM<N<N<P	!*!6IIaL<M<M<O	DHHY$7)9LNabcr   alphabetac           
      J   [        U R                  S5      (       a  U R                  R                  nOSn[        U R                  S5      (       a  U R                  R                  nOSnUb  UOUS   R	                  5       nUb  UOUS   R	                  5       n[
        R                  " S[
        R                  " SSU5      -
   Vs/ s H-  n[        R                  R                  R                  XsU5      PM/     sn Vs/ s H  nXXXe-
  -  -   PM     sn5      n	U	$ s  snf s  snf )az  
Construct a beta noise schedule as proposed in [Beta Sampling is All You
Need](https://huggingface.co/papers/2407.12173).

Args:
    in_sigmas (`torch.Tensor`):
        The input sigma values to be converted.
    num_inference_steps (`int`):
        The number of inference steps to generate the noise schedule for.
    alpha (`float`, *optional*, defaults to `0.6`):
        The alpha parameter for the beta distribution.
    beta (`float`, *optional*, defaults to `0.6`):
        The beta parameter for the beta distribution.

Returns:
    `torch.Tensor`:
        The converted sigma values following a beta distribution schedule.
r   Nr   re   r   r	   )r   rg   r   r   r   ru   r   rV   scipystatsr   ppf)
r~   r   rt   r   r   r   r   timestepr   rr   s
             r   r   'DEISMultistepScheduler._convert_to_beta  s   0 4;;,,--II4;;,,--II!*!6IIbM<N<N<P	!*!6IIaL<M<M<O	
 %&Aq:M(N$N$N KK$$(($?$NC I$9:;
 s   4D?D rG   model_outputc                J   [        U5      S:  a  US   OUR                  SS5      nUc   [        U5      S:  a  US   nO[        S5      eUb  [        SSS5        U R                  U R
                     nU R                  U5      u  pxU R                  R                  S	:X  a  X(U-  -
  U-  n	OU R                  R                  S
:X  a  Un	OU R                  R                  S:X  a
  Xr-  X-  -
  n	O^U R                  R                  S:X  a!  U R                  U R
                     nX(U-  -
  n	O#[        SU R                  R                   S35      eU R                  R                  (       a  U R                  U	5      n	U R                  R                  S:X  a
  X'U	-  -
  U-  $ [        S5      e)a  
Convert the model output to the corresponding type the DEIS algorithm needs.

Args:
    model_output (`torch.Tensor`):
        The direct output from the learned diffusion model.
    timestep (`int`):
        The current discrete timestep in the diffusion chain.
    sample (`torch.Tensor`):
        A current instance of a sample created by the diffusion process.

Returns:
    `torch.Tensor`:
        The converted model output.
r   r   Nr	   /missing `sample` as a required keyword argumentrx   1.0.0Passing `timesteps` is deprecated and has no effect as model output conversion is now handled via an internal counter `self.step_index`rF   rG   rH   rI   zprediction_type given as zi must be one of `epsilon`, `sample`, `v_prediction`, or `flow_prediction` for the DEISMultistepScheduler.r9   'only support log-rho multistep deis now)r   popr*   r   rr   r   r   rg   rE   rJ   r   rM   rj   )
r~   r   rG   argskwargsr   r   ro   rp   x0_preds
             r   convert_model_output+DEISMultistepScheduler.convert_model_outputE  s   , "$i!m47J1M>4y1}a !RSS Z DOO,77>;;&&)3, 66'AG[[((H4"G[[((N:&)??G[[((,==kk$//2G55G+DKK,G,G+H IW W 
 ;;##,,W5G;;%%/w..'99%&OPPr   c                ,   [        U5      S:  a  US   OUR                  SS5      n[        U5      S:  a  US   OUR                  SS5      nUc   [        U5      S:  a  US   nO[        S5      eUb  [        SS	S
5        Ub  [        SS	S5        U R                  U R
                  S-      U R                  U R
                     pU R                  U5      u  pU R                  U5      u  p[        R                  " U	5      [        R                  " U5      -
  n[        R                  " U
5      [        R                  " U5      -
  nX-
  nU R                  R                  S:X  a)  X-  U-  U[        R                  " U5      S-
  -  U-  -
  nU$ [        S5      e)a  
One step for the first-order DEIS (equivalent to DDIM).

Args:
    model_output (`torch.Tensor`):
        The direct output from the learned diffusion model.
    timestep (`int`):
        The current discrete timestep in the diffusion chain.
    prev_timestep (`int`):
        The previous discrete timestep in the diffusion chain.
    sample (`torch.Tensor`):
        A current instance of a sample created by the diffusion process.

Returns:
    `torch.Tensor`:
        The sample tensor at the previous timestep.
r   r   Nr	   prev_timestepr   r   rx   r   r   Passing `prev_timestep` is deprecated and has no effect as model output conversion is now handled via an internal counter `self.step_index`r9   r]   r   )r   r   r*   r   rr   r   r   r.   r"   rg   rM   r   rj   )r~   r   rG   r   r   r   r   rp   sigma_sro   alpha_srq   lambda_shx_ts                  r   deis_first_order_update.DEISMultistepScheduler.deis_first_order_update  s   0 "$i!m47J1M#&t9q=QfjjRV6W>4y1}a !RSS Z $ ^ KK!+,KK(   77@77@99W%		'(::99W%		'(::;;%%/$.'UYYq\C=O2PT`1``C 
 &&OPPr   model_output_listc                *   [        U5      S:  a  US   OUR                  SS5      n[        U5      S:  a  US   OUR                  SS5      nUc   [        U5      S:  a  US   nO[        S5      eUb  [        SSS	5        Ub  [        SSS
5        U R                  U R
                  S-      U R                  U R
                     U R                  U R
                  S-
     pnU R                  U5      u  pU R                  U5      u  pU R                  U	5      u  pUS   US   pXz-  X-  X-  nnnU R                  R                  S:X  aB  S nU" UUU5      U" UUU5      -
  nU" UUU5      U" UUU5      -
  nXU-  UU-  -   UU-  -   -  nU$ [        S5      e)au  
One step for the second-order multistep DEIS.

Args:
    model_output_list (`list[torch.Tensor]`):
        The direct outputs from learned diffusion model at current and latter timesteps.
    sample (`torch.Tensor`):
        A current instance of a sample created by the diffusion process.

Returns:
    `torch.Tensor`:
        The sample tensor at the previous timestep.
r   timestep_listNr	   r   r   r   r   Passing `timestep_list` is deprecated and has no effect as model output conversion is now handled via an internal counter `self.step_index`r   re   r9   c                     U [         R                  " U5      * [         R                  " U 5      -   S-
  -  [         R                  " U5      [         R                  " U5      -
  -  $ )Nr	   ru   r"   )r   bcs      r   ind_fnIDEISMultistepScheduler.multistep_deis_second_order_update.<locals>.ind_fn  sC    RVVAYJ2Q67266!9rvvay;PQQr   r   
r   r   r*   r   rr   r   r   rg   rM   rj   )r~   r   rG   r   r   r   r   rp   sigma_s0sigma_s1ro   alpha_s0alpha_s1m0m1rho_trho_s0rho_s1r   coef1coef2r   s                         r   "multistep_deis_second_order_update9DEISMultistepScheduler.multistep_deis_second_order_update  s   ( $'t9q=QfjjRV6W#&t9q=QfjjRV6W>4y1}a !RSS$ ^ $ ^ KK!+,KK(KK!+, $  77@!99(C!99(C"2&(9"(=B  v ;;%%/R 5&&1F6664RRE5&&1F6664RREh.;ebjHICJ%&OPPr   c                   [        U5      S:  a  US   OUR                  SS5      n[        U5      S:  a  US   OUR                  SS5      nUc   [        U5      S:  a  US   nO[        S5      eUb  [        SSS	5        Ub  [        SSS
5        U R                  U R
                  S-      U R                  U R
                     U R                  U R
                  S-
     U R                  U R
                  S-
     4u  pxpU R                  U5      u  pU R                  U5      u  pU R                  U	5      u  pU R                  U
5      u  pUS   US   US   nnnX{-  X-  X-  X-  4u  nnnnU R                  R                  S:X  ac  S nU" UUUU5      U" UUUU5      -
  nU" UUUU5      U" UUUU5      -
  nU" UUUU5      U" UUUU5      -
  nXU-  UU-  -   UU-  -   UU-  -   -  nU$ [        S5      e)ap  
One step for the third-order multistep DEIS.

Args:
    model_output_list (`list[torch.Tensor]`):
        The direct outputs from learned diffusion model at current and latter timesteps.
    sample (`torch.Tensor`):
        A current instance of a sample created by diffusion process.

Returns:
    `torch.Tensor`:
        The sample tensor at the previous timestep.
r   r   Nr	   r   r   r   r   r   r   re   r   r9   c                 L   U [         R                  " U5      [         R                  " U5      [         R                  " U 5      -
  S-   -  [         R                  " U5      [         R                  " U 5      -  -
  [         R                  " U5      -   [         R                  " U 5      S-  -   S[         R                  " U 5      -  -
  S-   -  n[         R                  " U5      [         R                  " U5      -
  [         R                  " U5      [         R                  " U5      -
  -  nXE-  $ )Nr	   r   r   )r   r   r   d	numeratordenominators         r   r   HDEISMultistepScheduler.multistep_deis_third_order_update.<locals>.ind_fnH  s    FF1IRVVAY!6!:;ffQi"&&)+,ffQi  ffQi1n% "&&)m	$
 	  "vvay266!94RVVAY9NO ..r   r   r   )r~   r   rG   r   r   r   r   rp   r   r   sigma_s2ro   r  r  alpha_s2r  r  m2r  r  r  rho_s2r   r  r	  coef3r   s                              r   !multistep_deis_third_order_update8DEISMultistepScheduler.multistep_deis_third_order_update  sP   * $'t9q=QfjjRV6W#&t9q=QfjjRV6W>4y1}a !RSS$ ^ $ ^ KK!+,KK(KK!+,KK!+,	1
-8  77@!99(C!99(C!99(C&r*,=b,ACTUWCXB 	)
%vvv ;;%%// 5&&&9F66SY[a<bbE5&&&9F66SY[a<bbE5&&&9F66SY[a<bbEh.;ebjH5SU:UVCJ%&OPPr   r   schedule_timestepsc                    Uc  U R                   nX!:H  R                  5       n[        U5      S:X  a  [        U R                   5      S-
  nU$ [        U5      S:  a  US   R                  5       nU$ US   R                  5       nU$ )ab  
Find the index for a given timestep in the schedule.

Args:
    timestep (`int` or `torch.Tensor`):
        The timestep for which to find the index.
    schedule_timesteps (`torch.Tensor`, *optional*):
        The timestep schedule to search in. If `None`, uses `self.timesteps`.

Returns:
    `int`:
        The index of the timestep in the schedule.
r   r	   )rx   nonzeror   r   )r~   r   r  index_candidatesr   s        r   index_for_timestep)DEISMultistepScheduler.index_for_timestep`  s    $ %!%.:CCE A%T^^,q0J  !"Q&)!,113J  *!,113Jr   c                     U R                   c[  [        U[        R                  5      (       a%  UR	                  U R
                  R                  5      nU R                  U5      U l        gU R                  U l        g)z
Initialize the step_index counter for the scheduler.

Args:
    timestep (`int` or `torch.Tensor`):
        The current timestep for which to initialize the step index.
N)
r   
isinstancer.   Tensorr}   rx   r   r  r{   r|   )r~   r   s     r   _init_step_index'DEISMultistepScheduler._init_step_index  sZ     #(ELL11#;;t~~'<'<=#66x@D#00Dr   return_dictc                    U R                   c  [        S5      eU R                  c  U R                  U5        U R                  [	        U R
                  5      S-
  :H  =(       a5    U R                  R                  =(       a    [	        U R
                  5      S:  nU R                  [	        U R
                  5      S-
  :H  =(       a5    U R                  R                  =(       a    [	        U R
                  5      S:  nU R                  XS9n[        U R                  R                  S-
  5       H"  nU R                  US-      U R                  U'   M$     XR                  S'   U R                  R                  S:X  d  U R                  S:  d  U(       a  U R                  XS9nOfU R                  R                  S:X  d  U R                  S:  d  U(       a  U R                  U R                  US9nOU R                  U R                  US9nU R                  U R                  R                  :  a  U =R                  S-  sl        U =R                   S-  sl        U(       d  U4$ [#        US9$ )a=  
Predict the sample from the previous timestep by reversing the SDE. This function propagates the sample with
the multistep DEIS.

Args:
    model_output (`torch.Tensor`):
        The direct output from learned diffusion model.
    timestep (`int` or `torch.Tensor`):
        The current discrete timestep in the diffusion chain.
    sample (`torch.Tensor`):
        A current instance of a sample created by the diffusion process.
    return_dict (`bool`, defaults to `True`):
        Whether or not to return a [`~schedulers.scheduling_utils.SchedulerOutput`] or `tuple`.

Returns:
    [`~schedulers.scheduling_utils.SchedulerOutput`] or `tuple`:
        If return_dict is `True`, [`~schedulers.scheduling_utils.SchedulerOutput`] 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   r   re   )prev_sample)rt   r*   r   r#  r   rx   rg   rO   r   r+   rD   ry   rz   r   r
  r  r{   r   )	r~   r   r   rG   r%  rO   lower_order_secondr2   r(  s	            r   stepDEISMultistepScheduler.step  s   4 ##+s  ??"!!(+ __DNN 3a 77wT[[=Z=Zw_bcgcqcq_ruw_w 	 __DNN 3a 77wT[[=Z=Zw_bcgcqcq_ruw_w 	 000Mt{{//!34A$($6$6q1u$=Dq! 5!-2;;##q(D,A,AA,EIZ66|6SK[[%%*d.C.Ca.GK]AA$BTBT]cAdK@@ASAS\b@cK  4;;#;#;;!!Q&! 	A>!;77r   c                     U$ )z
Ensures interchangeability with schedulers that need to scale the denoising model input depending on the
current timestep.

Args:
    sample (`torch.Tensor`):
        The input sample.

Returns:
    `torch.Tensor`:
        A scaled input sample.
 )r~   rG   r   r   s       r   scale_model_input(DEISMultistepScheduler.scale_model_input  s	     r   original_samplesnoiserx   c                 *   U R                   R                  UR                  UR                  S9nUR                  R                  S:X  av  [
        R                  " U5      (       a[  U R                  R                  UR                  [
        R                  S9nUR                  UR                  [
        R                  S9nO@U R                  R                  UR                  5      nUR                  UR                  5      nU R                  c!  U Vs/ s H  o`R                  Xe5      PM     nnOHU R                  b  U R                  /UR                  S   -  nOU R                  /UR                  S   -  nXG   R                  5       n[        UR                  5      [        UR                  5      :  a?  UR                  S5      n[        UR                  5      [        UR                  5      :  a  M?  U R!                  U5      u  pX-  X-  -   nU$ s  snf )a  
Add noise to the original samples according to the noise schedule at the specified timesteps.

Args:
    original_samples (`torch.Tensor`):
        The original samples without noise.
    noise (`torch.Tensor`):
        The noise to add to the samples.
    timesteps (`torch.IntTensor`):
        The timesteps at which to add noise to the samples.

Returns:
    `torch.Tensor`:
        The noisy samples.
r   mpsr(   r   re   )rr   r}   r   r)   typer.   is_floating_pointrx   r0   r   r  r   r   flattenr   r   r   )r~   r0  r1  rx   rr   r  r   step_indicesr   ro   rp   noisy_sampless               r   	add_noise DEISMultistepScheduler.add_noise  s   , '7'>'>FVF\F\]""''50U5L5LY5W5W!%!2!23C3J3JRWR_R_!2!`!%5%<%<EMMRI!%!2!23C3J3J!K!%5%<%<=I #T]^T]q33AJT]L^L__( OO,yq/AAL !,,-	0BBL$,,.%++%5%;%;!<<OOB'E %++%5%;%;!<<  77>2W_D _s   Hc                 .    U R                   R                  $ N)rg   r<   r   s    r   __len__DEISMultistepScheduler.__len__  s    {{...r   )r|   r{   ro   rl   rn   r1   rs   rq   rz   ry   rt   rp   rr   rx   )i  g-C6?g{Gz?r@   Nr   rF   Fgףp=
?r]   r9   r:   TFFFFr]   rV   r   Fr;   )r   )NN)333333?r?  r<  )T)/__name__
__module____qualname____firstlineno____doc__r
   name_compatiblesorderr   intr   r   ru   ndarraylistboolr   propertyr   r   r   strr.   r   r   r"  r   r   tupler   r   r   r   r   r   r
  r  r  r#  r   r*  r.  	IntTensorr9  r=  __static_attributes__).0es   00r   r7   r7   V   s   ;z %>>$=qFF$=>LE $("QY9=[d",1"%*0)1"&"'', % %GQ%*2?/], ], ], 	],
 MN], zzDK/$6], ], !!WX], ], %*],  ],  ], X&],  ],  ],  !%!]," #],$ %],& '],( ""CD)],* +],, #-],. !//],0 
1], ],~  C     !S ! !(3 (t (R, R,cELL>P R,]bei]i R,j) ) )X" " "

 "J U\\  eELLRWR^R^D^>_  ,$ELL $s $W\WcWc $N TW \a\h\h F dg..<?.HM.[`.	.h  $	:Qll:Q 	:Q 
:Q@  $	;ll; 	; 
;B  $	GQ-GQ 	GQ 
GQZ  $	VQ-VQ 	VQ 
VQx 37"$" "LL4/" 
	"J1u||); 1 1* !>8ll>8 $>8 	>8
 >8 
5	 >8@ %,,  /,,/ ||/ ??	/
 
/b/ /E ?s   L>r7   )g+?r   )r   typingr   numpyru   r.   configuration_utilsr   r   utilsr   r   scheduling_utilsr
   r   r   scipy.statsr   rH  r   r"  r5   r7   r-  r   r   <module>rY     sy   $     A 1 X X  @H14 1414 ""<=14 \\	14hA/^[ A/r   