
    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mZ ddlmZmZmZ  ej        e          Z	 	 dd
Z G d dee
          ZdS )    N)ListOptionalTupleUnion   )ConfigMixinregister_to_config)	deprecatelogging   )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_dpmsolver_singlestep.pyalpha_bar_fnz)betas_for_alpha_bar.<locals>.alpha_bar_fn9   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            %          e Zd ZdZd eD             ZdZedddddd	d
dddddddd ed           dfd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e
         d!ed"ee
         f"d#            Zd$e	d%ee	         fd&Zed'             Zed(             ZdJd*e	fd+Z	 	 	 dKd$e	d,ee
ej        f         d-eee	                  fd.Zd/ej        d%ej        fd0Zd1 Zd2 Zd3ej        d%ej        fd4Zdd5d6ej        d/ej        d%ej        fd7Zdd5d6ej        d/ej        d%ej        fd8Z dd5d9eej                 d/ej        d%ej        fd:Z!dd5d9eej                 d/ej        d%ej        fd;Z"ddd<d9eej                 d/ej        d=e	d%ej        fd>Z#dLd?Z$d@ Z%	 dMd6ej        dBe	d/ej        dCed%ee&e'f         f
dDZ(d/ej        d%ej        fdEZ)dFej        dGej        d-ej*        d%ej        fdHZ+dI Z,dS )NDPMSolverSinglestepScheduleru  
    `DPMSolverSinglestepScheduler` is a fast dedicated high-order solver for diffusion 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 DPMSolver 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`, *optional*):
            Prediction type of the scheduler function; can be `epsilon` (predicts the noise of the diffusion process),
            `sample` (directly predicts the noisy sample`) or `v_prediction` (see section 2.4 of [Imagen
            Video](https://imagen.research.google/video/paper.pdf) paper).
        thresholding (`bool`, defaults to `False`):
            Whether to use the "dynamic thresholding" method. This is unsuitable for latent-space diffusion models such
            as Stable Diffusion.
        dynamic_thresholding_ratio (`float`, defaults to 0.995):
            The ratio for the dynamic thresholding method. Valid only when `thresholding=True`.
        sample_max_value (`float`, defaults to 1.0):
            The threshold value for dynamic thresholding. Valid only when `thresholding=True` and
            `algorithm_type="dpmsolver++"`.
        algorithm_type (`str`, defaults to `dpmsolver++`):
            Algorithm type for the solver; can be `dpmsolver` or `dpmsolver++`. The `dpmsolver` type implements the
            algorithms in the [DPMSolver](https://huggingface.co/papers/2206.00927) paper, and the `dpmsolver++` type
            implements the algorithms in the [DPMSolver++](https://huggingface.co/papers/2211.01095) paper. It is
            recommended to use `dpmsolver++` or `sde-dpmsolver++` with `solver_order=2` for guided sampling like in
            Stable Diffusion.
        solver_type (`str`, defaults to `midpoint`):
            Solver type for the second-order solver; can be `midpoint` or `heun`. The solver type slightly affects the
            sample quality, especially for a small number of steps. It is recommended to use `midpoint` solvers.
        lower_order_final (`bool`, defaults to `True`):
            Whether to use lower-order solvers in the final steps. Only valid for < 15 inference steps. This can
            stabilize the sampling of DPMSolver for steps < 15, especially for steps <= 10.
        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}.
        final_sigmas_type (`str`, *optional*, defaults to `"zero"`):
            The final `sigma` value for the noise schedule during the sampling process. If `"sigma_min"`, the final
            sigma is the same as the last sigma in the training schedule. If `zero`, the final sigma is set to 0.
        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.
    c                     g | ]	}|j         
S  )name).0es     r   
<listcomp>z'DPMSolverSinglestepScheduler.<listcomp>   s    >>>qAF>>>r   r   i  g-C6?g{Gz?linearNr   epsilonFgףp=
?      ?dpmsolver++midpointzeroinf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final_sigmas_typelambda_min_clippedvariance_typec                    |dk    rd}t          dd|           |&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r6|dk    r|                     d           nt          | d| j                   |dvr4|dv r|                     d           nt          | d| j                   |dk    r|dk    rt)          d| d| d          d | _        t-          j        d|dz
  |t,          j                  d d d                                         }t          j        |          | _        d g|z  | _        d | _        |                     |          | _        d | _        d | _        | j                             d          | _        d S )N	dpmsolverzalgorithm_type `dpmsolver` is deprecated and will be removed in a future version. Choose from `dpmsolver++` or `sde-dpmsolver++` insteadzalgorithm_types=dpmsolver1.0.0r   r7   scaled_linear      ?r   squaredcos_cap_v2z is not implemented for r9   r   dimr   )rP   r:   deisr:   )rH   )r;   heun)logrhobh1bh2r;   )rI   r<   z`final_sigmas_type` z' is not supported for `algorithm_type` z%. Please chooose `sigma_min` instead.cpu)!r
   r$   r%   r&   r*   linspacer.   NotImplementedError	__class__alphascumprodalphas_cumprodsqrtalpha_tsigma_tloglambda_tsigmasinit_noise_sigmar	   r    num_inference_stepsnpcopy
