
    +hL                         S SK r S SKJr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  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)CallableListOptionalTupleUnion   )ConfigMixinregister_to_config)	deprecateis_scipy_available)randn_tensor   )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    b/home/james-whalen/.local/lib/python3.13/site-packages/diffusers/schedulers/scheduling_sasolver.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   A   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_barr0   #   s    . 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\	SSSSSS	S	S
SSSSSSSSSSS\
" S5      * SSS4S\S\
S\
S\S\\\R                   \\
   4      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+ 5       r\S, 5       rSXS-\4S. jjrSYS/\S0\\\R4                  4   4S1 jjrS2\R8                  S3\R8                  4S4 jrS5 rS6 rS7\R8                  S3\R8                  4S8 jr S7\R8                  S/\S3\R8                  4S9 jr! SZS7\R8                  S/\S:\
S;\
S3\R8                  4
S< jjr"SS=.S>\R8                  S2\R8                  S3\R8                  4S? jjr#S@ r$SA r%SB r&SC r'S>\R8                  S2\R8                  SD\R8                  SE\SF\R8                  S3\R8                  4SG jr(SH\R8                  SI\R8                  SJ\R8                  SK\R8                  SE\SF\R8                  S3\R8                  4SL jr)S[SM jr*SN r+  S\S>\R8                  SO\S2\R8                  SP\S3\\,\-4   4
SQ jjr.S2\R8                  S3\R8                  4SR jr/SS\R8                  SD\R8                  ST\R`                  S3\R8                  4SU jr1SV r2SWr3gs  snn f )]SASolverSchedulerO   u  
`SASolverScheduler` is a fast dedicated high-order solver for diffusion SDEs.

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`.
    predictor_order (`int`, defaults to 2):
        The predictor order which can be `1` or `2` or `3` or '4'. It is recommended to use `predictor_order=2` for
        guided sampling, and `predictor_order=3` for unconditional sampling.
    corrector_order (`int`, defaults to 2):
        The corrector order which can be `1` or `2` or `3` or '4'. It is recommended to use `corrector_order=2` for
        guided sampling, and `corrector_order=3` for unconditional sampling.
    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).
    tau_func (`Callable`, *optional*):
        Stochasticity during the sampling. Default in init is `lambda t: 1 if t >= 200 and t <= 800 else 0`.
        SA-Solver will sample from vanilla diffusion ODE if tau_func is set to `lambda t: 0`. SA-Solver will sample
        from vanilla diffusion SDE if tau_func is set to `lambda t: 1`. For more details, please check
        https://huggingface.co/papers/2309.05019
    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` and
        `algorithm_type="dpmsolver++"`.
    algorithm_type (`str`, defaults to `data_prediction`):
        Algorithm type for the solver; can be `data_prediction` or `noise_prediction`. It is recommended to use
        `data_prediction` with `solver_order=2` for guided sampling like in Stable Diffusion.
    lower_order_final (`bool`, defaults to `True`):
        Whether to use lower-order solvers in the final steps. Default = True.
    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.
    lambda_min_clipped (`float`, defaults to `-inf`):
        Clipping threshold for the minimum value of `lambda(t)` for numerical stability. This is critical for the
        cosine (`squaredcos_cap_v2`) noise schedule.
    variance_type (`str`, *optional*):
        Set to "learned" or "learned_range" for diffusion models that predict variance. If set, the model's output
        contains the predicted Gaussian variance.
    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   i  g-C6?g{Gz?linearNr   epsilonFgףp=
?      ?data_predictionTinflinspacer   num_train_timesteps
beta_startbeta_endbeta_scheduletrained_betaspredictor_ordercorrector_orderprediction_typetau_functhresholdingdynamic_thresholding_ratiosample_max_valuealgorithm_typelower_order_finaluse_karras_sigmasuse_exponential_sigmasuse_beta_sigmasuse_flow_sigmas
flow_shiftlambda_min_clippedvariance_typetimestep_spacingsteps_offsetc                    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;  a  [        U S
U R                   35      eS U l        [6        R                  " SUS-
  U[6        R                  S9S S S2   R9                  5       n[        R:                  " U5      U l        S /[?        XgS-
  5      -  U l         S /[?        XgS-
  5      -  U l!        U	c	  S U l"        OXl"        US:H  U l#        SU l$        S U l%        S U l&        S U l'        U R0                  RQ                  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    r4   scaled_linear      ?r   squaredcos_cap_v2z is not implemented for r6   r   dim)r7   noise_predictionc                 "    U S:  a  U S::  a  S$ S$ )N   i   r   r    r   s    r   <lambda>,SASolverScheduler.__init__.<locals>.<lambda>   s    18Sa&Ga&Gr   r7   cpu))configrJ   r   ImportErrorsumrI   rH   r"   r&   r'   r(   r,   r9   r0   NotImplementedError	__class__alphascumprodalphas_cumprodsqrtalpha_tsigma_tloglambda_tsigmasinit_noise_sigmanum_inference_stepsnpcopy
from_numpy	timestepsmaxtimestep_listmodel_outputsrB   
predict_x0lower_order_numslast_sample_step_index_begin_indexto)selfr:   r;   r<   r=   r>   r?   r@   rA   rB   rC   rD   rE   rF   rG   rH   rI   rJ   rK   rL   rM   rN   rO   rP   rr   s                            r   __init__SASolverScheduler.__init__   s   6 ;;&&/A/C/CZ[[++T[[-O-OQUQ\Q\QnQnopstt 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 !$!HH%(88PQUQ_Q_P`&abb $( KK#6#:<OWYWaWabcgegcghmmo	)))4"Vc/Q;N&OO"Vc/Q;N&OOGDM$M(,== ! kknnU+r   c                     U R                   $ )zW
The index counter for current timestep. It will increase 1 after each scheduler step.
)ry   r|   s    r   
step_indexSASolverScheduler.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.
rz   r   s    r   begin_indexSASolverScheduler.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   )r|   r   s     r   set_begin_index!SASolverScheduler.set_begin_index   s
     (r   rn   devicec           	         [         R                  " [         R                  " U R                  S/5      U R                  R
                  5      nU R                  R                  U-
  R                  5       R                  5       nU R                  R                  S:X  ab  [        R                  " SUS-
  US-   5      R                  5       SSS2   SS R                  5       R                  [        R                  5      nGOFU R                  R                  S:X  a  XAS-   -  n[        R                   " SUS-   5      U-  R                  5       SSS2   SS R                  5       R                  [        R                  5      nXPR                  R"                  -  nOU R                  R                  S:X  aq  U R                  R                  U-  n[        R                   " U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/                  XqS
9n[        R&                  " U V	s/ s H  oR1                  X5      PM     sn	5      R                  5       n[        R2                  " XwSS /5      R                  [        R4                  5      nGOU R                  R6                  (       a  [        R                  " U5      R                  5       nU R9                  XqS
9n[        R&                  " U V	s/ s H  oR1                  X5      PM     sn	5      n[        R2                  " XwSS /5      R                  [        R4                  5      nGOZU R                  R:                  (       a  [        R                  " U5      R                  5       nU R=                  XqS
9n[        R&                  " U V	s/ s H  oR1                  X5      PM     sn	5      n[        R2                  " XwSS /5      R                  [        R4                  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XpR                  R                  -  R                  5       n[        R2                  " XwSS /5      R                  [        R4                  5      nO[        RB                  " U[        R                   " S[E        U5      5      U5      nSU R(                  S   -
  U R(                  S   -  S	-  n[        R2                  " X{//5      R                  [        R4                  5      n[         RF                  " U5      U l$        [         RF                  " U5      RK                  U[         R                  S9U l&        [E        U5      U l'        S/[Q        U R                  RR                  U R                  RT                  S-
  5      -  U l+        SU l,        SU l-        SU l.        SU l/        U RH                  RK                  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.
r   r9   r   NrX   leadingtrailingzY is not supported. Please make sure to choose one of 'linspace', 'leading' or 'trailing'.rS   )	in_sigmasrn   r6   )r   r!   r^   )0r&   searchsortedfliprk   r_   rM   r:   numpyitemrO   ro   r9   roundrp   astypeint64arangerP   r"   arrayrf   rj   rH   _convert_to_karras_sigma_to_tconcatenater(   rI   _convert_to_exponentialrJ   _convert_to_betarK   rL   interplenrq   rl   r{   rr   rn   rs   r?   r@   ru   rw   rx   ry   rz   )r|   rn   r   clipped_idxlast_timesteprr   
step_ratiorl   
log_sigmassigmard   
sigma_lasts               r   set_timestepsSASolverScheduler.set_timesteps  s    ((DMMA3)GIgIgh++99KGNNPVVX ;;'':5A}q02E2IJPPRSWUWSWXY\Z\]bbdkklnltltu  [[))Y6&+BCJ 1&9A&=>KRRTUYWYUYZ[^\^_ddfmmnpnvnvwI111I[[))Z788;NNJ 		-ZK@FFHMMOVVWYW_W_`I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> 
++T[[-H-H1-LMN !"   kknnU+I "[
 "[
 "[s   .]8]4]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   rU   )r%   rs   )r!   shaper&   r(   float64floatreshapero   prodabsquantiler_   rD   clamprE   	unsqueezer{   )r|   r   r!   
batch_sizechannelsremaining_dims
abs_sampless           r   _threshold_sample#SASolverScheduler._threshold_sampleW  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   )rs   r   )	ro   rj   maximumnewaxiscumsumargmaxclipr   r   )r|   r   r   	log_sigmadistslow_idxhigh_idxlowhighwr   s              r   r   SASolverScheduler._sigma_to_ty  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   rS   )r_   rK   )r|   r   rh   ri   s       r   _sigma_to_alpha_sigma_t)SASolverScheduler._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_maxrX   r   g      @r   )hasattrr_   r   r   r   ro   r9   )
r|   r   rn   r   r   rhorampmin_inv_rhomax_inv_rhorl   s
             r   r   $SASolverScheduler._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   rX   r   )
r   r_   r   r   r   ro   r   r9   r   rj   )r|   r   rn   r   r   rl   s         r   r   )SASolverScheduler._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   rX   r   r   )r   r_   r   r   r   ro   r   r9   scipystatsr   ppf)
r|   r   rn   r   r   r   r   timestepr   rl   s
             r   r   "SASolverScheduler._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                   [        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	;   Ga  U R                  R                  S
:X  a0  U R                  R                  S;   a  USS2SS24   n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	$ U R                  R                  S;   Ga  U R                  R                  S
:X  a)  U R                  R                  S;   a  USS2SS24   n
OoUn
OlU R                  R                  S:X  a  X'U-  -
  U-  n
OGU R                  R                  S:X  a
  Xq-  X-  -   n
O#[        SU R                  R                   S35      eU R                  R                  (       aB  U R                  U   U R                  U   pX(U
-  -
  U-  n	U R                  U	5      n	X'U	-  -
  U-  n
U
$ g)a  
Convert the model output to the corresponding type the data_prediction/noise_prediction algorithm needs.
Noise_prediction is designed to discretize an integral of the noise prediction model, and data_prediction is
designed to discretize an integral of the data prediction model.

<Tip>

The algorithm and model type are decoupled. You can use either data_prediction or noise_prediction for both
noise prediction and data prediction models.

</Tip>

Args:
    model_output (`torch.Tensor`):
        The direct output from the learned diffusion model.
    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 argumentrr   1.0.0zPassing `timesteps` is deprecated and has no effect as model output conversion is now handled via an internal counter `self.step_index`)r7   r5   )learnedlearned_range   r   v_predictionflow_predictionzprediction_type given as zd must be one of `epsilon`, `sample`, `v_prediction`, or `flow_prediction` for the SASolverScheduler.)rW   zQ must be one of `epsilon`, `sample`, or `v_prediction` for the SASolverScheduler.)r   popr"   r   rl   r   r   r_   rF   rA   rN   rC   r   rh   ri   )r|   r   r   argskwargsr   r   rh   ri   x0_predr5   s              r   convert_model_output&SASolverScheduler.convert_model_output  s   : "$i!m47J1M>4y1}a !RSS Z DOO,77>;;%%)<<{{**i7;;,,0LL#/2A2#6L!l$::gE,,8&,,>!*W-CC,,0AA++doo6 \#99 /0K0K/L MV V 
 {{''009N [[''+??{{**i7;;,,0LL*1bqb51G*G,,8!l$::gE,,>!073CC /0K0K/L MA A 
 {{''#'<<#94<<;Q!g$55@009!g$55@N/ @r   c                    US;   d   S5       eUS:X  a3  [         R                  " U* 5      [         R                  " X2-
  5      S-
  -  $ US:X  a<  [         R                  " U* 5      US-   [         R                  " X2-
  5      -  US-   -
  -  $ US:X  aN  [         R                  " U* 5      US-  SU-  -   S-   [         R                  " X2-
  5      -  US-  SU-  -   S-   -
  -  $ US:X  a`  [         R                  " U* 5      US-  SUS-  -  -   SU-  -   S-   [         R                  " X2-
  5      -  US-  SUS-  -  -   SU-  -   S-   -
  -  $ g)	zT
Calculate the integral of exp(-x) * x^order dx from interval_start to interval_end
r   r   r   r   )order is only supported for 0, 1, 2 and 3r   r   r   r      Nr&   r   )r|   orderinterval_startinterval_ends       r   %get_coefficients_exponential_negative7SASolverScheduler.get_coefficients_exponential_negativeJ  sz    $Q&QQ$A:99l]+uyy9V/WZ[/[\\aZ99l]+!#uyy1N'OOS_bcScd  aZ99l]+"Q%77!;uyyIf?gg?Q%559;  aZ99l]+"Q):%::Q=OORSS))L9:;?Qq%881|;KKaOQ  r   c                    US;   d   S5       eSUS-  -   U-  nSUS-  -   U-  nUS:X  a<  [         R                  " U5      S[         R                  " XV-
  * 5      -
  -  SUS-  -   -  $ US:X  aH  [         R                  " U5      US-
  US-
  [         R                  " XV-
  * 5      -  -
  -  SUS-  -   S-  -  $ US:X  aZ  [         R                  " U5      US-  SU-  -
  S-   US-  SU-  -
  S-   [         R                  " XV-
  * 5      -  -
  -  SUS-  -   S-  -  $ US:X  al  [         R                  " U5      US-  SUS-  -  -
  SU-  -   S-
  US-  SUS-  -  -
  SU-  -   S-
  [         R                  " XV-
  * 5      -  -
  -  SUS-  -   S-  -  $ g	)
z\
Calculate the integral of exp(x(1+tau^2)) * x^order dx from interval_start to interval_end
r   r   r   r   r   r   r      Nr   )r|   r   r   r   tauinterval_end_covinterval_start_covs          r   %get_coefficients_exponential_positive7SASolverScheduler.get_coefficients_exponential_positiveb  s    $Q&QQ$ QJ,6#q&jN:A:		*+q599?O?d=e3f/fgklortuoukuv aZ		*+%))A-=M=b;c1dde
 QJ1$& aZ		*+%q(1/?+??!C)1,q3E/EEIii"2"G HIJJ QJ1$& aZ		*+%q(1/?/B+BBQIYEYY\]])1,q3Eq3H/HH1OaKaadeeii"2"G HIJJ QJ1$& r   c           	         US;   d   eU[        U5      S-
  :X  d   eUS:X  a  S//$ US:X  a@  SUS   US   -
  -  US   * US   US   -
  -  /SUS   US   -
  -  US   * US   US   -
  -  //$ US:X  a  US   US   -
  US   US   -
  -  nUS   US   -
  US   US   -
  -  nUS   US   -
  US   US   -
  -  nSU-  US   * US   -
  U-  US   US   -  U-  /SU-  US   * US   -
  U-  US   US   -  U-  /SU-  US   * US   -
  U-  US   US   -  U-  //$ US:X  Ga  US   US   -
  US   US   -
  -  US   US   -
  -  nUS   US   -
  US   US   -
  -  US   US   -
  -  nUS   US   -
  US   US   -
  -  US   US   -
  -  nUS   US   -
  US   US   -
  -  US   US   -
  -  nSU-  US   * US   -
  US   -
  U-  US   US   -  US   US   -  -   US   US   -  -   U-  US   * US   -  US   -  U-  /SU-  US   * US   -
  US   -
  U-  US   US   -  US   US   -  -   US   US   -  -   U-  US   * US   -  US   -  U-  /SU-  US   * US   -
  US   -
  U-  US   US   -  US   US   -  -   US   US   -  -   U-  US   * US   -  US   -  U-  /SU-  US   * US   -
  US   -
  U-  US   US   -  US   US   -  -   US   US   -  -   U-  US   * US   -  US   -  U-  //$ g)z2
Calculate the coefficient of lagrange polynomial
r   r   r   r   r   N)r   )r|   r   lambda_listdenominator1denominator2denominator3denominator4s          r   lagrange_polynomial_coefficient1SASolverScheduler.lagrange_polynomial_coefficient  sa   
 $$$K(1,,,,A:C5LaZ Q+a.89 ^O{1~A'FG
 Q+a.89 ^O{1~A'FG	 	 aZ'N[^;AQ\]^Q_@_`L'N[^;AQ\]^Q_@_`L'N[^;AQ\]^Q_@_`L $!!n_{1~5EN[^3lB $!!n_{1~5EN[^3lB $!!n_{1~5EN[^3lB " aZQ+a.0q>KN24q>KN24  Q+a.0q>KN24q>KN24  Q+a.0q>KN24q>KN24  Q+a.0q>KN24q>KN24  $!!n_{1~5AF,V#AQ7%a.;q>9:%a.;q>9: ## "!n_{1~5AF,V
 $!!n_{1~5AF,V#AQ7%a.;q>9:%a.;q>9: ## "!n_{1~5AF,V
 $!!n_{1~5AF,V#AQ7%a.;q>9:%a.;q>9: ## "!n_{1~5AF,V
 $!!n_{1~5AF,V#AQ7%a.;q>9:%a.;q>9: ## "!n_{1~5AF,V
E- -+ r   c           
         US;   d   eU[        U5      :X  d   S5       e/ nU R                  US-
  U5      n[        U5       H  nSn	[        U5       H]  n
U R                  (       a&  XU   U
   U R	                  US-
  U
-
  X#U5      -  -  n	M:  XU   U
   U R                  US-
  U
-
  X#5      -  -  n	M_     UR                  U	5        M     [        U5      U:X  d   S5       eU$ )N)r   r   r   r   z4the length of lambda list must be equal to the orderr   r   z3the length of coefficients does not match the order)r   r  r#   rv   r   r   r$   )r|   r   r   r   r  r   coefficientslagrange_coefficientr-   coefficientjs              r   get_coefficients_fn%SASolverScheduler.get_coefficients_fn  s
   $$$K((`*``(#CCEAI{[uAK5\??#:1#=@j@j	A~SA $ K  #:1#=@j@j	A~A $ K " ,  < E)`+``)r   noiser   r   c                
   [        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c   [        U5      S:  a  US   nO[        S5      eUc   [        U5      S:  a  US   nO[        S	5      eUc   [        U5      S
:  a  US
   nO[        S5      eUb  [        SSS5        U R                  n	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[        R                  " U5      nX-
  n/ n[        U5       Hq  nU R                  U-
  nU R                  U R
                  U   5      u  nn[        R                  " U5      [        R                  " U5      -
  nUR                  U5        Ms     U R                  XOUUU5      nUnU R                  (       GaT  US:X  GaM  U R
                  U R                  S-
     nU R                  U5      u  nn[        R                  " U5      [        R                  " U5      -
  nUS==   S[        R                  " SUS-  -   U-  5      -  US-  S-  USUS-  -   -  S-
  [        R                  " SUS-  -   U* -  5      -   SUS-  -   S-  -  -
  -  UU-
  -  -  ss'   US==   S[        R                  " SUS-  -   U-  5      -  US-  S-  USUS-  -   -  S-
  [        R                  " SUS-  -   U* -  5      -   SUS-  -   S-  -  -
  -  UU-
  -  -  ss'   [        U5       Hq  nU R                  (       a>  USUS-  -   U
-  [        R                  " US-  * U-  5      -  UU   -  U	US-   *    -  -  nMR  USUS-  -   * U-  UU   -  U	US-   *    -  -  nMs     U R                  (       a=  U
[        R                   " S[        R                  " SUS-  -  U-  5      -
  5      -  U-  nO8XZ-  [        R                   " [        R                  " SU-  5      S-
  5      -  U-  nU R                  (       a,  [        R                  " US-  * U-  5      X-  -  U-  U-   U-   nOX-  U-  U-   U-   nUR#                  UR$                  5      nU$ )a  
One step for the SA-Predictor.

Args:
    model_output (`torch.Tensor`):
        The direct output from the learned diffusion model at the current timestep.
    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.
    order (`int`):
        The order of SA-Predictor at this timestep.

Returns:
    `torch.Tensor`:
        The sample tensor at the previous timestep.
r   prev_timestepNr   r   r   z.missing `noise` as a required keyword argumentr   .missing `order` as a required keyword argumentr   ,missing `tau` as a required keyword argumentr   zPassing `prev_timestep` is deprecated and has no effect as model output conversion is now handled via an internal counter `self.step_index`r6   r   r   r"   r   ru   rl   r   r   r&   rj   
zeros_liker#   r$   r  rv   r   rg   r{   r!   ) r|   r   r   r  r   r   r   r   r  model_output_listri   sigma_s0rh   alpha_s0rk   	lambda_s0gradient_parthr  r-   sialpha_sisigma_si	lambda_sigradient_coefficientsx
temp_sigmatemp_alpha_stemp_sigma_stemp_lambda_s
noise_partx_ts                                    r   !stochastic_adams_bashforth_update3SASolverScheduler.stochastic_adams_bashforth_update  s!   6 $'t9q=QfjjRV6W>4y1}a !RSS=4y1}Q !QRR=4y1}Q !QRR;4y1}1g !OPP$ ^
 !..KK!+,KK(   77@!99(C99W%		'(::IIh'%))H*==	((0 uA1$B!%!=!=dkk"o!NHh		(+eii.AAIy)	  !% 8 88U`be f???
 "[[1)<=
-1-I-I*-U*l %		, 7%))L:Q Q%a(iiS!Vx 789!tax1CF
#3a#7%))QaZUVTVDW:X#X^_beghbh^hmn]n"ooq !=02( &a(iiS!Vx 789!tax1CF
#3a#7%))QaZUVTVDW:X#X^_beghbh^hmn]n"ooq !=02( uAaZii#q&	H 456 ,A./ (!a%1	2 1sAv:!8;PQR;S!SVgjknojohpVq!qq  ?? 5::a%))BaK!O2L.L#MMPUUJEIIa!e4Dq4H)IIEQJ??))c1fIM*g.@AAEUXbbC%*]:ZGCffQWWo
r   this_model_outputrx   
last_noisethis_samplec                	   [        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c   [        U5      S:  a  US   nO[        S5      eUc   [        U5      S:  a  US   nO[        S	5      eUc   [        U5      S
:  a  US
   nO[        S5      eUc   [        U5      S:  a  US   nO[        S5      eU	b  [        SSS5        U R                  n
U R
                  U R                     U R
                  U R                  S-
     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[        R                  " U5      nUU-
  n/ n[        U5       Hq  nU R                  U-
  nU R                  U R
                  U   5      u  nn[        R                  " U5      [        R                  " U5      -
  nUR                  U5        Ms     X/-   nU R                  UUUUU5      nUnU R                  (       a  US:X  a  US==   S[        R                  " SUS-  -   U-  5      -  US-  USUS-  -   -  S-
  [        R                  " SUS-  -   U* -  5      -   SUS-  -   S-  U-  -  -
  -  -  ss'   US==   S[        R                  " SUS-  -   U-  5      -  US-  USUS-  -   -  S-
  [        R                  " SUS-  -   U* -  5      -   SUS-  -   S-  U-  -  -
  -  -  ss'   [        U5       Hq  nU R                  (       a>  USUS-  -   U-  [        R                  " US-  * U-  5      -  UU   -  UUS-   *    -  -  nMR  USUS-  -   * U-  UU   -  UUS-   *    -  -  nMs     U R                  (       a=  U[        R                   " S[        R                  " SUS-  -  U-  5      -
  5      -  U-  nO8Xk-  [        R                   " [        R                  " SU-  5      S-
  5      -  U-  nU R                  (       a,  [        R                  " US-  * U-  5      X-  -  U-  U-   U-   nOX-  U-  U-   U-   nUR#                  UR$                  5      nU$ )a  
One step for the SA-Corrector.

Args:
    this_model_output (`torch.Tensor`):
        The model outputs at `x_t`.
    this_timestep (`int`):
        The current timestep `t`.
    last_sample (`torch.Tensor`):
        The generated sample before the last predictor `x_{t-1}`.
    this_sample (`torch.Tensor`):
        The generated sample after the last predictor `x_{t}`.
    order (`int`):
        The order of SA-Corrector at this step.

Returns:
    `torch.Tensor`:
        The corrected sample tensor at the current timestep.
r   this_timestepNr   z4missing `last_sample` as a required keyword argumentr   z3missing `last_noise` as a required keyword argumentr   z4missing `this_sample` as a required keyword argumentr   r     r  r   zPassing `this_timestep` is deprecated and has no effect as model output conversion is now handled via an internal counter `self.step_index`r6   r  r  )r|   r+  rx   r,  r-  r   r   r   r   r/  r  ri   r  rh   r  rk   r  r  r  r  r-   r  r  r  r   model_prev_listr!  r"  r'  r(  s                                 r   stochastic_adams_moulton_update1SASolverScheduler.stochastic_adams_moulton_update  s   > $'t9q=QfjjRV6W4y1}"1g !WXX4y1}!!W
 !VWW4y1}"1g !WXX=4y1}Q !QRR;4y1}1g !OPP$ ^ !..KK(KK!+,   77@!99(C99W%		'(::IIh'%))H*==	((5y uA1$B!%!=!=dkk"o!NHh		(+eii.AAIy)	  ,.AA $ 8 8	8U`be f??
 &a(iiS!Vx 7891uQaZ 01 4uyy!c1f*RSQSAT7U U[\_bde_e[ejkZknoZoppr(
 &a(iiS!Vx 7891uQaZ 01 4uyy!c1f*RSQSAT7U U[\_bde_e[ejkZknoZoppr( uAaZii#q&	H 456 ,A./ &Ah/	0 1sAv:!8;PQR;S!SVehilmhmfnVo!oo  ?? 5::a%))BaK!O2L.L#MMPZZJEIIa!e4Dq4H)IIJVJ??))c1fIM*g.@AAEUXbbC%*]:ZGCffQWWo
r   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   )rr   nonzeror   r   )r|   r   schedule_timestepsindex_candidatesr   s        r   index_for_timestep$SASolverScheduler.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&   Tensorr{   rr   r   r8  ry   rz   )r|   r   s     r   _init_step_index"SASolverScheduler._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                  S:  =(       a    U R                  SLnU R                  XS9nU(       aP  U R                  U R                  S   5      nU R                  UU R                  U R                  UU R                  US9n[        [        U R                  R                  U R                  R                  S-
  5      S-
  5       HA  n	U R                   U	S-      U R                   U	'   U R                  U	S-      U R                  U	'   MC     XpR                   S'   X R                  S'   [#        UR$                  UUR&                  UR(                  S9n
U R                  R*                  (       a  [-        U R                  R                  [/        U R0                  5      U R                  -
  5      n[-        U R                  R                  [/        U R0                  5      U R                  -
  S-   5      nO,U R                  R                  nU R                  R                  n[-        XR2                  S-   5      U l        [-        XR2                  S	-   5      U l
        U R4                  S:  d   eU R                  S:  d   eX0l        Xl	        U R                  U R                  S   5      nU R7                  UUU
U R4                  US
9nU R2                  [        U R                  R                  U R                  R                  S-
  5      :  a  U =R2                  S-  sl        U =R8                  S-  sl        U(       d  U4$ [;        US9$ )ae  
Predict the sample from the previous timestep by reversing the SDE. This function propagates the sample with
the SA-Solver.

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.
    generator (`torch.Generator`, *optional*):
        A random number generator.
    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.

NzaNumber of inference steps is 'None', you need to run 'set_timesteps' after creating the schedulerr   r   rX   )r+  rx   r,  r-  r   r   r   )	generatorr   r!   r   )r   r   r  r   r   )prev_sample)rn   r"   r   r=  rx   r   rB   rt   r2  r,  this_corrector_orderr#   rs   r_   r?   r@   ru   r   r   r   r!   rG   r%   r   rr   rw   this_predictor_orderr)  ry   r   )r|   r   r   r   rA  r?  use_correctormodel_output_convertcurrent_taur-   r  rD  rC  rB  s                 r   stepSASolverScheduler.step4  s   < ##+s  ??"!!(+!+L0@0@0L#888U--(:(:2(>?K99"6 ,,??"// : F s4;;668S8SVW8WX[\\]A$($6$6q1u$=Dq!$($6$6q1u$=Dq! ^ "62!)2&&$$	
 ;;((#&t{{'B'BCDWZ^ZiZiDi#j #&t{{'B'BCDWZ^ZiZiDilmDm#n #';;#>#> #';;#>#> $'(<>S>SVW>W$X!$'(<>S>SVW>W$X!((1,,,((1,,,!mmD$6$6r$:;<<-++ = 
   3t{{'B'BDKKD_D_bcDc#dd!!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[   )r|   r   r   r   s       r   scale_model_input#SASolverScheduler.scale_model_input  s	     r   original_samplesrr   c                    U R                   R                  UR                  S9U l         U R                   R                  UR                  S9nUR                  UR                  5      nXC   S-  nUR	                  5       n[        UR                  5      [        UR                  5      :  a?  UR                  S5      n[        UR                  5      [        UR                  5      :  a  M?  SXC   -
  S-  nUR	                  5       n[        UR                  5      [        UR                  5      :  a?  UR                  S5      n[        UR                  5      [        UR                  5      :  a  M?  XQ-  Xb-  -   nU$ )N)r   r    rS   rX   r   )rf   r{   r   r!   flattenr   r   r   )r|   rM  r  rr   rf   sqrt_alpha_prodsqrt_one_minus_alpha_prodnoisy_sampless           r   	add_noiseSASolverScheduler.add_noise  sW    #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 (:=V=^^r   c                 .    U R                   R                  $ N)r_   r:   r   s    r   __len__SASolverScheduler.__len__  s    {{...r   )rz   ry   rh   rd   rf   r,   rm   rk   r,  rx   rw   ru   rn   rv   ri   rl   rB   rC  rD  rt   rr   )r   )NN)333333?rY  rV  )NT)4__name__
__module____qualname____firstlineno____doc__r   name_compatiblesr   r
   r   intstrr   r   ro   ndarrayr   r   boolr}   propertyr   r   r   r&   r   r   r<  r   r   r   r   r   r   r   r   r   r  r  r)  r2  r8  r=  r   r   rH  rK  	IntTensorrS  rW  __static_attributes__).0es   00r   r2   r2   O   s   AF %>>$=qFF$=>LE $("%BF  ('+",1"%/"&,116*/*/&)%*5\M'+ *1S, S, S, 	S,
 S,  bjj$u+&= >?S, S, S, S, 8$S, S, %*S,  S, S,  S,  $D>!S," !)#S,$ "$%S,& "$'S,( UO)S,* "+S,,  }-S,. /S,0 1S, S,j     ! !(3 (O, O,U3PUP\P\K\E] O,d  D0 ELL RWR^R^ 4 TW \a\h\h . dg<?HM[`	F  $	]ll] 	] 
]~0*XkZ(}ll} 	}
 ||} } \\} 
}~C <<C \\	C
 LLC \\C C \\C 
CL(
1"  d8lld8 d8 	d8 d8 
%	&d8L %,,  ,, || ??	
 
4/c! ?s   J:r2   )g+?r   )r   typingr   r   r   r   r   r   ro   r&   configuration_utilsr	   r
   utilsr   r   utils.torch_utilsr   scheduling_utilsr   r   r   scipy.statsr   r0   r2   r[   r   r   <module>rp     sQ   $  9 9   A 1 , X X  !)4Xv/ v/r   