
    wi͇                         d dl Z d dlmZmZmZmZ d dlZd dlZddl	m
Z
mZ ddlmZ ddlmZmZmZ 	 	 dd
Z G d dee
          ZdS )    N)ListOptionalTupleUnion   )ConfigMixinregister_to_config)	deprecate   )KarrasDiffusionSchedulersSchedulerMixinSchedulerOutput+?cosinec           
      F   |dk    rd }n|dk    rd }nt          d|           g }t          |           D ]J}|| z  }|dz   | z  }|                    t          d ||           ||          z  z
  |                     Kt	          j        |t          j                  S )a  
    Create a beta schedule that discretizes the given alpha_t_bar function, which defines the cumulative product of
    (1-beta) over time from t = [0,1].

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


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

    Returns:
        betas (`np.ndarray`): the betas used by the scheduler to step the model outputs
    r   c                 \    t          j        | dz   dz  t           j        z  dz            dz  S )NgMb?gT㥛 ?r   )mathcospits    ~/root/.openclaw/workspace/chatterbox_venv_py311/lib/python3.11/site-packages/diffusers/schedulers/scheduling_deis_multistep.pyalpha_bar_fnz)betas_for_alpha_bar.<locals>.alpha_bar_fn7   s,    8QY%/$'9A=>>!CC    expc                 0    t          j        | dz            S )Ng      ()r   r   r   s    r   r   z)betas_for_alpha_bar.<locals>.alpha_bar_fn<   s    8A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 	D 	D 	D 
	&	&	' 	' 	' 	' T>RTTUUUE*++ M M((!e..S\\"--R0@0@@@(KKLLLL<U]3333r   c            "       8   e Zd ZdZd eD             ZdZe	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 dDdede	de	de
deej                 dede
dede	de	de
de
ded ee         d!e
d"ef d#            Zed$             Zed%             ZdEd&efd'ZdFd(ed)ee
ej        f         fd*Zd+ej        d,ej        fd-Zd. Zd/ Zd0ej        d,ej        fd1Zdd2d3ej        d+ej        d,ej        fd4Zdd2d3ej        d+ej        d,ej        fd5Zdd2d6eej                 d+ej        d,ej        fd7Z dd2d6eej                 d+ej        d,ej        fd8Z!dFd9Z"d: Z#	 dGd3ej        d;ed+ej        d<ed,ee$e%f         f
d=Z&d+ej        d,ej        fd>Z'd?ej        d@ej        dAej(        d,ej        fdBZ)dC Z*dS )HDEISMultistepScheduleru  
    `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}.
        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.
    c                     g | ]	}|j         
S  )name).0es     r   
<listcomp>z!DEISMultistepScheduler.<listcomp>y   s    >>>qAF>>>r   r     -C6?{Gz?linearNr   epsilonFףp=
?      ?deislogrhoTlinspacer   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timestep_spacingsteps_offsetc                 6   |&t          j        |t           j                  | _        n|dk    r(t          j        |||t           j                  | _        nk|dk    r1t          j        |dz  |dz  |t           j                  dz  | _        n4|dk    rt          |          | _        nt          | d| j                   d| j        z
  | _        t          j	        | j        d	
          | _
        t          j        | j
                  | _        t          j        d| j
        z
            | _        t          j        | j                  t          j        | j                  z
  | _        d| j
        z
  | j
        z  dz  | _        d| _        |dvr4|dv r|                     d           nt          | d| j                   |dvr5|dv r|                     d           nt          d| d| j                   d | _        t)          j        d	|dz
  |t(          j                  d d d                                         }t          j        |          | _        d g|z  | _        d	| _        d | _        d | _        | j                            d          | _        d S )Nr   r9   scaled_linear      ?r   squaredcos_cap_v2z is not implemented for r<   r   dimr   )r=   )	dpmsolverzdpmsolver++r=   )rJ   )r>   )midpointheunbh1bh2r>   )rK   zsolver type cpu)r#   r$   r%   r)   r?   r-   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)selfr@   rA   rB   rC   rD   rE   rF   rG   rH   rI   rJ   rK   rL   rM   rN   rO   rm   s                     r   __init__zDEISMultistepScheduler.__init__|   s   ( $m5=IIIDJJh&&
H>QY^YfgggDJJo--
C3H[chcpqqquvvDJJ111,-@AADJJ%&`&`PTP^&`&`aaaDJ&#mDKQ???z$"566z!d&9"9::	$,//%)DL2I2IID//43FF3N !$ ))!===''v'>>>>)^*e*eUYUc*e*efffj((@@@''H'====)*n*n*n^b^l*n*nooo $( K#6#:<OWYWabbbcgcgegcghmmoo	))44"Vl2 ! knnU++r   c                     | j         S )zg
        The index counter for current timestep. It will increase 1 after each scheduler step.
        )rp   rs   s    r   
step_indexz!DEISMultistepScheduler.step_index   s    
 r   c                     | j         S )zq
        The index for the first timestep. It should be set from pipeline with `set_begin_index` method.
        rq   rv   s    r   begin_indexz"DEISMultistepScheduler.begin_index   s    
   r   rz   c                     || _         dS )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.
        Nry   )rs   rz   s     r   set_begin_indexz&DEISMultistepScheduler.set_begin_index   s     (r   ri   devicec           	           j         j        dk    rzt          j        d j         j        dz
  |dz                                             ddd         dd                                                             t          j                  }nB j         j        dk    r j         j        |dz   z  }t          j	        d|dz             |z                                  ddd         dd                                                             t          j                  }| j         j
        z  }n j         j        dk    rw j         j        |z  }t          j	         j         j        d|                                                                                               t          j                  }|dz  }nt           j         j         d          t          j        d j        z
   j        z  d	z            } j         j        rt          j        |          t          j        |                                          }                     ||
          }t          j         fd|D                                                       }t          j        ||dd         g                              t          j                  }nt          j        |t          j	        dt+          |                    |          }d j        d         z
   j        d         z  d	z  }t          j        ||gg                              t          j                  }t-          j        |           _        t-          j        |                              |t,          j                   _        t+          |           _        dg j         j        z   _        d _        d _        d _          j                            d           _        dS )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.
        r?   r   r   Nr[   leadingtrailingzY is not supported. Please make sure to choose one of 'linspace', 'leading' or 'trailing'.rR   )	in_sigmasri   c                 <    g | ]}                     |          S r1   )_sigma_to_t)r3   sigma
log_sigmasrs   s     r   r5   z8DEISMultistepScheduler.set_timesteps.<locals>.<listcomp>   s)    !Z!Z!Z%$"2"25*"E"E!Z!Z!Zr   r}   r   r\   )!configrN   rj   r?   r@   roundrk   astypeint64arangerO   r   arrayra   rM   re   flip_convert_to_karrasconcatenater%   interplenr#   rl   rg   rr   rm   ri   rE   rn   ro   rp   rq   )rs   ri   r}   rm   
step_ratiorg   
sigma_lastr   s   `      @r   set_timestepsz$DEISMultistepScheduler.set_timesteps   s    ;':55At{>BDWZ[D[\\2"s$!!	 I [)Y668=PST=TUJ 1&9A&=>>KRRTTUYUYWYUYZ[^\^[^_ddffmmnpnvwwI11II[)Z778;NNJ 	$+"A1zkRRXXZZ__aahhikiqrrINII;/  K  K  K   A 33t7JJsRSS;( 		OJWV__))++F,,vSf,ggF!Z!Z!Z!Z!ZSY!Z!Z!Z[[aaccI^VVBCC[$9::AA"*MMFFYy")As6{{*C*CVLLFt21559LQ9OOTWWJ^Vj\$:;;BB2:NNF&v..))4477vU[7YY#&y>>  
K$% !"   knnU++r   samplereturnc                 ,   |j         }|j        ^}}}|t          j        t          j        fvr|                                }|                    ||t          j        |          z            }|	                                }t          j
        || j        j        d          }t          j        |d| j        j                  }|                    d          }t          j        || |          |z  } |j        ||g|R  }|                    |          }|S )as  
        "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://arxiv.org/abs/2205.11487
        r   rT   )r"   max)r   shaper#   r%   float64floatreshaperj   prodabsquantiler   rH   clamprI   	unsqueezerr   )rs   r   r   