from_numpy	timestepsmodel_outputssampleget_order_list
order_list_step_index_begin_indexto)selfr>   r?   r@   rA   rB   rC   rD   rE   rF   rG   rH   rI   rJ   rK   rL   rM   rN   deprecation_messagero   s                       r   __init__z%DPMSolverSinglestepScheduler.__init__   s4   * [(( #m17<OPPP$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 !$ !===''''}'EEEE)^*e*eUYUc*e*efff222666''J'????)[*b*bRVR`*b*bccc]**/@F/J/J W'8  W  Wao  W  W  W  
 $( K#6#:<OWYWabbbcgcgegcghmmoo	))44"Vl2--.ABB knnU++r   rk   returnc                    |}| j         j        }|dk    rt          d          | j         j        r|dk    rH|dz  dk    rg d|dz  dz
  z  ddgz   dgz   }n|dz  dk    rg d|dz  z  dgz   }n|g d|dz  z  ddgz   }nl|dk    r+|dz  dk    rddg|dz  dz
  z  ddgz   }nJddg|dz  z  dgz   }n;|dk    rdg|z  }n.|dk    rg d|dz  z  }n|dk    rddg|dz  z  }n|dk    rdg|z  }|S )z
        Computes the solver order at each time step.

        Args:
            num_inference_steps (`int`):
                The number of diffusion steps used when generating samples with a pre-trained model.
           z,Order > 3 is not supported by this schedulerr   )r   r   r|   r   r   )configrC   r    rJ   )rw   rk   stepsorderorderss        r   rr   z+DPMSolverSinglestepScheduler.get_order_list   su    $(199KLLL;( 	%zz19>>&YY%1*q.9QFBaSHFFQY!^^&YY%1*5;FF&YY%1*5A>FF!19>>VuzA~6!Q?FFVuz2aS8FF!uzz"eqj1!Q5A:.!ur   c                     | j         S )zg
        The index counter for current timestep. It will increase 1 after each scheduler step.
        )rt   rw   s    r   
step_indexz'DPMSolverSinglestepScheduler.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.
        ru   r   s    r   begin_indexz(DPMSolverSinglestepScheduler.begin_index  s    
   r   r   r   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.
        Nr   )rw   r   s     r   set_begin_indexz,DPMSolverSinglestepScheduler.set_begin_index  s     (r   devicero   c           	      Z    ||t          d          ||t          d          | j        j        rt          d          |pt          |          }| _        |2t          j        |                              t
          j                  }nt          j
        t          j         j        dg           j        j                  }t          j        d j        j        dz
  |z
  |dz                                             ddd         dd                                                             t
          j                  }t          j        d j        z
   j        z  dz            } j        j        rt          j        |          t          j        |                                          }                     ||          }t          j         fd	|D                                                       }n6t          j        |t          j        dt          |                    |          } j        j        d
k    r"d j        d         z
   j        d         z  dz  }n/ j        j        dk    rd}nt          d j        j                   t          j        ||gg                              t
          j                  }t          j        |                              |           _        t          j        |                              |t          j                   _        dg j        j        z   _        d _          j        j!        sC| j        j        z  dk    r0tD          #                    d            $                    d            j        j!        s@ j        j        dk    r0tD          #                    d            $                    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.
            timesteps (`List[int]`, *optional*):
                Custom timesteps used to support arbitrary spacing between timesteps. If `None`, then the default
                timestep spacing strategy of equal spacing between timesteps schedule is used. If `timesteps` is
                passed, `num_inference_steps` must be `None`.
        Nz?Must pass exactly one of  `num_inference_steps` or `timesteps`.z<Cannot use `timesteps` when `config.use_karras_sigmas=True`.r   r   r\   rS   )	in_sigmasrk   c                 <    g | ]}                     |          S r2   )_sigma_to_t)r4   sigma
