
    bi|                     x    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  G d d	ee
      Zy)
    N)ListOptionalTupleUnion   )ConfigMixinregister_to_config)randn_tensor   )SchedulerMixinSchedulerOutputc            #          e Zd ZdZg ZdZe	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d9dedededede	ded	ed
e	de
dedededede
de
dee   f d       Zed        Zed        Zed        Zd:de	fdZd Zd Zd Zdej,                  deeej,                  f   dej,                  fdZd;d!e	d"eeej2                  f   fd#Zd;dej,                  fd$Zd;dej,                  fd%Zdej,                  dej,                  fd&Zd' Zd( Z	 d<d)ej,                  dej,                  dej,                  fd*Z 	 	 d;d)ej,                  dej,                  d+eej,                     dej,                  fd,Z!	 	 d;d-e"ej,                     dej,                  d+eej,                     dej,                  fd.Z#	 d<d-e"ej,                     dej,                  dej,                  fd/Z$d<d0Z%d1 Z&	 	 d=d)ej,                  dee	ej,                  f   dej,                  d2e
dee'e(f   f
d3Z)d4ej,                  d+ej,                  d5ej,                  dej,                  fd6Z*d7 Z+d8 Z,y )>EDMDPMSolverMultistepSchedulera%  
    Implements DPMSolverMultistepScheduler in EDM formulation as presented in Karras et al. 2022 [1].
    `EDMDPMSolverMultistepScheduler` is a fast dedicated high-order solver for diffusion ODEs.

    [1] Karras, Tero, et al. "Elucidating the Design Space of Diffusion-Based Generative Models."
    https://huggingface.co/papers/2206.00364

    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:
        sigma_min (`float`, *optional*, defaults to 0.002):
            Minimum noise magnitude in the sigma schedule. This was set to 0.002 in the EDM paper [1]; a reasonable
            range is [0, 10].
        sigma_max (`float`, *optional*, defaults to 80.0):
            Maximum noise magnitude in the sigma schedule. This was set to 80.0 in the EDM paper [1]; a reasonable
            range is [0.2, 80.0].
        sigma_data (`float`, *optional*, defaults to 0.5):
            The standard deviation of the data distribution. This is set to 0.5 in the EDM paper [1].
        sigma_schedule (`str`, *optional*, defaults to `karras`):
            Sigma schedule to compute the `sigmas`. By default, we the schedule introduced in the EDM paper
            (https://huggingface.co/papers/2206.00364). Other acceptable value is "exponential". The exponential
            schedule was incorporated in this model: https://huggingface.co/stabilityai/cosxl.
        num_train_timesteps (`int`, defaults to 1000):
            The number of diffusion steps to train the model.
        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 `sde-dpmsolver++`. 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.
        euler_at_final (`bool`, defaults to `False`):
            Whether to use Euler's method in the final step. It is a trade-off between numerical stability and detail
            richness. This can stabilize the sampling of the SDE variant of DPMSolver for small number of inference
            steps, but sometimes may result in blurring.
        final_sigmas_type (`str`, 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.
    r   	sigma_min	sigma_max
sigma_datasigma_schedulenum_train_timestepsprediction_typerhosolver_orderthresholdingdynamic_thresholding_ratiosample_max_valuealgorithm_typesolver_typelower_order_finaleuler_at_finalfinal_sigmas_typec                    |dvr2|dk(  r| j                  d       nt        | d| j                         |dvr1|dv r| j                  d	       nt        | d| j                         |dvr|d
k(  rt        d| d| d      t	        j
                  dd|      }|dk(  r| j                  |      }n|dk(  r| j                  |      }| j                        | _	        t	        j                  |t	        j                  d|j                        g      | _        d | _        d g|z  | _        d| _        d | _        d | _        | j                  j'                  d      | _        y )N)dpmsolver++sde-dpmsolver++deisr!   )r   z is not implemented for )midpointheun)logrhobh1bh2r$   )r   zeroz`final_sigmas_type` z' is not supported for `algorithm_type` z$. Please choose `sigma_min` instead.r   r   karrasexponential)devicecpu)r	   NotImplementedError	__class__
ValueErrortorchlinspace_compute_karras_sigmas_compute_exponential_sigmasprecondition_noise	timestepscatzerosr,   sigmasnum_inference_stepsmodel_outputslower_order_nums_step_index_begin_indexto)selfr   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   rampr9   s                      r/home/cdr/jupyterlab/.venv/lib/python3.12/site-packages/diffusers/schedulers/scheduling_edm_dpmsolver_multistep.py__init__z'EDMDPMSolverMultistepScheduler.__init__[   s   * !CC'''}'E)^,<<TUYUcUcTd*eff2266''J'?)[M9QRVR`R`Qa*bcc!CCHY]cHc&'8&99`ao`p  qU  V  ~~a$78X%006F},55d;F008iiQv}})M NO $( "Vl2 ! kknnU+    c                 @    | j                   j                  dz  dz   dz  S )Nr   r         ?)configr   r@   s    rB   init_noise_sigmaz/EDMDPMSolverMultistepScheduler.init_noise_sigma   s#     %%q(1,44rD   c                     | j                   S )zg
        The index counter for current timestep. It will increase 1 after each scheduler step.
        )r=   rH   s    rB   