batch_sizechannelsremaining_dims
abs_sampless           r   _threshold_samplez(DEISMultistepScheduler._threshold_sample  s    06-
H~666\\^^F 
Hrw~7N7N,NOOZZ\\
N:t{'MSTUUUK1$+6
 
 
 KKNNVaR++a/
HF~FFF5!!r   c                    t          j        t          j        |d                    }||d d t           j        f         z
  }t          j        |dk    d                              d                              |j        d         dz
            }|dz   }||         }||         }||z
  ||z
  z  }	t          j        |	dd          }	d|	z
  |z  |	|z  z   }
|
                    |j                  }
|
S )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   z"DEISMultistepScheduler._sigma_to_t9  s    F2:eU3344	 Jqqq"*}55 )UaZq11188a8@@EE*JZ[\J]`aJaEbbQ;!(# 9_t,GAq! UgH,IIek""r   c                 0    d|dz  dz   dz  z  }||z  }||fS )Nr   r   rR   r1   )rs   r   rc   rd   s       r   _sigma_to_alpha_sigma_tz.DEISMultistepScheduler._sigma_to_alpha_sigma_tQ  s-    q1,-'/r   r   c                 z   t          | j        d          r| j        j        }nd}t          | j        d          r| j        j        }nd}||n|d                                         }||n|d                                         }d}t          j        dd|          }|d|z  z  }|d|z  z  }||||z
  z  z   |z  }	|	S )z6Constructs the noise schedule of Karras et al. (2022).	sigma_minN	sigma_maxr[   r   g      @r   )hasattrr   r   r   itemrj   r?   )
rs   r   ri   r   r   rhorampmin_inv_rhomax_inv_rhorg   s
             r   r   z)DEISMultistepScheduler._convert_to_karrasX  s    
 4;,, 	-III4;,, 	-III!*!6IIIbM<N<N<P<P	!*!6IIIaL<M<M<O<O	{1a!455AG,AG,k(A BBsJr   r   model_outputc                   t          |          dk    r|d         n|                    dd          }|+t          |          dk    r	|d         }nt          d          |t          ddd           | j        | j                 }|                     |          \  }}| j        j        d	k    r|||z  z
  |z  }	nL| j        j        d
k    r|}	n9| j        j        dk    r||z  ||z  z
  }	nt          d| j        j         d          | j        j	        r| 
                    |	          }	| j        j        dk    r|||	z  z
  |z  S t          d          )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   timestepNr   z/missing `sample` as a required keyward 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`r:   r   v_predictionzprediction_type given as zV must be one of `epsilon`, `sample`, or `v_prediction` for the DEISMultistepScheduler.r=   'only support log-rho multistep deis now)r   popr   r
   rg   rw   r   r   rF   rG   r   rJ   r]   )