log_sigmasrw   s     r   r6   z>DPMSolverSinglestepScheduler.set_timesteps.<locals>.<listcomp>D  s)    !Z!Z!Z%$"2"25*"E"E!Z!Z!Zr   	sigma_minr<   zC `final_sigmas_type` must be one of `sigma_min` or `zero`, but got )r   r   r   zChanging scheduler {self.config} to have `lower_order_final` set to True to handle uneven amount of inference steps. Please make sure to always use an even number of `num_inference steps when using `lower_order_final=False`.T)rJ   z `last_sigmas_type='zero'` is not supported for `lower_order_final=False`. Changing scheduler {self.config} to have `lower_order_final` set to True.r]   ))r    r}   rK   lenrk   rl   arrayastypeint64r$   searchsortedfliprh   rM   r^   r>   roundrm   rc   rg   _convert_to_karrasinterparangerL   concatenater&   rn   rv   ri   ro   rC   rp   rq   rJ   loggerwarningr	   rr   rs   rt   ru   )rw   rk   r   ro   clipped_idxri   
sigma_lastr   s   `      @r   set_timestepsz*DPMSolverSinglestepScheduler.set_timesteps  s   & &9+<^___*y/D^___ T[%B [\\\1CS^^#6  ++2228<<II  ,UZs-K-KT[MkllKAt{>B[PRehiRijj2"s$!!	  A 33t7JJsRSS;( 	MJWV__))++F,,vSf,ggF!Z!Z!Z!Z!ZSY!Z!Z!Z[[aaccIIYy")As6{{*C*CVLLF;(K77t21559LQ9OOTWWJJ[*f44JJuVZVaVsuu   * 677>>rzJJ&v..111@@))4477vU[7YY"Vdk&>>{, 	<1Dt{G_1_cd1d1dNN s   ##d#;;;{, 	<1NRX1X1XNN g   ##d#;;;--.ABB   knnU++r   rq   c                 ,   |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   rU   )r#   max)r   shaper$   r&   float64floatreshaperl   prodabsquantiler}   rF   clamprG   	unsqueezerv   )rw   rq   r   
batch_sizechannelsremaining_dims
abs_sampless           r   _threshold_samplez.DPMSolverSinglestepScheduler._threshold_samplel  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   )	rl   rg   maximumnewaxiscumsumargmaxclipr   r   )rw   r   r   	log_sigmadistslow_idxhigh_idxlowhighwr   s              r   r   z(DPMSolverSinglestepScheduler._sigma_to_t  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   rS   r2   )rw   r   re   rf   s       r   _sigma_to_alpha_sigma_tz4DPMSolverSinglestepScheduler._sigma_to_alpha_sigma_t  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).r   N	sigma_maxr\   r   g      @r   )hasattrr}   r   r   itemrl   r^   )
rw   r   rk   r   r   rhorampmin_inv_rhomax_inv_rhori   s
             r   r   z/DPMSolverSinglestepScheduler._convert_to_karras  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   rq   model_outputc                   t          |          dk    r|d         n|                    dd          }|+t          |          dk    r	|d         }nt          d          |t          ddd           | j        j        d	k    r| j        j        d
k    rR| j        j        dv r|ddddf         }| j        | j	                 }| 
                    |          \  }}|||z  z
  |z  }	nv| j        j        dk    r|}	nc| j        j        dk    r6| j        | j	                 }| 
                    |          \  }}||z  ||z  z
  }	nt          d| j        j         d          | j        j        r|                     |	          }	|	S | j        j        dk    r| j        j        d
k    r| j        j        dv r|ddddf         }|S | j        j        dk    r7| j        | j	                 }| 
                    |          \  }}|||z  z
  |z  }
|
S | j        j        dk    r7| j        | j	                 }| 
                    |          \  }}||z  ||z  z   }
