
    i+              	          d dl Z d dlmZ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mZ ddlmZ ddlmZmZmZ  e       rd dlZ ej2                  e      Z	 	 dd	ed
eded   de	j<                  fdZ G d dee      Z y)    N)ListLiteralOptionalTupleUnion   )ConfigMixinregister_to_config)	deprecateis_scipy_availablelogging)randn_tensor   )KarrasDiffusionSchedulersSchedulerMixinSchedulerOutputnum_diffusion_timestepsmax_betaalpha_transform_type)cosineexpreturnc           
      $   |dk(  rd }n|dk(  rd }nt        d|       g }t        |       D ]<  }|| z  }|dz   | z  }|j                  t        d ||       ||      z  z
  |             > t	        j
                  |t        j                        S )aB  
    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`, defaults to `0.999`):
            The maximum beta to use; use values lower than 1 to avoid numerical instability.
        alpha_transform_type (`"cosine"` or `"exp"`, defaults to `"cosine"`):
            The type of noise schedule for `alpha_bar`. Choose from `cosine` or `exp`.

    Returns:
        `torch.Tensor`:
            The betas used by the scheduler to step the model outputs.
    r   c                 f    t        j                  | dz   dz  t         j                  z  dz        dz  S )NgMb?gT㥛 ?r   )mathcospits    ~/home/obispo/Crisostomo_bridge/mision_env/lib/python3.12/site-packages/diffusers/schedulers/scheduling_dpmsolver_singlestep.pyalpha_bar_fnz)betas_for_alpha_bar.<locals>.alpha_bar_fn>   s-    88QY%/$''9A=>!CC    r   c                 2    t        j                  | dz        S )Ng      ()r   r   r   s    r    r!   z)betas_for_alpha_bar.<locals>.alpha_bar_fnC   s    88AI&&r"   z"Unsupported alpha_transform_type: r   dtype)
ValueErrorrangeappendmintorchtensorfloat32)r   r   r   r!   betasit1t2s           r    betas_for_alpha_barr1   $   s    0 x'	D 
	&	' =>R=STUUE*+ M((!e..S\"-R0@@@(KLM <<U]]33r"   c            0          e Zd ZdZeD  cg c]  }|j
                   c}} ZdZeddddddd	d
ddddd
d
d
d
d
dd e	d       d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e   d"ee   d#ee	   d$ee   d%e	d&ee   d'ed(ef.d)       Zd*e
d+ee
   fd,Zed-        Zed.        ZdUd/e
fd0Z	 	 	 	 dVd*e
d1eeej2                  f   d2ee	   d3eee
      fd4Zd5ej6                  d+ej6                  fd6Zd7 Zd8 Zd9ej6                  d+ej6                  fd:Zd9ej6                  d*e
d+ej6                  fd;Z 	 dWd9ej6                  d*e
d<e	d=e	d+ej6                  f
d>Z!dd?d@ej6                  d5ej6                  d+ej6                  fdAZ"dddBd@ej6                  d5ej6                  dCeej6                     d+ej6                  fdDZ#dddBdEeej6                     d5ej6                  dCeej6                     d+ej6                  fdFZ$dddBdEeej6                     d5ej6                  dCeej6                     d+ej6                  fdGZ%ddddHdEeej6                     d5ej6                  dIe
dCeej6                     d+ej6                  f
dJZ&	 dXdKee
ej6                  f   dLeej6                     d+e
fdMZ'dN Z(	 	 dYd@ej6                  dKee
ej6                  f   d5ej6                  dOed+ee)e*f   f
dPZ+d5ej6                  d+ej6                  fdQZ,dRej6                  dCej6                  d3ejZ                  d+ej6                  fdSZ.dT Z/yc c}} w )Z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://huggingface.co/papers/2210.02303) 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++` or `sde-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}.
        use_exponential_sigmas (`bool`, *optional*, defaults to `False`):
            Whether to use exponential sigmas for step sizes in the noise schedule during the sampling process.
        use_beta_sigmas (`bool`, *optional*, defaults to `False`):
            Whether to use beta sigmas for step sizes in the noise schedule during the sampling process. Refer to [Beta
            Sampling is All You Need](https://huggingface.co/papers/2407.12173) for more information.
        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.
    r   i  g-C6?g{Gz?linearNr   epsilonFgףp=
?      ?dpmsolver++midpointzeroinfexponentialnum_train_timesteps
beta_startbeta_endbeta_scheduletrained_betassolver_orderprediction_typethresholdingdynamic_thresholding_ratiosample_max_valuealgorithm_typesolver_typelower_order_finaluse_karras_sigmasuse_exponential_sigmasuse_beta_sigmasuse_flow_sigmas
flow_shiftfinal_sigmas_typelambda_min_clippedvariance_typeuse_dynamic_shiftingtime_shift_typec                 $   | j                   j                  rt               st        d      t	        | j                   j                  | j                   j
                  | j                   j                  g      dkD  rt        d      |dk(  rd}t        dd|       |+t        j                  |t        j                        | _        n|d	k(  r-t        j                  |||t        j                        | _        nk|d
k(  r6t        j                  |dz  |dz  |t        j                        dz  | _        n0|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r2|dk(  r| j7                  d       nt        | d| j                          |dvr1|dv r| j7                  d       nt        | d| j                          |dvr|dk(  rt        d| d| d      d | _        t;        j                  d|dz
  |t:        j                        d d d   j=                         }t        j>                  |      | _         d g|z  | _!        d | _"        | jG                  |      | _$        d | _%        d | _&        | j2                  jO                  d       | _        y )!Nz:Make sure to install scipy if you want to use beta sigmas.r   znOnly one of `config.use_beta_sigmas`, `config.use_exponential_sigmas`, `config.use_karras_sigmas` can be used.	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$   r4   scaled_linear      ?r   squaredcos_cap_v2z is not implemented for r6   r   dim)rT   r7   sde-dpmsolver++deisr7   )rF   )r8   heun)logrhobh1bh2r8   )rG   r7   r[   r9   z`final_sigmas_type` z' is not supported for `algorithm_type` z$. Please choose `sigma_min` instead.cpu)(configrK   r   ImportErrorsumrJ   rI   r&   r   r*   r+   r,   r-   linspacer1   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sampleget_order_list
order_list_step_index_begin_indexto)selfr<   r=   r>   r?   r@   rA   rB   rC   rD   rE   rF   rG   rH   rI   rJ   rK   rL   rM   rN   rO   rP   rQ   rR   deprecation_messagerx   s                             r    __init__z%DPMSolverSinglestepScheduler.__init__   sF   6 ;;&&/A/CZ[[++T[[-O-OQUQ\Q\QnQnopstt A  [( #m17<OP$m5==IDJh&
H>QY^YfYfgDJo-
C3H[chcpcpquvvDJ11,-@ADJ%7OPTP^P^O_&`aaDJJ&#mmDKKQ?zz$"5"56zz!d&9&9"9:		$,,/%))DLL2IID///43F3FF3N !$ !PP'''}'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 
 $( KK#6#:<OWYWaWabcgegcghmmo	)))4"Vl2--.AB kknnU+r"   rt   r   c                     |}| j                   j                  }|dkD  rt        d      | j                   j                  r|dk(  rF|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   }nvg d|dz  z  ddgz   }nf|dk(  r*|dz  dk(  rddg|dz  dz
  z  ddgz   }nFddg|dz  z  dgz   }n7|dk(  r2d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  }| j                   j                  dk(  rdd<   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   r9   rb   )rd   rA   r&   rH   rN   )r   rt   stepsorderorderss        r    r{   z+DPMSolverSinglestepScheduler.get_order_list   s_    $((19KLL;;((z19>&%1*q.9QFBaSHFQY!^&%1*5;F&%1*5A>F!19>VuzA~6!Q?FVuz2aS8F!uz"eqj1!Q5A:.!u;;((F2F2Jr"   c                     | j                   S )zg
        The index counter for current timestep. It will increase 1 after each scheduler step.
        )r}   r   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.
        r~   r   s    r    begin_indexz(DPMSolverSinglestepScheduler.begin_index  s    
    r"   r   c                     || _         y)z
        Sets the begin index for the scheduler. This function should be run from pipeline before the inference.

        Args:
            begin_index (`int`, defaults to `0`):
                The begin index for the scheduler.
        Nr   )r   r   s     r    set_begin_indexz,DPMSolverSinglestepScheduler.set_begin_index%  s     (r"   devicemurx   c           	      (   |U| j                   j                  r| j                   j                  dk(  sJ t        j                  |      | j                   _        ||t        d      ||t        d      |!| j                   j                  rt        d      |!| j                   j                  rt        d      |!| j                   j                  rt        d      |xs t        |      }|| _        |3t        j                  |      j                  t        j                        }nt        j                   t        j"                  | j$                  dg      | j                   j&                        }|j)                         }t        j*                  d| j                   j,                  dz
  |z
  |dz         j/                         ddd	   dd	 j1                         j                  t        j                        }t        j                  d| j2                  z
  | j2                  z  d