step_indexz)EDMDPMSolverMultistepScheduler.step_index   s    
 rD   c                     | j                   S )zq
        The index for the first timestep. It should be set from pipeline with `set_begin_index` method.
        r>   rH   s    rB   begin_indexz*EDMDPMSolverMultistepScheduler.begin_index   s    
    rD   rN   c                     || _         y)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.
        NrM   )r@   rN   s     rB   set_begin_indexz.EDMDPMSolverMultistepScheduler.set_begin_index   s     (rD   c                 2    | j                  |      }||z  }|S N)_get_conditioning_c_in)r@   samplesigmac_inscaled_samples        rB   precondition_inputsz2EDMDPMSolverMultistepScheduler.precondition_inputs   s!    **51rD   c                     t        |t        j                        st        j                  |g      }dt        j                  |      z  }|S )Ng      ?)
isinstancer1   Tensortensorlog)r@   rU   c_noises      rB   r5   z1EDMDPMSolverMultistepScheduler.precondition_noise   s8    %.LL%)E5))rD   c                 j   | j                   j                  }|dz  |dz  |dz  z   z  }| j                   j                  dk(  r||z  |dz  |dz  z   dz  z  }nR| j                   j                  dk(  r| |z  |dz  |dz  z   dz  z  }n#t        d| j                   j                   d      ||z  ||z  z   }|S )Nr   epsilonrF   v_predictionzPrediction type z is not supported.)rG   r   r   r0   )r@   rT   model_outputrU   r   c_skipc_outdenoiseds           rB   precondition_outputsz3EDMDPMSolverMultistepScheduler.precondition_outputs   s    [[++
Q%(Z]":;;;&&)3J&%(Z]*Bs)JJE[[((N:FZ'5!8j!m+C*KKE/0K0K/LL^_``F?U\%99rD   rT   timestepreturnc                     | j                   | j                  |       | j                  | j                      }| j                  ||      }d| _        |S )a   
        Ensures interchangeability with schedulers that need to scale the denoising model input depending on the
        current timestep. Scales the denoising model input by `(sigma**2 + 1) ** 0.5` to match the Euler algorithm.

        Args:
            sample (`torch.Tensor`):
                The input sample.
            timestep (`int`, *optional*):
                The current timestep in the diffusion chain.

        Returns:
            `torch.Tensor`:
                A scaled input sample.
        T)rK   _init_step_indexr9   rX   is_scale_input_called)r@   rT   rg   rU   s       rB   scale_model_inputz0EDMDPMSolverMultistepScheduler.scale_model_input   sM     ??"!!(+DOO,))&%8%)"rD   Nr:   r,   c                 r   || _         t        j                  dd| j                         }| j                  j                  dk(  r| j                  |      }n*| j                  j                  dk(  r| j                  |      }j                  t        j                  |      }| j                  |      | _
        | j                  j                  dk(  r| j                  j                  }n>| j                  j                  dk(  rd}n"t        d| j                  j                         t        j                  |t        j                  |gt        j                  |      g      | _        d	g| j                  j"                  z  | _        d| _        d	| _        d	| _        | j                   j                  d
      | _        y	)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*   r+   )dtyper,   r   r)   zC`final_sigmas_type` must be one of 'zero', or 'sigma_min', but got Nr-   )r:   r1   r2   rG   r   r3   r4   r?   float32r5   r6   r   r   r0   r7   r\   r9   r   r;   r<   r=   r>   )r@   r:   r,   rA   r9   