rs   r   r   argskwargsr   r   rc   rd   x0_preds
             r   convert_model_outputz+DEISMultistepScheduler.convert_model_outputq  s   , "$ii!mm477J1M1M>4yy1}}a !RSSS Z   DO,77>>;&)33, 66'AGG[(H44"GG[(N::&<)??GGBDK,G B B B  
 ;# 	6,,W55G;%//Ww..'99%&OPPPr   c                X   t          |          dk    r|d         n|                    dd          }t          |          dk    r|d         n|                    dd          }|+t          |          dk    r	|d         }nt          d          |t          dd	d
           |t          dd	d           | j        | j        dz            | j        | j                 }}|                     |          \  }	}|                     |          \  }
}t          j        |	          t          j        |          z
  }t          j        |
          t          j        |          z
  }||z
  }| j	        j
        dk    r'|	|
z  |z  |t          j        |          dz
  z  |z  z
  }nt          d          |S )au  
        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   0 missing `sample` as a required keyward argumentrm   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`r=   r<   r   )r   r   r   r
   rg   rw   r   r#   re   r   rJ   r   r]   )rs   r   r   r   r   r   r   rd   sigma_src   alpha_srf   lambda_shx_ts                  r   deis_first_order_updatez.DEISMultistepScheduler.deis_first_order_update  s   0 "$ii!mm477J1M1M#&t99q==QfjjRV6W6W>4yy1}}a !STTT Z   $ ^    ;t':;T[=Y77@@77@@9W%%	'(:(::9W%%	'(:(::x;%//W$.'UYq\\C=O2PT`1``CC%&OPPP
r   model_output_listc                   t          |          dk    r|d         n|                    dd          }t          |          dk    r|d         n|                    dd          }|+t          |          dk    r	|d         }nt          d          |t          ddd	           |t          ddd
           | j        | j        dz            | j        | j                 | j        | j        dz
           }	}}|                     |          \  }
}|                     |          \  }}|                     |	          \  }}	|d         |d         }}||
z  ||z  |	|z  }}}| j        j        dk    rOd } ||||           ||||          z
  } ||||           ||||          z
  }|