z        }t        j4                  |      }| j                   j                  ryt        j"                  |      j1                         }| j7                  ||      }t        j                  |D cg c]  }| j9                  ||       c}      j/                         }n| j                   j                  rkt        j"                  |      j1                         }| j;                  ||      }t        j                  |D cg c]  }| j9                  ||       c}      }n| j                   j                  rkt        j"                  |      j1                         }| j=                  ||      }t        j                  |D cg c]  }| j9                  ||       c}      }n| j                   j>                  rt        j*                  dd| j                   j,                  z  |dz         }	d|	z
  }t        j"                  | j                   j
                  |z  d| j                   j
                  dz
  |z  z   z        dd	 j1                         }|| j                   j,                  z  j1                         }n4t        j@                  |t        jB                  dt        |            |      }| j                   jD                  dk(  r&d| j2                  d   z
  | j2                  d   z  d
z  }
n>| j                   jD                  dk(  rd}
n"t        d| j                   jD                         t        jF                  ||
gg      j                  t        jH                        }t        jJ                  |      jM                  |      | _'        t        jJ                  |      jM                  |t        j                        | _(        dg| j                   jR                  z  | _*        d| _+        | j                   jX                  sC|| j                   jR                  z  dk7  r'tZ        j]                  d       | j_                  d       | j                   jX                  s@| j                   jD                  dk(  r'tZ        j]                  d       | j_                  d       | ja                  |      | _1        d| _2        d| _3        | jN                  jM                  d      | _'        yc c}w c c}w c c}w )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`.
        Nr;   z?Must pass exactly one of  `num_inference_steps` or `timesteps`.z<Cannot use `timesteps` when `config.use_karras_sigmas=True`.zCCannot set `timesteps` with `config.use_exponential_sigmas = True`.z<Cannot set `timesteps` with `config.use_beta_sigmas = True`.r   r   rb   rW   )	in_sigmasrt   r6   	sigma_minr9   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)rH   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.rc   )4rd   rQ   rR   ru   r   rM   r&   rI   rJ   rK   lenrt   arrayastypeint64r*   searchsortedfliprq   rO   itemrg   r<   roundrv   rl   rp   _convert_to_karras_sigma_to_t_convert_to_exponential_convert_to_betarL   interparangerN   concatenater,   rw   r   rr   rx   rA   ry   rz   rH   loggerwarningr
   r{   r|   r}   r~   )r   rt   r   r   rx   clipped_idxrr   
log_sigmassigmarj   
sigma_lasts              r    set_timestepsz*DPMSolverSinglestepScheduler.set_timesteps/  s   ( >;;338S8SWd8ddd%'VVBZDKK"&9+<^__*y/D^__ T[[%B%B[\\ T[[%G%Gbcc T[[%@%@[\\1CS^#6  +22288<I  ,,UZZs-KT[[MkMklK%**,KAt{{>>B[PRehiRij2"$!	  A 3 33t7J7JJsRSVVF^
;;((WWV_))+F,,vSf,gFSY!Z%$"2"25*"E!Z[aacI[[//WWV_))+F11FXk1lFSY!Z%$"2"25*"E!Z[I[[((WWV_))+F**VQd*eFSY!Z%$"2"25*"E!Z[I[[(([[A(G(G$GI\_`I`aF6\FWWT[[33f<T[[E[E[^_E_ciDi@ijklomopuuwF$++"A"AAGGIIYYy"))As6{*CVLF;;((K7t221559L9LQ9OOTWWJ[[**f4JUVZVaVaVsVsUtu  * 67>>rzzJ&&v.111@)))477vU[[7Y"Vdkk&>&>>{{,,1Dt{{G_G_1_cd1dNN s ##d#;{{,,1N1NRX1XNN g ##d#;--.AB   kknnU+e "[ "[ "[s   \.\
/\rz   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 )az  
        Apply dynamic thresholding to the predicted sample.

        "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

        Args:
            sample (`torch.Tensor`):
                The predicted sample to be thresholded.

        Returns:
            `torch.Tensor`:
                The thresholded sample.
        r   rY   )r)   max)r%   shaper*   r,   float64floatreshaperu   prodabsquantilerd   rD   clamprE   	unsqueezer   )r   rz   r%   
batch_sizechannelsremaining_dims
abs_sampless           r    _threshold_samplez.DPMSolverSinglestepScheduler._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!r"   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 )a  
        Convert sigma values to corresponding timestep values through interpolation.

        Args:
            sigma (`np.ndarray`):
                The sigma value(s) to convert to timestep(s).
            log_sigmas (`np.ndarray`):
                The logarithm of the sigma schedule used for interpolation.

        Returns:
            `np.ndarray`:
                The interpolated timestep value(s) corresponding to the input sigma(s).
        g|=Nr   )axisr   )r   r   )	ru   rp   maximumnewaxiscumsumargmaxclipr   r   )r   r   r   	log_sigmadistslow_idxhigh_idxlowhighwr   s              r    r   z(DPMSolverSinglestepScheduler._sigma_to_t  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"r"   c                 r    | j                   j                  rd|z
  }|}||fS d|dz  dz   dz  z  }||z  }||fS )a(  
        Convert sigma values to alpha_t and sigma_t values.

        Args:
            sigma (`torch.Tensor`):
                The sigma value(s) to convert.

        Returns:
            `Tuple[torch.Tensor, torch.Tensor]`:
                A tuple containing (alpha_t, sigma_t) values.
        r   r   rW   )rd   rL   )r   r   rn   ro   s       r    _sigma_to_alpha_sigma_tz4DPMSolverSinglestepScheduler._sigma_to_alpha_sigma_t  sY     ;;&&%iGG
  E1HqLS01GgoGr"   r   c                    t        | j                  d      r| j                  j                  }nd}t        | j                  d      r| j                  j                  }nd}||n|d   j	                         }||n|d   j	                         }d}t        j                  dd|      }|d|z  z  }|d|z  z  }||||z
  z  z   |z  }	|	S )a  
        Construct the noise schedule as proposed in [Elucidating the Design Space of Diffusion-Based Generative
        Models](https://huggingface.co/papers/2206.00364).

        Args:
            in_sigmas (`torch.Tensor`):
                The input sigma values to be converted.
            num_inference_steps (`int`):
                The number of inference steps to generate the noise schedule for.

        Returns:
            `torch.Tensor`:
                The converted sigma values following the Karras noise schedule.
        r   N	sigma_maxrb   r   g      @r   )hasattrrd   r   r   r   ru   rg   )
r   r   rt   r   r   rhorampmin_inv_rhomax_inv_rhorr   s
             r    r   z/DPMSolverSinglestepScheduler._convert_to_karras  s    $ 4;;,--II4;;,--II!*!6IIbM<N<N<P	!*!6IIaL<M<M<O	{{1a!45AG,AG,k(A BBsJr"   c                    t        | j                  d      r| j                  j                  }nd}t        | j                  d      r| j                  j                  }nd}||n|d   j	                         }||n|d   j	                         }t        j                  t        j                  t        j                  |      t        j                  |      |            }|S )a  
        Construct an exponential noise schedule.

        Args:
            in_sigmas (`torch.Tensor`):
                The input sigma values to be converted.
            num_inference_steps (`int`):
                The number of inference steps to generate the noise schedule for.

        Returns:
            `torch.Tensor`:
                The converted sigma values following an exponential schedule.
        r   Nr   rb   r   )
r   rd   r   r   r   ru   r   rg   r   rp   )r   r   rt   r   r   rr   s         r    r   z4DPMSolverSinglestepScheduler._convert_to_exponential*  s    " 4;;,--II4;;,--II!*!6IIbM<N<N<P	!*!6IIaL<M<M<O	DHHY$7)9LNabcr"   alphabetac           
      (   t        | j                  d      r| j                  j                  }nd}t        | j                  d      r| j                  j                  }nd}||n|d   j	                         }||n|d   j	                         }t        j                  dt        j                  dd|      z
  D cg c]-  }t        j                  j                  j                  |||      / c}D cg c]  }||||z
  z  z    c}      }	|	S c c}w c c}w )a  
        Construct a beta noise schedule as proposed in [Beta Sampling is All You
        Need](https://huggingface.co/papers/2407.12173).

        Args:
            in_sigmas (`torch.Tensor`):
                The input sigma values to be converted.
            num_inference_steps (`int`):
                The number of inference steps to generate the noise schedule for.
            alpha (`float`, *optional*, defaults to `0.6`):
                The alpha parameter for the beta distribution.
            beta (`float`, *optional*, defaults to `0.6`):
                The beta parameter for the beta distribution.

        Returns:
            `torch.Tensor`:
                The converted sigma values following a beta distribution schedule.
        r   Nr   rb   r   r   )r   rd   r   r   r   ru   r   rg   scipystatsr   ppf)
r   r   rt   r   r   r   r   timestepr   rr   s
             r    r   z-DPMSolverSinglestepScheduler._convert_to_betaL  s    0 4;;,--II4;;,--II!*!6IIbM<N<N<P	!*!6IIaL<M<M<O	
 %&Aq:M(N$N  KK$$((5$? SI	$9:;
 s   82D
/Drz   model_outputc                   t        |      dkD  r|d   n|j                  dd      }|t        |      dkD  r|d   }nt        d      |t        ddd       | j                  j
                  d	v rj| j                  j                  d
k(  r\| j                  j                  dv r|ddddf   }| j                  | j                     }| j                  |      \  }}|||z  z
  |z  }	n| j                  j                  dk(  r|}	n| j                  j                  dk(  r9| j                  | j                     }| j                  |      \  }}||z  ||z  z
  }	n^| j                  j                  dk(  r"| j                  | j                     }|||z  z
  }	n#t        d| j                  j                   d      | j                  j                  r| j                  |	      }	|	S | j                  j
                  dk(  rd| j                  j                  d
k(  r'| j                  j                  dv r|ddddf   }
n|}
n| j                  j                  dk(  r9| j                  | j                     }| j                  |      \  }}|||z  z
  |z  }
nu| j                  j                  dk(  r9| j                  | j                     }| j                  |      \  }}||z  ||z  z   }
n#t        d| j                  j                   d      | j                  j                  rE| j                  |   | j                  |   }}|||
z  z
  |z  }	| j                  |	      }	|||	z  z
  |z  }
|
S y)a  
        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.

        Args:
            model_output (`torch.Tensor`):
                The direct output from the learned diffusion model.
            sample (`torch.Tensor`):
                A current instance of a sample created by the diffusion process.

        Returns:
            `torch.Tensor`:
                The converted model output.
        r   r   Nr   /missing `sample` as a required keyword argumentrx   rU   Passing `timesteps` is deprecated and has no effect as model output conversion is now handled via an internal counter `self.step_index`ra   r5   )learnedlearned_ranger   rz   v_predictionflow_predictionzprediction_type given as zo must be one of `epsilon`, `sample`, `v_prediction`, or `flow_prediction` for the DPMSolverSinglestepScheduler.rT   z\ must be one of `epsilon`, `sample`, or `v_prediction` for the DPMSolverSinglestepScheduler.)r   popr&   r   rd   rF   rB   rP   rr   r   r   rC   r   rn   ro   )r   r   rz   argskwargsr   r   rn   ro   x0_predr5   s              r    convert_model_outputz1DPMSolverSinglestepScheduler.convert_model_output|  sT   2 "$i!m47J1M>4y1}a !RSS Z ;;%%)KK{{**i7;;,,0LL#/2A2#6LDOO4#'#?#?#F !Gl$::gE,,8&,,>DOO4#'#?#?#F !F*W|-CC,,0AA++doo6 7\#99 /0K0K/L Ma a 
 {{''009N [['';6{{**i7;;,,0LL*1bqb51G*G,,8DOO4#'#?#?#F !Gl$::gE,,>DOO4#'#?#?#F !L07V3CC /0K0K/L ML L 
 {{''#'<<#94<<;Q!Gg$55@009!Gg$55@N7 7r"   rz   noiser   c          	         t        |      dkD  r|d   n|j                  dd      }t        |      dkD  r|d   n|j                  dd      }|t        |      dkD  r|d   }nt        d      |t        dd	d
       |t        dd	d       | 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(  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 )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   r   rx   rU   r   Passing `prev_timestep` is deprecated and has no effect as model output conversion is now handled via an internal counter `self.step_index`r7   r6   rT   r[          )r   r   r&   r   rr   r   r   r*   rp   rd   rF   r   rm   )r   r   rz   r   r   r   r   r   ro   sigma_srn   alpha_srq   lambda_shx_ts                   r    dpm_solver_first_order_updatez:DPMSolverSinglestepScheduler.dpm_solver_first_order_update  s`   2 "$i!m47J1M#&t9q=QfjjRV6W>4y1}a !RSS Z $ ^
  ;;t':;T[[=Y77@77@99W%		'(::99W%		'(::x;;%%6W$.'UYYr]S=P2QUa1aaC 
 [['';6W$.'UYYq\C=O2PT`1``C 
 [[''+<<$$$7"UYYr]2f<a%))D1H"556,FGEJJsUYYrAv->'>??%GH 
 
r"   model_output_listc          	      4
   t        |      dkD  r|d   n|j                  dd      }t        |      dkD  r|d   n|j                  dd      }|t        |      dkD  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                  |	      \  }}	| 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(  r| j                  j                  dk(  rK||z  |z  |t        j                  |      dz
  z  |z  z
  d|t        j                  |      dz
  z  z  |z  z
  }|S | j                  j                  dk(  rL||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 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   rU   Passing `timestep_list` is deprecated and has no effect as model output conversion is now handled via an internal counter `self.step_index`r   rb   r   r6   r7   r8   rW   r]   rT   r[   r   r   r   r&   r   rr   r   r   r*   rp   rd   rF   rG   r   rm   )r   r   rz   r   r   r   r   r   ro   sigma_s0sigma_s1rn   alpha_s0alpha_s1rq   	lambda_s0	lambda_s1m0m1r   h_0r0D0D1r   s                            r    )singlestep_dpm_solver_second_order_updatezFDPMSolverSinglestepScheduler.singlestep_dpm_solver_second_order_update  s[   4 $'t9q=QfjjRV6W#&t9q=QfjjRV6W>4y1}a !RS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 R 
I ((F2x'61%))QB-#"56"<=599aR=3#6!";c"ABbHI F 
= [['';6{{&&*4x'61%))A,"45;<W		!s(:;<rAB 6 
- ((F2x'61%))A,"45;<599Q<##5":S"@ARGH * 
! [[''+<<$$${{&&*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  
r"   c          	         t        |      dkD  r|d   n|j                  dd      }t        |      dkD  r|d   n|j                  dd      }|t        |      dkD  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\  }}	}
}| 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(  r| j                  j                  dk(  rP||z  |z  |t        j                  |       dz
  z  |z  z
  |t        j                  |       dz
  |z  dz   z  |z  z   }!|!S | 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 | 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
  }!|!S | 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
  }!!S | j                  j                  dk(  r|J | 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 | 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   |dt        j                  d|z        z
  d|z  z   d|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 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   r   rU   r   r   rb   r   r6   g       @r7   r8   r]   rW   rT   r[   r   r   )"r   r   rz   r   r   r   r   r   ro   r   r   sigma_s2rn   r   r   alpha_s2rq   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   6 $'t9q=QfjjRV6W#&t9q=QfjjRV6W>4y1}a !RS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4i"t)#R0D4K BG,;;%%6{{&&*4x'61%))QB-#"56"<=599aR=3#6!";c"ABdJK X 
O ((F2x'61%))QB-#"56"<=599aR=3#6!";c"ABbHI 599aR=3#6#:ad"BS"HIROP L 
A [['';6{{&&*4x'61%))A,"45;<599Q<##5":S"@ATIJ : 
1 ((F2x'61%))A,"45;<599Q<##5":S"@ARGH 599Q<##5#9QT"AC"GHBNO . 
# [[''+<<$$${{&&*4x'%))QB-76A#		$((;";<BC34!8)<#<"JS"PQUYYZ 

3261B+B CCeKL  
 ((F2x'%))QB-76A#		$((;";<BC34!8)<#<"JS"PQUWWX 34!8)<#<q#IdUVh[\_"\_b"bcgiij 

3261B+B CCeK	L  
r"   rz   r   r   r   c                   t        |      dkD  r|d   n|j                  dd      }t        |      dkD  r|d   n|j                  dd      }|t        |      dkD  r|d   }nt        d      |t        |      dkD  r|d   }nt        d	      |t        dd
d       |t        dd
d       |dk(  r| j	                  |d   ||      S |dk(  r| j                  |||      S |dk(  r| j                  |||      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 keyword argumentrU   r   r   rb   r   zOrder must be 1, 2, 3, got )r   r   r&   r   r   r  r  )	r   r   rz   r   r   r   r   r   r   s	            r    singlestep_dpm_solver_updatez9DPMSolverSinglestepScheduler.singlestep_dpm_solver_update  sF   8 $'t9q=QfjjRV6W#&t9q=QfjjRV6W>4y1}a !RSS=4y1}Q !QRR$ ^ $ ^ A:556G6KTZbg5hhaZAABS\bjoAppaZ@@AR[ain@oo:5'BCCr"   r   schedule_timestepsc                    || j                   }||k(  j                         }t        |      dk(  rt        | j                         dz
  }|S t        |      dkD  r|d   j                         }|S |d   j                         }|S )a  
        Find the index for a given timestep in the schedule.

        Args:
            timestep (`int` or `torch.Tensor`):
                The timestep for which to find the index.
            schedule_timesteps (`torch.Tensor`, *optional*):
                The timestep schedule to search in. If `None`, uses `self.timesteps`.

        Returns:
            `int`:
                The index of the timestep in the schedule.
        r   r   )rx   nonzeror   r   )r   r   r  index_candidatesr   s        r    index_for_timestepz/DPMSolverSinglestepScheduler.index_for_timestepE  s      %!%.(:CCE A%T^^,q0J  !"Q&)!,113J  *!,113Jr"   c                     | j                   Vt        |t        j                        r%|j	                  | j
                  j                        }| j                  |      | _        y| j                  | _        y)z
        Initialize the step_index counter for the scheduler.

        Args:
            timestep (`int` or `torch.Tensor`):
                The current timestep for which to initialize the step index.
        N)
r   
isinstancer*   Tensorr   rx   r   r  r}   r~   )r   r   s     r    _init_step_indexz-DPMSolverSinglestepScheduler._init_step_indexh  sW     #(ELL1#;;t~~'<'<=#66x@D#00Dr"   return_dictc                     | j                   t        d      | j                  | j                  |       | 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                     }| j                  |    |dz  }| j                  |    |dk(  r|| _        | j!                  | 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   rb   r[   )	generatorr   r%   r  )prev_sample)rt   r&   r   r   r   r'   rd   rA   ry   rF   r   r   r   r%   r|   rz   r  r}   r   )
r   r   r   rz   r#  r!  r.   r   r   r$  s
             r    stepz!DPMSolverSinglestepScheduler.stepx  s   8 ##+s  ??"!!(+00f0Mt{{//!34 	>A$($6$6q1u$=Dq!	>!-2;;%%):: ""i@S@S[g[m[mE E0   %(0QJE   %(0 A: DK77t{{%u 8 

 	A>!;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.
         )r   rz   r   r   s       r    scale_model_inputz.DPMSolverSinglestepScheduler.scale_model_input  s	     r"   original_samplesc                 *   | 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=| j!                  |      \  }	}
|	|z  |
|z  z   }|S c c}w )a  
        Add noise to the original samples according to the noise schedule at the specified timesteps.

        Args:
            original_samples (`torch.Tensor`):
                The original samples without noise.
            noise (`torch.Tensor`):
                The noise to add to the samples.
            timesteps (`torch.IntTensor`):
                The timesteps at which to add noise to the samples.

        Returns:
            `torch.Tensor`:
                The noisy samples.
        r   mpsr$   r   rb   )rr   r   r   r%   typer*   is_floating_pointrx   r,   r   r  r   r   flattenr   r   r   )r   r)  r   rx   rr   r  r   step_indicesr   rn   ro   noisy_sampless               r    	add_noisez&DPMSolverSinglestepScheduler.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%;%;!<<  77>"22Wu_D _s   Hc                 .    | j                   j                  S N)rd   r<   r   s    r    __len__z$DPMSolverSinglestepScheduler.__len__   s    {{...r"   )r   )NNNN)333333?r5  r3  )NT)0__name__