sigma_lasts         rB   set_timestepsz,EDMDPMSolverMultistepScheduler.set_timesteps   si    $7 ~~aD$<$<=;;%%1006F[[''=855d;Fv>008;;((K7..J[[**f4JUVZVaVaVsVsUtu  iizl%--`f)g hi 
KK$$% !"   kknnU+rD   c                     |xs | j                   j                  }|xs | j                   j                  }| j                   j                  }|d|z  z  }|d|z  z  }||||z
  z  z   |z  }|S )z6Constructs the noise schedule of Karras et al. (2022).r   )rG   r   r   r   )r@   rA   r   r   r   min_inv_rhomax_inv_rhor9   s           rB   r3   z5EDMDPMSolverMultistepScheduler._compute_karras_sigmas  sq    6!6!6	6!6!6	kkooAG,AG,k(A BBsJrD   c                 4   |xs | j                   j                  }|xs | j                   j                  }t        j                  t        j                  |      t        j                  |      t        |            j                         j                  d      }|S )zImplementation closely follows k-diffusion.

        https://github.com/crowsonkb/k-diffusion/blob/6ab5146d4a5ef63901326489f31f1d8e7dd36b48/k_diffusion/sampling.py#L26
        r   )
rG   r   r   r1   r2   mathr]   lenexpflip)r@   rA   r   r   r9   s        rB   r4   z:EDMDPMSolverMultistepScheduler._compute_exponential_sigmas!  sn    
 6!6!6	6!6!6	 3TXXi5H#d)TXXZ__`abrD   c                 b   |j                   }|j                  ^}}}|t        j                  t        j                  fvr|j                         }|j                  ||t        j                  |      z        }|j                         }t        j                  || j                  j                  d      }t        j                  |d| j                  j                        }|j                  d      }t        j                  || |      |z  } |j                  ||g| }|j!                  |      }|S )a{  
        "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   )dim)minmax)rn   shaper1   ro   float64floatreshapenpprodabsquantilerG   r   clampr   	unsqueezer?   )r@   rT   rn   
batch_sizechannelsremaining_dims
abs_sampless           rB   _threshold_samplez0EDMDPMSolverMultistepScheduler._threshold_sample,  s     06-
H~66\\^F 
Hrww~7N,NOZZ\
NN:t{{'M'MSTUKK1$++66
 KKNVaR+a/
HF~F5!rD   c                    t        j                  t        j                  |d            }||d d t         j                  f   z
  }t        j                  |dk\  d      j                  d      j                  |j                  d   dz
        }|dz   }||   }||   }||z
  ||z
  z  }	t        j                  |	dd      }	d|	z
  |z  |	|z  z   }