||z  ||z  z   ||z  z   z  }|S t          d          )a  
        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   r[   r=   c                     | t          j        |           t          j        |           z   dz
  z  t          j        |          t          j        |          z
  z  S )Nr   rj   re   )r   bcs      r   ind_fnzIDEISMultistepScheduler.multistep_deis_second_order_update.<locals>.ind_fn  sC    RVAYYJ2Q6726!99rvayy;PQQr   r   
r   r   r   r
   rg   rw   r   r   rJ   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_updatez9DEISMultistepScheduler.multistep_deis_second_order_update  s)   ( $'t99q==QfjjRV6W6W#&t99q==QfjjRV6W6W>4yy1}}a !STTT$ ^   $ ^   K!+,K(K!+, $  77@@!99(CC(!99(CC("2&(9"(=B '' 18h3FS[H[vv;%//R R R F5&&11FF6664R4RREF5&&11FF6664R4RREVh.;ebjHICJ%&OPPPr   c                \   t          |          dk    r|d         n|                    dd          }t          |          dk    r|d         n|                    dd          }|+t          |          dk    r	|d         }nt          d          |t          ddd	           |t          ddd
           | j        | j        dz            | j        | j                 | j        | j        dz
           | j        | j        dz
           f\  }}}	}
|                     |          \  }}|                     |          \  }}|                     |	          \  }}	|                     |
          \  }}
|d         |d         |d         }}}||z  ||z  |	|z  |
|z  f\  }}}}| j        j        dk    rvd } |||||           |||||          z
  } |||||           |||||          z
  } |||||           |||||          z
  }|||z  ||z  z   ||z  z   ||z  z   z  }|S t          d          )a  
        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   z/ missing`sample` as a required keyward argumentr   r   r   r[   r   r=   c                    | t          j        |          t          j        |          t          j        |           z
  dz   z  t          j        |          t          j        |           z  z
  t          j        |          z   t          j        |           dz  z   dt          j        |           z  z
  dz   z  }t          j        |          t          j        |          z
  t          j        |          t          j        |          z
  z  }||z  S )Nr   r   r   )r   r   r   d	numeratordenominators         r   r   zHDEISMultistepScheduler.multistep_deis_third_order_update.<locals>.ind_fnj  s    F1IIRVAYY!6!:;fQii"&))+,fQii  fQii1n% "&))m	$
 	  "vayy26!994RVAYY9N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_updatez8DEISMultistepScheduler.multistep_deis_third_order_update)  s   * $'t99q==QfjjRV6W6W#&t99q==QfjjRV6W6W>4yy1}}a !RSSS$ ^   $ ^   K!+,K(K!+,K!+,	1
-8X  77@@!99(CC(!99(CC(!99(CC(&r*,=b,ACTUWCXB gxxx	)
%vvv ;%/// / / F5&&&99FF66SY[a<b<bbEF5&&&99FF66SY[a<b<bbEF5&&&99FF66SY[a<b<bbEVh.;ebjH5SU:UVCJ%&OPPPr   c                 .   || j         }||k                                    }t          |          dk    rt          | j                   dz
  }nHt          |          dk    r|d                                         }n|d                                         }|S )Nr   r   )rm   nonzeror   r   )rs   r   schedule_timestepsindex_candidatesrw   s        r   index_for_timestepz)DEISMultistepScheduler.index_for_timestep  s    %!%.(:CCEE  A%%T^,,q0JJ
 !""Q&&)!,1133JJ)!,1133Jr   c                     | j         Ut          |t          j                  r|                    | j        j                  }|                     |          | _        dS | j	        | _        dS )zF
        Initialize the step_index counter for the scheduler.
        N)