|
S t          d| j        j         d          dS )a0  
        Convert the model output to the corresponding type the DPMSolver/DPMSolver++ algorithm needs. DPM-Solver is
        designed to discretize an integral of the noise prediction model, and DPM-Solver++ is designed to discretize an
        integral of the data prediction model.

        <Tip>

        The algorithm and model type are decoupled. You can use either DPMSolver or DPMSolver++ 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   timestepNr   z/missing `sample` as a required keyward argumentro   rQ   Passing `timesteps` is deprecated and has no effect as model output conversion is now handled via an internal counter `self.step_index`r:   r8   )learned_ranger|   rq   v_predictionzprediction_type given as z\ must be one of `epsilon`, `sample`, or `v_prediction` for the DPMSolverSinglestepScheduler.rP   )r   popr    r
   r}   rH   rD   rN   ri   r   r   rE   r   )rw   r   rq   argskwargsr   r   re   rf   x0_predr8   s              r   convert_model_outputz1DPMSolverSinglestepScheduler.convert_model_output  s   : "$ii!mm477J1M1M>4yy1}}a !RSSS Z   ;%66{*i77;,0AAA#/2A2#6LDO4#'#?#?#F#F !Gl$::gE,88&,>>DO4#'#?#?#F#F !F*W|-CC L0K L L L  
 {' :0099N[';66{*i77;,0AAA#/2A2#6L##,88DO4#'#?#?#F#F !Gl$::gE,>>DO4#'#?#?#F#F !L07V3CC L0K L L L  # 76r   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                 }}|                     |          \  }	}|                     |          \  }
}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
  }n6| j	        j
        dk    r&|	|
z  |z  |t          j        |          dz
  z  |z  z
  }|S )az  
        One step for the first-order DPMSolver (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 argumentro   rQ   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:   r9   rP   )r   r   r    r
   ri   r   r   r$   rg   r}   rH   r   )rw   r   rq   r   r   r   r   rf   sigma_sre   alpha_srh   lambda_shx_ts                  r   dpm_solver_first_order_updatez:DPMSolverSinglestepScheduler.dpm_solver_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;%66W$.'UYr]]S=P2QUa1aaCC[';66W$.'UYq\\C=O2PT`1``C
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
           }	}}|                     |          \  }
}|                     |          \  }}|                     |	          \  }}	t          j        |
          t          j        |          z
  }t          j        |          t          j        |          z
  }t          j        |          t          j        |	          z
  }|d         |d         }}||z
  ||z
  }}||z  }|d|z  ||z
  z  }}| j	        j
        dk    r| j	        j        dk    rK||	z  |z  |
t          j        |           dz
  z  |z  z
  d|
t          j        |           dz
  z  z  |z  z
  }n| j	        j        dk    rL||	z  |z  |
t          j        |           dz
  z  |z  z
  |
t          j        |           dz
  |z  dz   z  |z  z   }n| j	        j
        dk    r| j	        j        dk    rH|
|z  |z  |t          j        |          dz
  z  |z  z
  d|t          j        |          dz
  z  z  |z  z
  }nZ| j	        j        dk    rJ|
|z  |z  |t          j        |          dz
  z  |z  z
  |t          j        |          dz
  |z  dz
  z  |z  z
  }|S )a  
        One step for the second-order singlestep DPMSolver that computes the solution at time `prev_timestep` from the
        time `timestep_list[-2]`.

        Args:
            model_output_list (`List[torch.Tensor]`):
                The direct outputs from learned diffusion model at current and latter timesteps.
            timestep (`int`):
                The current and latter 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   timestep_listNr   r   r   r   rQ   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\   r9   r:   r;   rS   rX   rP   r   r   r    r
   ri   r   r   r$   rg   r}   rH   rI   r   )rw   r   rq   r   r   r   r   rf   sigma_s0sigma_s1re   alpha_s0alpha_s1rh   	lambda_s0	lambda_s1m0m1r   h_0r0D0D1r   s                           r   )singlestep_dpm_solver_second_order_updatezFDPMSolverSinglestepScheduler.singlestep_dpm_solver_second_order_updateW  s   2 $'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(9W%%	'(:(::Ih''%)H*=*==	Ih''%)H*=*==	"2&(9"(=BI%y9'<31WcBh27+B;%66{&*44x'61%)QB--#"56"<=W	1"(;<=BC 
 (F22x'61%)QB--#"56"<=59aR==3#6!";c"ABbHI 
 [';66{&*44x'61%)A,,"45;<W	!s(:;<rAB 
 (F22x'61%)A,,"45;<59Q<<##5":S"@ARGH 
 
r   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\  }}}	}
|                     |          \  }}|                     |          \  }}|                     |	          \  }}	|                     |
          \  }}