|
j                  |j                        }
|
S )Ng|=r   )axisr   )r}   r   )	r   r]   maximumnewaxiscumsumargmaxclipr~   r   )r@   rU   
log_sigmas	log_sigmadistslow_idxhigh_idxlowhighwts              rB   _sigma_to_tz*EDMDPMSolverMultistepScheduler._sigma_to_tN  s    FF2::eU34	 Jq"**}55 ))UaZq188a8@EE*JZJZ[\J]`aJaEbQ;!(# 9_t,GGAq! UgH,IIekk"rD   c                 8    t        j                  d      }|}||fS )Nr   )r1   r\   )r@   rU   alpha_tsigma_ts       rB   _sigma_to_alpha_sigma_tz6EDMDPMSolverMultistepScheduler._sigma_to_alpha_sigma_te  s    ,,q/rD   rb   c                     | j                   | j                     }| j                  |||      }| j                  j                  r| j                  |      }|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.
        )r9   rK   rf   rG   r   r   )r@   rb   rT   rU   x0_preds        rB   convert_model_outputz3EDMDPMSolverMultistepScheduler.convert_model_outputk  sL    6 DOO,++FL%H;;##,,W5GrD   noisec           	      "   | j                   | j                  dz      | j                   | j                     }}| 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
  }|S | j
                  j                  dk(  rz|J ||z  t        j                  |
       z  |z  |dt        j                  d|
z        z
  z  |z  z   |t        j                  dt        j                  d|
z        z
        z  |z  z   }S )a  
        One step for the first-order DPMSolver (equivalent to DDIM).

        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 sample tensor at the previous timestep.
        r   r!         ?r"          )	r9   rK   r   r1   r]   rG   r   rx   sqrt)r@   rb   rT   r   r   sigma_sr   alpha_slambda_tlambda_shx_ts               rB   dpm_solver_first_order_updatez<EDMDPMSolverMultistepScheduler.dpm_solver_first_order_update  s{   &  ;;t':;T[[=Y77@77@99W%		'(::99W%		'(::x;;%%6W$.'UYYr]S=P2QUa1aaC 
 [[''+<<$$$7"UYYr]2f<a%))D1H"556,FGEJJsUYYrAv->'>??%GH  
rD   model_output_listc           	      Z   | j                   | j                  dz      | j                   | j                     | j                   | j                  dz
     }}}| j                  |      \  }}| j                  |      \  }}| j                  |      \  }	}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(  rM||z  |z  |t        j                  |       dz
  z  |z  z
  d|t        j                  |       dz
  z  z  |z  z
  }|S | j
                  j                  dk(  rN||z  |z  |t        j                  |       dz
  z  |z  z
  |t        j                  |       dz
  |z  dz   z  |z  z   }S | j
                  j                  d	k(  rt|J | j
                  j                  dk(  r||z  t        j                  |       z  |z  |dt        j                  d
|z        z
  z  |z  z   d|dt        j                  d
|z        z
  z  z  |z  z   |t        j                  dt        j                  d|z        z
        z  |z  z   }|S | j
                  j                  dk(  r||z  t        j                  |       z  |z  |dt        j                  d
|z        z
  z  |z  z   |dt        j                  d
|z        z
  d
|z  z  dz   z  |z  z   |t        j                  dt        j                  d|z        z
        z  |z  z   }S )a  
        One step for the second-order multistep DPMSolver.

        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   r   r   r!   r$   rF   r%   r"   r   )