rz   
isinstancer#   Tensorrr   rm   r}   r   rp   rq   )rs   r   s     r   _init_step_indexz'DEISMultistepScheduler._init_step_index  sd    
 #(EL11 >#;;t~'<==#66x@@D#0Dr   r   return_dictc                    | j         t          d          | j        |                     |           | j        t	          | j                  dz
  k    o#| j        j        ot	          | j                  dk     }| j        t	          | j                  dz
  k    o#| j        j        ot	          | j                  dk     }|                     ||          }t          | j        j
        dz
            D ]}| j        |dz            | j        |<   || j        d<   | j        j
        dk    s| j        dk     s|r|                     ||          }nV| j        j
        dk    s| j        dk     s|r|                     | j        |          }n|                     | j        |          }| j        | j        j
        k     r| xj        dz  c_        | xj        dz  c_        |s|fS t#          |          S )	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 (`float`):
                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.

        NzaNumber of inference steps is 'None', you need to run 'set_timesteps' after creating the schedulerr      r   r   r[   )prev_sample)ri   r   rw   r  r   rm   r   rL   r   r    rE   rn   ro   r   r   r   rp   r   )	rs   r   r   r   r  rL   lower_order_secondr*   r  s	            r   stepzDEISMultistepScheduler.step  s    6 #+s   ?"!!(+++ _DN 3 3a 77wT[=Zw_bcgcq_r_ruw_w 	 _DN 3 3a 77wT[=Zw_bcgcq_r_ruw_w 	 00f0MMt{/!344 	> 	>A$($6q1u$=Dq!!!-2;#q((D,AA,E,EIZ,E66|F6SSKK[%**d.Ca.G.GK].GAA$BT]cAddKK@@AS\b@ccK 4;#;;;!!Q&!! 	A 	">!;7777r   c                     |S )a?  
        Ensures interchangeability with schedulers that need to scale the denoising model input depending on the
        current timestep.

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

        Returns:
            `torch.Tensor`:
                A scaled input sample.
        r1   )rs   r   r   r   s       r   scale_model_inputz(DEISMultistepScheduler.scale_model_input  s	     r   original_samplesnoiserm   c                    
  j                             |j        |j                  }|j        j        dk    rft          j        |          rR j                            |j        t
          j                  
|                    |j        t
          j                  }n9 j                            |j                  
|                    |j                  } j	        
 fd|D             }n4 j
         j
        g|j        d         z  }n j	        g|j        d         z  }||                                         }t          |j                  t          |j                  k     r?|                    d          }t          |j                  t          |j                  k     ?                     |          \  }}||z  ||z  z   }	|	S )Nr   mpsr   c                 <    g | ]}                     |          S r1   )r   )r3   r   r   rs   s     r   r5   z4DEISMultistepScheduler.add_noise.<locals>.<listcomp>  s*    ^^^qD33A7IJJ^^^r   r   r[   )rg   rr   r}   r   typer#   is_floating_pointrm   r%   rz   rw   r   flattenr   r   r   )rs   r  r  rm   rg   step_indicesr   rc   rd   noisy_samplesr   s   `         @r   	add_noisez DEISMultistepScheduler.add_noise  s    '7'>FVF\]]"'500U5LY5W5W0!%!2!23C3JRWR_!2!`!`!%5%<EMRRII!%!2!23C3J!K!K!%5%<==I #^^^^^T]^^^LL_( O,yq/AALL !,-	0BBL|$,,..%+%5%;!<!<<<OOB''E %+%5%;!<!<<<  77>>"22Wu_Dr   c                     | j         j        S N)r   r@   rv   s    r   __len__zDEISMultistepScheduler.__len__  s    {..r   )r6   r7   r8   r9   Nr   r:   Fr;   r<   r=   r>   TFr?   r   )r   r  )T)+__name__
__module____qualname____doc__r   _compatiblesorderr	   intr   strr   rj   ndarrayboolrt   propertyrw   rz   r|   r   r#   r}   r   r  r   r   r   r   r   r   r   r   r   r   r  r   r   r	  r  	IntTensorr  r  r1   r   r   r/   r/   J   s       , ,\ ?>$=>>>LE $("%.2(",1"%$#"&,1 *#@, @, @, @, 	@,
 @,  
+@, @, @, @, %*@,  @, @, @,  @, $D>@,  !@," #@, @, @, @,D     X  ! ! X!( (3 ( ( ( (<, <, <,eCDU>V <, <, <, <,~     D  0     EL RWR^    :  $	7Q 7Q 7Ql7Q 	7Q 
7Q 7Q 7Q 7Qz  $	8 8 8l8 	8 
8 8 8 8|  $	CQ CQ CQ-CQ 	CQ 
CQ CQ CQ CQR  $	VQ VQ VQ-VQ 	VQ 
VQ VQ VQ VQr   (
1 
1 
1" !?8 ?8l?8 ?8 	?8
 ?8 
%	&?8 ?8 ?8 ?8B %,      ,  |  ?	 
 
       D/ / / / /r   r/   )r   r   )r   typingr   r   r   r   numpyrj   r#   configuration_utilsr   r	   utilsr
   scheduling_utilsr   r   r   r-   r/   r1   r   r   <module>r+     s   $  / / / / / / / / / / / /      A A A A A A A A       X X X X X X X X X X !)4 )4 )4 )4XL/ L/ L/ L/ L/^[ L/ L/ L/ L/ L/r   