t          j        |          t          j        |          z
  }t          j        |          t          j        |          z
  }t          j        |          t          j        |	          z
  }t          j        |          t          j        |
          z
  }|d         |d         |d         }}}||z
  ||z
  ||z
  }}}||z  ||z  }}|}d|z  ||z
  z  d|z  ||z
  z  }}||z  ||z  z
  ||z
  z  }d||z
  z  ||z
  z  }| j	        j
        dk    r| j	        j        dk    rN||
z  |z  |t          j        |           dz
  z  |z  z
  |t          j        |           dz
  |z  dz   z  |z  z   } nw| j	        j        dk    rw||
z  |z  |t          j        |           dz
  z  |z  z
  |t          j        |           dz
  |z  dz   z  |z  z   |t          j        |           dz
  |z   |dz  z  dz
  z  |z  z
  } n| j	        j
        dk    r| j	        j        dk    rK||z  |z  |t          j        |          dz
  z  |z  z
  |t          j        |          dz
  |z  dz
  z  |z  z
  } n| j	        j        dk    rt||z  |z  |t          j        |          dz
  z  |z  z
  |t          j        |          dz
  |z  dz
  z  |z  z
  |t          j        |          dz
  |z
  |dz  z  dz
  z  |z  z
  } | S )a  
        One step for the third-order singlestep DPMSolver that computes the solution at time `prev_timestep` from the
        time `timestep_list[-3]`.

        Args:
            model_output_list (`List[torch.Tensor]`):
                The direct outputs from learned diffusion model at current and latter timesteps.
            timestep (`int`):
                The current and latter 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 diffusion process.

        Returns:
            `torch.Tensor`:
                The sample tensor at the previous timestep.
        r   r   Nr   r   r   / missing`sample` as a required keyward argumentrQ   r   r   r\   r   r9   g       @r:   r;   rX   rS   rP   r   )!rw   r   rq   r   r   r   r   rf   r   r   sigma_s2re   r   r   alpha_s2rh   r   r   	lambda_s2r   r   m2r   r   h_1r   r1r   D1_0D1_1r   D2r   s!                                    r   (singlestep_dpm_solver_third_order_updatezEDPMSolverSinglestepScheduler.singlestep_dpm_solver_third_order_update  s   4 $'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(9W%%	'(:(::Ih''%)H*=*==	Ih''%)H*=*==	Ih''%)H*=*==	&r*,=b,ACTUWCXB*I	,A9yCX3q#'BBh27+cBh27-Cd4i"t)#R0D4K BG,;%66{&*44x'61%)QB--#"56"<=59aR==3#6!";c"ABdJK 
 (F22x'61%)QB--#"56"<=59aR==3#6!";c"ABbHI 59aR==3#6#:ad"BS"HIROP  [';66{&*44x'61%)A,,"45;<59Q<<##5":S"@ATIJ 
 (F22x'61%)A,,"45;<59Q<<##5":S"@ARGH 59Q<<##5#9QT"AC"GHBNO  
r   rq   r   r   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k    r	|d         }nt          d	          |t          dd
d           |t          dd
d           |dk    r|                     |d         |          S |dk    r|                     ||          S |dk    r|                     ||          S t          d|           )a  
        One step for the singlestep DPMSolver.

        Args:
            model_output_list (`List[torch.Tensor]`):
                The direct outputs from learned diffusion model at current and latter timesteps.
            timestep (`int`):
                The current and latter 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 diffusion process.
            order (`int`):
                The solver order at this step.

        Returns:
            `torch.Tensor`:
                The sample tensor at the previous timestep.
        r   r   Nr   r   r   r   r|   z/ missing `order` as a required keyward argumentrQ   r   r   r\   r   zOrder must be 1, 2, 3, got )r   r   r    r
   r   r   r   )rw   r   rq   r   r   r   r   r   s           r   singlestep_dpm_solver_updatez9DPMSolverSinglestepScheduler.singlestep_dpm_solver_update  s   6 $'t99q==QfjjRV6W6W#&t99q==QfjjRV6W6W>4yy1}}a !RSSS=4yy1}}Q !RSSS$ ^   $ ^   A::556G6KTZ5[[[aZZAABS\bAcccaZZ@@AR[a@bbbB5BBCCCr   c                 .   || j         }||k                                    }t          |          dk    rt          | j                   dz
  }nHt          |          dk    r|d                                         }n|d                                         }|S )Nr   r   )ro   nonzeror   r   )rw   r   schedule_timestepsindex_candidatesr   s        r   index_for_timestepz/DPMSolverSinglestepScheduler.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)