r9   rK   r   r1   r]   rG   r   r   rx   r   )r@   r   rT   r   r   sigma_s0sigma_s1r   alpha_s0alpha_s1r   	lambda_s0	lambda_s1m0m1r   h_0r0D0D1r   s                        rB   (multistep_dpm_solver_second_order_updatezGEDMDPMSolverMultistepScheduler.multistep_dpm_solver_second_order_update  s   ( KK!+,KK(KK!+, $  77@!99(C(!99(C(99W%		'(::IIh'%))H*==	IIh'%))H*==	"2&(9"(=BI%y9'<31WcBh27+B;;%%6{{&&*4x'61%))QB-#"56"<=W		1"(;<=BC 8 
/ ((F2x'61%))QB-#"56"<=599aR=3#6!";c"ABbHI , 
# [[''+<<$$${{&&*4x'%))QB-76A!eiiq&9"9:b@AWEIIdQh,?(?@ABFG 

3261B+B CCeKL  
 ((F2x'%))QB-76A!eiiq&9"9:b@A34!8)<#<"JS"PQUWWX 

3261B+B CCeKL  
rD   c                    | j                   | j                  dz      | j                   | j                     | j                   | j                  dz
     | j                   | j                  dz
     f\  }}}}| j                  |      \  }}| j                  |      \  }}| j                  |      \  }	}| j                  |      \  }
}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(  rz||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 multistep DPMSolver.

        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   r   r   r   r!   rF   )r9   rK   r   r1   r]   rG   r   rx   )r@   r   rT   r   r   r   sigma_s2r   r   r   alpha_s2r   r   r   	lambda_s2r   r   m2r   r   h_1r   r1r   D1_0D1_1r   D2r   s                                rB   'multistep_dpm_solver_third_order_updatezFEDMDPMSolverMultistepScheduler.multistep_dpm_solver_third_order_update  s   & KK!+,KK(KK!+,KK!+,	1
-8X  77@!99(C(!99(C(!99(C(99W%		'(::IIh'%))H*==	IIh'%))H*==	IIh'%))H*==	&r*,=b,ACTUWCXB*I	,A9yCX3q#'BBh27+cBh27-CdR27^t44R"Wo$+.;;%%6 8#v-eiimc12b89uyy!}s2a7#=>"DE uyy!}s2Q6!Q$>DEKL  
rD   c                    || j                   }||k(  j                         }t        |      dk(  rt        | j                         dz
  }|S t        |      dkD  r|d   j                         }|S |d   j                         }|S )Nr   r   )r6   nonzerorw   item)r@   rg   schedule_timestepsindex_candidatesrK   s        rB   index_for_timestepz1EDMDPMSolverMultistepScheduler.index_for_timestep2  s    %!%.(:CCE A%T^^,q0J  !"Q&)!,113J  *!,113JrD   c                     | j                   Vt        |t        j                        r%|j	                  | j
                  j                        }| j                  |      | _        y| j                  | _        y)zF
        Initialize the step_index counter for the scheduler.
        N)
rN   rZ   r1   r[   r?   r6   r,   r   r=   r>   )r@   rg   s     rB   rj   z/EDMDPMSolverMultistepScheduler._init_step_indexF  sW    
 #(ELL1#;;t~~'<'<=#66x@D#00DrD   return_dictc                    | j                   t        d      | j                  | j                  |       | j                  t	        | j
                        dz
  k(  xrc | j                  j                  xsK | j                  j                  xr t	        | j
                        dk  xs | j                  j                  dk(  }| j                  t	        | j
                        dz
  k(  xr0 | j                  j                  xr t	        | j
                        dk  }| j                  ||      }t        | j                  j                  dz
        D ]!  }| j                  |dz      | j                  |<   # || j                  d<   | j                  j                  d	k(  r.t        |j                   ||j"                  |j$                  
      }	nd}	| j                  j                  dk(  s| j&                  dk  s|r| j)                  |||	      }
nf| j                  j                  dk(  s| j&                  dk  s|r| j+                  | j                  ||	      }
n| j-                  | j                  |      }
| j&                  | j                  j                  k  r| xj&                  dz  c_        | xj.                  dz  c_        |s|
fS t1        |
      S )a  
        Predict the sample from the previous timestep by reversing the SDE. This function propagates the sample with
        the multistep 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.
            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)   r   )rT   r   r"   )	generatorr,   rn   )rT   r   )prev_sample)r:   r0   rK   rj   rw   r6   rG   r   r   r   r   ranger   r;   r   r
   r~   r,   rn   r<   r   r   r   r=   r   )r@   rb   rg   rT   r   r   r   lower_order_secondir   r   s              rB   stepz#EDMDPMSolverMultistepScheduler.stepR  s   < ##+s  ??"!!(+ "__DNN0Ca0GG 
