
    +hX                         S SK r S SKJrJrJr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 jr " S	 S
\\
5      rg)    N)ListOptionalTupleUnion   )ConfigMixinregister_to_config)	deprecateis_scipy_available   )KarrasDiffusionSchedulersSchedulerMixinSchedulerOutputc           
      &   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`): 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                 h    [         R                  " U S-   S-  [         R                  -  S-  5      S-  $ )NgMb?gT㥛 ?r   )mathcospits    h/home/james-whalen/.local/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    expc                 4    [         R                  " U S-  5      $ )Ng      ()r   r   r   s    r   r   r   @   s    88AI&&r   z"Unsupported alpha_transform_type: r   dtype)
ValueErrorrangeappendmintorchtensorfloat32)num_diffusion_timestepsmax_betaalpha_transform_typer   betasit1t2s           r   betas_for_alpha_barr.   "   s    . x'	D 
	&	' =>R=STUUE*+(!e..S\"-R0@@@(KL , <<U]]33r   c            .       V   \ rS rSrSr\ V Vs/ s H  oR                  PM     snn rSr\	                      SBS\
S\S\S\S	\\R                     S
\
S\S\S\S\S\S\S\S\\   S\\   S\\   S\\   S\\   S\S\
S\S\4,S jj5       r\S 5       r\S 5       rSCS\
4S jjr SDS \
S!\\\R0                  4   S"\\   4S# jjrS$\R4                  S%\R4                  4S& jrS' rS( rS)\R4                  S%\R4                  4S* jrS)\R4                  S \
S%\R4                  4S+ jr SES)\R4                  S \
S,\S-\S%\R4                  4
S. jjr SS/.S0\R4                  S$\R4                  S%\R4                  4S1 jjr!SS/.S0\R4                  S$\R4                  S%\R4                  4S2 jjr"SS/.S3\#\R4                     S$\R4                  S%\R4                  4S4 jjr$SS/.S3\#\R4                     S$\R4                  S%\R4                  4S5 jjr%SFS6 jr&S7 r' SGS0\R4                  S8\\
\R4                  4   S$\R4                  S9\S%\\(\)4   4
S: jjr*S$\R4                  S%\R4                  4S; jr+S<\R4                  S=\R4                  S>\RX                  S%\R4                  4S? jr-S@ r.SAr/gs  snn f )HDEISMultistepSchedulerN   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 (`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`.
    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 (`str`, 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`) 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`.
    algorithm_type (`str`, defaults to `deis`):
        The algorithm type for the solver.
    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.
    timestep_spacing (`str`, 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.
r   Nnum_train_timesteps
beta_startbeta_endbeta_scheduletrained_betassolver_orderprediction_type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steps_offsetuse_dynamic_shiftingtime_shift_typec                    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   linearscaled_linear      ?r   squaredcos_cap_v2z is not implemented for       ?r   dim)deis)	dpmsolverzdpmsolver++rP   )r<   )logrho)midpointheunbh1bh2rR   )r=   zsolver type cpu)%configrA   r   ImportErrorsumr@   r?   r    r$   r%   r&   r*   linspacer.   NotImplementedError	__class__alphascumprodalphas_cumprodsqrtalpha_tsigma_tloglambda_tsigmasinit_noise_sigmar	   num_inference_stepsnpcopy
from_numpy	timestepsmodel_outputslower_order_nums_step_index_begin_indexto)selfr2   r3   r4   r5   r6   r7   r8   r9   r:   r;   r<   r=   r>   r?   r@   rA   rB   rC   rD   rE   rF   rG   rm   s                           r   __init__DEISMultistepScheduler.__init__   s   4 ;;&&/A/C/CZ[[++T[[-O-OQUQ\Q\QnQnopstt A  $m5==IDJh&
>QY^YfYfgDJo-
C3H[chcpcpquvvDJ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.
)rp   rs   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.
rq   rw   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`):
        The begin index for the scheduler.
Nr{   )rs   r|   s     r   set_begin_index&DEISMultistepScheduler.set_begin_index   s
     (r   ri   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 )au  
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.
Nexponentialr\   r   r   rW   leadingtrailingzY is not supported. Please make sure to choose one of 'linspace', 'leading' or 'trailing'.rK   )	in_sigmasri   rM   r   r   rX   )+rY   rF   rG   rj   r   rC   rD   r\   r2   roundrk   astypeint64arangerE   r    arrayra   re   r?   flip_convert_to_karras_sigma_to_tconcatenater&   r@   _convert_to_exponentialrA   _convert_to_betarB   interplenr$   rl   rg   rr   rm   ri   r7   rn   ro   rp   rq   )rs   ri   r   r   rm   
step_ratiorg   
log_sigmassigmar_   
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   
\?]]	samplereturnc                 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$ )aC  
"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
r   rN   )r#   max)r   shaper$   r&   float64floatreshaperj   prodabsquantilerY   r:   clampr;   	unsqueezerr   )rs   r   r   
batch_sizechannelsremaining_dims
abs_sampless           r   _threshold_sample(DEISMultistepScheduler._threshold_sampleA  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   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
$ )Ng|=r   )axisr   )r   r   )	rj   re   maximumnewaxiscumsumargmaxclipr   r   )rs   r   r   	log_sigmadistslow_idxhigh_idxlowhighwr   s              r   r   "DEISMultistepScheduler._sigma_to_tc  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$ )Nr   r   rK   )rY   rB   )rs   r   rc   rd   s       r   _sigma_to_alpha_sigma_t.DEISMultistepScheduler._sigma_to_alpha_sigma_t{  sQ    ;;&&%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	$ )z6Constructs the noise schedule of Karras et al. (2022).	sigma_minN	sigma_maxrW   r   g      @r   )hasattrrY   r   r   itemrj   r\   )
rs   r   ri   r   r   rhorampmin_inv_rhomax_inv_rhorg   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$ )z)Constructs an exponential noise schedule.r   Nr   rW   r   )
r   rY   r   r   r   rj   r   r\   r   re   )rs   r   ri   r   r   rg   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 )zJFrom "Beta Sampling is All You Need" [arXiv:2407.12173] (Lee et. al, 2024)r   Nr   rW   r   r   )r   rY   r   r   r   rj   r   r\   scipystatsr   ppf)
rs   r   ri   r   r   r   r   timestepr   rg   s
             r   r   'DEISMultistepScheduler._convert_to_beta  s    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 r   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 argumentrm   1.0.0Passing `timesteps` is deprecated and has no effect as model output conversion is now handled via an internal counter `self.step_index`epsilonr   v_predictionflow_predictionzprediction_type given as zi must be one of `epsilon`, `sample`, `v_prediction`, or `flow_prediction` for the DEISMultistepScheduler.rP   'only support log-rho multistep deis now)r   popr    r
   rg   rx   r   rY   r8   r9   r   r<   r]   )