r   
isinstancer$   Tensorrv   ro   r   r  rt   ru   )rw   r   s     r   _init_step_indexz-DPMSolverSinglestepScheduler._init_step_indexp  sd    
 #(EL11 >#;;t~'<==#66x@@D#0Dr   Tr   return_dictc                 $   | j         t          d          | j        |                     |           |                     ||          }t          | j        j        dz
            D ]}| j        |dz            | j        |<   || j        d<   | j	        | j                 }| j        |          |dz  }| j        |          |dk    r|| _
        |                     | j        | j
        |          }| 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 singlestep DPMSolver.

        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.

        NzaNumber of inference steps is 'None', you need to run 'set_timesteps' after creating the schedulerr   r   r\   r  )prev_sample)rk   r    r   r  r   r!   r}   rC   rp   rs   rq   r  rt   r   )rw   r   r   rq   r  r+   r   r  s           r   stepz!DPMSolverSinglestepScheduler.step|  sH   6 #+s   ?"!!(+++00f0MMt{/!344 	> 	>A$($6q1u$=Dq!!!-20  %(0QJE  %(0 A:: DK778JSWS^fk7ll 	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.
        r2   )rw   rq   r   r   s       r   scale_model_inputz.DPMSolverSinglestepScheduler.scale_model_input  s	     r   original_samplesnoisec                    
  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 r2   )r  )r4   r   r  rw   s     r   r6   z:DPMSolverSinglestepScheduler.add_noise.<locals>.<listcomp>  s*    ^^^qD33A7IJJ^^^r   r   r\   )ri   rv   r   r   typer$   is_floating_pointro   r&   r   r   r   flattenr   r   r   )rw   r  r  ro   ri   step_indicesr   re   rf   noisy_samplesr  s   `         @r   	add_noisez&DPMSolverSinglestepScheduler.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>   r   s    r   __len__z$DPMSolverSinglestepScheduler.__len__  s    {..r   )r   )NNNr  )T)-__name__
__module____qualname____doc__r   _compatiblesr   r	   r   intstrr   rl   ndarrayboolry   r   rr   propertyr   r   r   r   r$   r   r   r  r   r   r   r   r   r   r   r   r  r  r  r   r   r  r  	IntTensorr  r   r2   r   r   r0   r0   L   sN       9 9v ?>$=>>>LE $("%.2(",1"%+%"',1+1%*U5\\M'+%J, J, J, J, 	J,
 J,  
+J, J, J, J, %*J,  J, J, J,  J, $D>J,  $C=!J," "#J,$  }%J, J, J, J,X"# "$s) " " " "H     X  ! ! X!( (3 ( ( ( ( $(+/)-	T, T, T, c5<'(T, DI&	T, T, T, T,n     D  0     EL RWR^    :  $	W W WlW 	W 
W W W Wz  $	6 6 6l6 	6 
6 6 6 6x  $	\ \ \-\ 	\ 
\ \ \ \D  $	f f f-f 	f 
f f f fX  $<D <D <D-<D 	<D
 <D 
<D <D <D <D~   (
1 
1 
1" !;8 ;8l;8 ;8 	;8
 ;8 
%	&;8 ;8 ;8 ;8z %,      ,  |  ?	 
 
       D/ / / / /r   r0   )r   r   )r   typingr   r   r   r   numpyrl   r$   configuration_utilsr   r	   utilsr
   r   scheduling_utilsr   r   r   
get_loggerr!  r   r.   r0   r2   r   r   <module>r2     s  "  / / / / / / / / / / / /      A A A A A A A A & & & & & & & & X X X X X X X X X X 
	H	%	% !)4 )4 )4 )4X`/ `/ `/ `/ `/>; `/ `/ `/ `/ `/r   