KK&& 7--J#dnn2E2J7{{,,6 	 __DNN 3a 77wT[[=Z=Zw_bcgcqcq_ruw_w 	 00f0Mt{{//!34 	>A$($6$6q1u$=Dq!	>!-2;;%%):: ""i@S@S[g[m[mE E;;##q(D,A,AA,EIZ<<\RX`e<fK[[%%*d.C.Ca.GK]GGHZHZciqvGwKFFtGYGYbhFiK  4;;#;#;;!!Q&! 	A>!;77rD   original_samplesr6   c                    | j                   j                  |j                  |j                        }|j                  j                  dk(  rvt        j                  |      ra| j                  j                  |j                  t
        j                        }|j                  |j                  t
        j                        }n@| j                  j                  |j                        }|j                  |j                        }| j                   |D cg c]  }| j                  ||       }}nG| j                  | j                  g|j                  d   z  }n| j                  g|j                  d   z  }||   j                         }t        |j                        t        |j                        k  r=|j                  d      }t        |j                        t        |j                        k  r=|||z  z   }	|	S c c}w )N)r,   rn   mps)rn   r   r   )r9   r?   r,   rn   typer1   is_floating_pointr6   ro   rN   r   rK   r~   flattenrw   r   )
r@   r   r   r6   r9   r   r   step_indicesrU   noisy_sampless
             rB   	add_noisez(EDMDPMSolverMultistepScheduler.add_noise  s    '7'>'>FVF\F\]""''50U5L5LY5W!%!2!23C3J3JRWR_R_!2!`!%5%<%<EMMRI!%!2!23C3J3J!K!%5%<%<=I #T]^qD33A7IJ^L^__( OO,yq/AAL !,,-	0BBL|$,,.%++%5%;%;!<<OOB'E %++%5%;%;!<< )55=8 _s   G9c                 P    d|dz  | j                   j                  dz  z   dz  z  }|S )Nr   r   rF   )rG   r   )r@   rU   rV   s      rB   rS   z5EDMDPMSolverMultistepScheduler._get_conditioning_c_in  s.    UAX 6 6 99cABrD   c                 .    | j                   j                  S rR   )rG   r   rH   s    rB   __len__z&EDMDPMSolverMultistepScheduler.__len__  s    {{...rD   )gMb`?g      T@rF   r*   i  r`   g      @r   Fgףp=
?r   r!   r$   TFr)   )r   )NNrR   )NT)-__name__
__module____qualname____doc___compatiblesorderr	   r   strintboolr   rC   propertyrI   rK   rN   rP   rX   r5   rf   r1   r[   r   rl   r,   rq   r3   r4   r   r   r   r   r   r   r   r   r   rj   r   r   r   r   rS   r    rD   rB   r   r      s   9v LE !&#'(",1"%+%"&$+1#5,5, 5, 	5,
 5, !5, 5, 5, 5, 5, %*5,  5, 5, 5,  5,  !5," $C=#5, 5,n 5 5     ! !(3 (  eU\\FY@Z _d_k_k 0), ),U3PUP\P\K\E] ),X	ell 	SXS_S_   D.   $!ll! ! 
	!L  $(,	$ll$ $ %	$
 
$R  $(,	E-E E %	E
 
ET  $4-4 4 
	4n(
1"  L8llL8 U\\)*L8 	L8 L8 
%	&L8^,, || <<	
 
D/rD   r   )rv   typingr   r   r   r   numpyr   r1   configuration_utilsr   r	   utils.torch_utilsr
   scheduling_utilsr   r   r   r   rD   rB   <module>r      s/   "  / /   A , =l
/^[ l
/rD   