rs   r   r   argskwargsr   r   rc   rd   x0_preds
             r   convert_model_output+DEISMultistepScheduler.convert_model_output  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   rm   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`rP   rM   r   )r   r   r    r
   rg   rx   r   r$   re   rY   r<   r   r]   )rs   r   r   r   r   r   r   rd   sigma_src   alpha_srf   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 $ ^  ;;t':;T[[=Y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   rW   rP   c                     U [         R                  " U5      * [         R                  " U 5      -   S-
  -  [         R                  " U5      [         R                  " U5      -
  -  $ )Nr   rj   re   )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
   rg   rx   r   rY   r<   r]   )rs   r   r   r   r   r   r   rd   sigma_s0sigma_s1rc   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_updateK  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 ' 183FH[vv;;%%/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   rW   r   rP   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_fn  s    FF1IRVVAY!6!:;ffQi"&&)+,ffQi  ffQi1n% "&&)m	$
 	  "vvay266!94RVVAY9NO ..r   r   r   )rs   r   r   r   r   r   r   rd   r   r   sigma_s2rc   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   c                    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$ )Nr   r   )rm   nonzeror   r   )rs   r   schedule_timestepsindex_candidatesrx   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)z6
Initialize the step_index counter for the scheduler.
N)
r|   
isinstancer$   Tensorrr   rm   r   r  rp   rq   )rs   r   s     r   _init_step_index'DEISMultistepScheduler._init_step_index  sZ    
 #(ELL11#;;t~~'<'<=#66x@D#00Dr   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`):
        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`):
        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   rW   )prev_sample)ri   r    rx   r   r   rm   rY   r>   r   r!   r7   rn   ro   r   r  r  rp   r   )	rs   r   r   r   r"  r>   lower_order_secondr+   r%  s	            r   stepDEISMultistepScheduler.step	  s   6 ##+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.
 )rs   r   r   r   s       r   scale_model_input(DEISMultistepScheduler.scale_model_inputJ  s	     r   original_samplesnoiserm   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 )Nr   mpsr   r   rW   )rg   rr   r   r   typer$   is_floating_pointrm   r&   r|   r  rx   r   flattenr   r   r   )rs   r-  r.  rm   rg   r  r   step_indicesr   rc   rd   noisy_sampless               r   	add_noise DEISMultistepScheduler.add_noiseZ  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)rY   r2   rw   s    r   __len__DEISMultistepScheduler.__len__|  s    {{...r   )rq   rp   rc   r_   ra   r*   rh   rf   ro   rn   ri   rd   rg   rm   )i  g-C6?g{Gz?rI   Nr   r   Fgףp=
?rM   rP   rR   TFFFFrM   r\   r   Fr   )r   )NN)333333?r<  r9  )T)0__name__
__module____qualname____firstlineno____doc__r   name_compatiblesorderr	   intr   strr   rj   ndarrayboolrt   propertyrx   r|   r   r   r$   r   r   r  r   r   r   r   r   r   r   r   r   r  r  r  r   r   r   r'  r+  	IntTensorr6  r:  __static_attributes__).0es   00r   r0   r0   N   sV   1f %>>$=qFF$=>LE $("%.2(",1"%$#"&,116*/*/&) *%*,/L, L, L, 	L,
 L,  

+L, L, L, L, %*L,  L, L, L,  L, $D>L,  !)!L," "$#L,$ "$%L,& UO'L,( )L,* +L,, #-L,. /L, L,\     ! !(3 ( hlQ,#&Q,05c5<<6G0HQ,U]^cUdQ,h  D0 ELL RWR^R^ 4 TW \a\h\h . dg<?HM[`	F  $	:Qll:Q 	:Q 
:Q@  $	8ll8 	8 
8|  $	CQ-CQ 	CQ 
CQR  $	VQ-VQ 	VQ 
VQr(
1" !?8ll?8 U\\)*?8 	?8
 ?8 
%	&?8B %,,   ,,  ||  ??	 
 
 D/u ?s   J%r0   )g+?r   )r   typingr   r   r   r   numpyrj   r$   configuration_utilsr   r	   utilsr
   r   scheduling_utilsr   r   r   scipy.statsr   r.   r0   r*  r   r   <module>rT     sN   $  / /   A 1 X X  !)4Xo/^[ o/r   