__module____qualname____doc__r   name_compatiblesr   r
   r   intstrr   ru   ndarrayboolr   r   r{   propertyr   r   r   r   r*   r   r   r  r   r   r   r   r   r   r   r   r  r  r  r  r   r   r   r%  r(  	IntTensorr1  r4  ).0es   00r    r3   r3   Q   s   >@ %>>qAFF>LE $("%.2(",1"%+%"',116*/*/&)+1%*5\M'+%*,1V, V, V, 	V,
 V,  

+V, V, V, V, %*V,  V, V, V,  V, $D>V,  !)!V," "$#V,$ "$%V,& UO'V,( $C=)V,* "+V,,  }-V,. #/V,0 1V, V,p&# &$s) &P     ! !(3 ( $(+/")-j, j, c5<<'(j, UO	j,
 DI&j,Z) ) )X"J ,$ELL $RWR^R^ $N TW \a\h\h F dg..<?.HM.[`.	.h  $	^ll^ 	^ 
^H  $(,>ll> 	>
 %> 
>H  $(,m-m 	m
 %m 
mf  $(,x-x 	x
 %x 
x|  $(,=D-=D 	=D
 =D %=D 
=DB `d c5<</0 FNu||F\ 	 F1*  E8llE8 U\\)*E8 	E8 E8 
%	&E8N %,,  /,,/ ||/ ??	/
 
/b/]# ?s   Mr3   )g+?r   )!r   typingr   r   r   r   r   numpyru   r*   configuration_utilsr	   r
   utilsr   r   r   utils.torch_utilsr   scheduling_utilsr   r   r   scipy.statsr   
get_loggerr6  r   r<  r   r  r1   r3   r'  r"   r    <module>rL     s   "  8 8   A : : , X X 			H	% 5=*4 *4*4 "/2*4 \\	*4Zp/>; p/r"   