
    ic              	       f   d dl Z d dlm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  e       rd dlZ ej4                  e      Ze G d
 de             Z	 	 ddededed   dej@                  fdZ!dej@                  dej@                  fdZ" G d dee      Z#y)    N)	dataclass)ListLiteralOptionalTupleUnion   )ConfigMixinregister_to_config)
BaseOutputis_scipy_availablelogging)randn_tensor   )KarrasDiffusionSchedulersSchedulerMixinc                   X    e Zd ZU dZej
                  ed<   dZeej
                     ed<   y)EulerDiscreteSchedulerOutputaq  
    Output class for the scheduler's `step` function output.

    Args:
        prev_sample (`torch.Tensor` of shape `(batch_size, num_channels, height, width)` for images):
            Computed sample `(x_{t-1})` of previous timestep. `prev_sample` should be used as next model input in the
            denoising loop.
        pred_original_sample (`torch.Tensor` of shape `(batch_size, num_channels, height, width)` for images):
            The predicted denoised sample `(x_{0})` based on the model output from the current timestep.
            `pred_original_sample` can be used to preview progress or for guidance.
    prev_sampleNpred_original_sample)	__name__
__module____qualname____doc__torchTensor__annotations__r   r        x/home/obispo/Crisostomo_bridge/mision_env/lib/python3.12/site-packages/diffusers/schedulers/scheduling_euler_discrete.pyr   r   "   s'    
 37(5<<07r   r   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    r    alpha_bar_fnz)betas_for_alpha_bar.<locals>.alpha_bar_fnP   s-    88QY%/$''9A=>!CCr   r%   c                 2    t        j                  | dz        S )Ng      ()r)   r%   r,   s    r    r.   z)betas_for_alpha_bar.<locals>.alpha_bar_fnU   s    88AI&&r   z"Unsupported alpha_transform_type: r   dtype)
ValueErrorrangeappendminr   tensorfloat32)r!   r"   r#   r.   betasit1t2s           r    betas_for_alpha_barr<   6   s    0 x'	D 
	&	' =>R=STUUE*+ M((!e..S\"-R0@@@(KLM <<U]]33r   r8   c                 (   d| z
  }t        j                  |d      }|j                         }|d   j                         }|d   j                         }||z  }||||z
  z  z  }|dz  }|dd |dd z  }t        j                  |dd |g      }d|z
  } | S )a:  
    Rescales betas to have zero terminal SNR Based on https://huggingface.co/papers/2305.08891 (Algorithm 1)

    Args:
        betas (`torch.Tensor`):
            The betas that the scheduler is being initialized with.

    Returns:
        `torch.Tensor`:
            Rescaled betas with zero terminal SNR.
          ?r   dimr	   r   N)r   cumprodsqrtclonecat)r8   alphasalphas_cumprodalphas_bar_sqrtalphas_bar_sqrt_0alphas_bar_sqrt_T
alphas_bars          r    rescale_zero_terminal_snrrL   d   s     5[F]]6q1N$))+O (*002'+113 ((O (,=@Q,QRRO !!#J^j"o-FYY
1Q01FJELr   c            %          e Zd ZdZeD  cg c]  }|j
                   c}} ZdZe	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 dGde	de
de
ded   d	eeej                  ee
   f      d
ed   ded   dee   dee   dee   dee
   dee
   ded   ded   de	deded   f"d       Zedee
ej*                  f   fd       Zedee	   fd       Zedee	   fd       ZdHd e	ddfd!Zd"ej*                  d#ee
ej*                  f   dej*                  fd$Z	 	 	 	 dId%ee	   d&eeeej8                  f      d'eee	      d(eee
      ddf
d)Zd*ej                  d+ej                  dej                  fd,Zd-ej*                  d%e	dej*                  fd.Zd-ej*                  d%e	dej*                  fd/Z 	 dJd-ej*                  d%e	d0e
d1e
dej*                  f
d2Z!	 dKd#ee
ej*                  f   d3eej*                     de	fd4Z"d#ee
ej*                  f   ddfd5Z#d6d6 e
d7      d8dd9fd:ej*                  d#ee
ej*                  f   d"ej*                  d;e
d<e
d=e
d>e
d?eejH                     d@edee%e&f   fdAZ'dBej*                  dCej*                  d'ej*                  dej*                  fdDZ(d"ej*                  dCej*                  d'ej*                  dej*                  fdEZ)de	fdFZ*yc c}} w )LEulerDiscreteScheduleru"  
    Euler scheduler.

    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 (`Literal["linear", "scaled_linear", "squaredcos_cap_v2"]`, 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`.
        prediction_type (`Literal["epsilon", "sample", "v_prediction"]`, 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).
        interpolation_type (`Literal["linear", "log_linear"]`, defaults to `"linear"`, *optional*):
            The interpolation type to compute intermediate sigmas for the scheduler denoising steps. Should be one of
            `"linear"` or `"log_linear"`.
        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.
        sigma_min (`float`, *optional*):
            The minimum sigma value for the noise schedule. If not provided, defaults to the last sigma in the
            schedule.
        sigma_max (`float`, *optional*):
            The maximum sigma value for the noise schedule. If not provided, defaults to the first sigma in the
            schedule.
        timestep_spacing (`Literal["linspace", "leading", "trailing"]`, defaults to `"linspace"`):
            The way the timesteps should be scaled. Refer to Table 2 of the [Common Diffusion Noise Schedules and
            Sample Steps are Flawed](https://huggingface.co/papers/2305.08891) for more information.
        timestep_type (`Literal["discrete", "continuous"]`, defaults to `"discrete"`):
            The type of timesteps to use. Can be `"discrete"` or `"continuous"`.
        steps_offset (`int`, defaults to 0):
            An offset added to the inference steps, as required by some model families.
        rescale_betas_zero_snr (`bool`, defaults to `False`):
            Whether to rescale the betas to have zero terminal SNR. This enables the model to generate very bright and
            dark samples instead of limiting it to samples with medium brightness. Loosely related to
            [`--offset_noise`](https://github.com/huggingface/diffusers/blob/74fd735eb073eb1d774b1ab4154a0876eb82f055/examples/dreambooth/train_dreambooth.py#L506).
        final_sigmas_type (`Literal["zero", "sigma_min"]`, 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   Nnum_train_timesteps
beta_startbeta_endbeta_schedule)linearscaled_linearsquaredcos_cap_v2trained_betasprediction_type)epsilonsamplev_predictioninterpolation_type)rS   
log_linearuse_karras_sigmasuse_exponential_sigmasuse_beta_sigmas	sigma_min	sigma_maxtimestep_spacing)linspaceleadingtrailingtimestep_type)discrete
continuoussteps_offsetrescale_betas_zero_snrfinal_sigmas_type)zeror`   c                 N   | j                   j                  rt               st        d      t	        | j                   j                  | j                   j
                  | j                   j                  g      dkD  rt        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                         |rt!        | j                        | _        d| j                  z
  | _        t        j$                  | j"                  d      | _        |rd| j&                  d<   d| j&                  z
  | j&                  z  dz  j)                  d      }t+        j                  d|dz
  |t,              d d d   j/                         }t        j0                  |      j3                  t        j                        }d | _        |dk(  r?|dk(  r:t        j6                  |D cg c]  }d|j9                         z   c}      | _        n|| _        t        j<                  |t        j>                  d|j@                        g      | _!        d| _"        || _        |	| _        |
| _        d | _#        d | _$        | jB                  j3                  d      | _!        y c c}w )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.r0   rS   rT         ?r	   rU   z is not implemented for r>   r   r?   g      p>rA   rh   rZ         ?deviceFcpu)%configr_   r   ImportErrorsumr^   r]   r2   r   r6   r7   r8   rc   r<   NotImplementedError	__class__rL   rF   rB   rG   flipnpfloatcopy
from_numpytonum_inference_stepsr   log	timestepsrE   zerosrq   sigmasis_scale_input_called_step_index_begin_index)selfrO   rP   rQ   rR   rV   rW   r[   r]   r^   r_   r`   ra   rb   rf   ri   rj   rk   r   r   sigmas                        r    __init__zEulerDiscreteScheduler.__init__   s   * ;;&&/A/CZ[[++T[[-O-OQUQ\Q\QnQnopstt A  $m5==IDJh&
H>QY^YfYfgDJo-
C3H[chcpcpquvvDJ11,-@ADJ%7OPTP^P^O_&`aa!24::>DJDJJ&#mmDKKQ?! '-D#+++t/B/BBsJPPQRSKK#6#:<OW\]^b`b^bchhj	$$Y/222G	 $(  L(_-N"\\6*R%4%))++=*RSDN&DNiiQv}})M NO%*"!2&<#. kknnU+ +Ss   .L"r&   c                     t        | j                  t              rt        | j                        n| j                  j                         }| j                  j
                  dv r|S |dz  dz   dz  S )a0  
        The standard deviation of the initial noise distribution.

        Returns:
            `float` or `torch.Tensor`:
                The standard deviation of the initial noise distribution, computed based on the maximum sigma value and
                the timestep spacing configuration.
        )rc   re   r	   r   rn   )
isinstancer   listmaxrs   rb   )r   	max_sigmas     r    init_noise_sigmaz'EulerDiscreteScheduler.init_noise_sigma  sY     )34;;(EC$4;;??K\	;;''+CC1q S((r   c                     | j                   S )z
        The index counter for current timestep. It will increase by 1 after each scheduler step.

        Returns:
            `int` or `None`:
                The current step index, or `None` if not initialized.
        )r   r   s    r    
step_indexz!EulerDiscreteScheduler.step_index  s     r   c                     | j                   S )z
        The index for the first timestep. It should be set from pipeline with `set_begin_index` method.

        Returns:
            `int` or `None`:
                The begin index for the scheduler, or `None` if not set.
        r   r   s    r    begin_indexz"EulerDiscreteScheduler.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&EulerDiscreteScheduler.set_begin_index5  s     (r   rY   timestepc                     | j                   | j                  |       | j                  | j                      }||dz  dz   dz  z  }d| _        |S )a9  
        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 to be scaled.
            timestep (`float` or `torch.Tensor`):
                The current timestep in the diffusion chain.

        Returns:
            `torch.Tensor`:
                A scaled input sample, divided by `(sigma**2 + 1) ** 0.5`.
        r	   r   rn   T)r   _init_step_indexr   r   )r   rY   r   r   s       r    scale_model_inputz(EulerDiscreteScheduler.scale_model_input?  sR     ??"!!(+DOO,E1HqLS01%)"r   r~   rq   r   r   c           	         ||t        d      |||t        d      |||t        d      |!| j                  j                  rt        d      |!| j                  j                  rt        d      |!| j                  j                  rt        d      |=| j                  j
                  dk(  r$| j                  j                  d	k(  rt        d
      ||t        |      nt        |      dz
  }|| _        |t        j                  t        j                  d| j                  z
  | j                  z  dz              }t        j                  |      j                  t        j                        }t        j                  |dd D cg c]  }| j                  ||       c}      }n|4t        j                  |      j                  t        j                        }n| j                  j                   dk(  rTt        j"                  d| j                  j$                  dz
  |t        j                        ddd   j'                         }nw| j                  j                   dk(  r| j                  j$                  | j                  z  }t        j(                  d|      |z  j+                         ddd   j'                         j                  t        j                        }|| j                  j,                  z  }n| j                  j                   dk(  r| j                  j$                  | j                  z  }t        j(                  | j                  j$                  d|       j+                         j'                         j                  t        j                        }|dz  }n"t        | j                  j                    d      t        j                  d| j                  z
  | j                  z  dz        }t        j                  |      }| j                  j.                  dk(  r5t        j0                  |t        j(                  dt        |            |      }n| j                  j.                  dk(  rct3        j"                  t        j                  |d         t        j                  |d         |dz         j5                         j7                         }n"t        | j                  j.                   d      | j                  j                  rQ| j9                  || j                        }t        j                  |D cg c]  }| j                  ||       c}      }n| j                  j                  rG| j;                  ||      }t        j                  |D cg c]  }| j                  ||       c}      }n\| j                  j                  rF| j=                  ||      }t        j                  |D cg c]  }| j                  ||       c}      }| 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      j                  t        j                        }t3        jB                  |      jE                  t2        j                  |      }| j                  j
                  dk(  rf| j                  j                  d	k(  rMt3        jF                  |dd D cg c]  }d|j                         z   c}      jE                  |      | _$        nGt3        jB                  |j                  t        j                              jE                  |      | _$        d| _%        d| _&        |jE                  d      | _'        yc c}w c c}w 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`, *optional*):
                The number of diffusion steps used when generating samples with a pre-trained model. If `None`,
                `timesteps` or `sigmas` must be provided.
            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 timesteps schedule. If `None`, timesteps will be generated
                based on the `timestep_spacing` attribute. If `timesteps` is passed, `num_inference_steps` and `sigmas`
                must be `None`, and `timestep_spacing` attribute will be ignored.
            sigmas (`List[float]`, *optional*):
                Custom sigmas used to support arbitrary timesteps schedule. If `None`, timesteps and sigmas will be
                generated based on the relevant scheduler attributes. If `sigmas` is passed, `num_inference_steps` and
                `timesteps` must be `None`, and the timesteps will be generated based on the custom sigmas schedule.
        Nz2Only one of `timesteps` or `sigmas` should be set.zIMust pass exactly one of `num_inference_steps` or `timesteps` or `sigmas.zFCan only pass one of `num_inference_steps` or `timesteps` or `sigmas`.z>Cannot set `timesteps` with `config.use_karras_sigmas = True`.zCCannot set `timesteps` with `config.use_exponential_sigmas = True`.z<Cannot set `timesteps` with `config.use_beta_sigmas = True`.rh   rZ   zpCannot set `timesteps` with `config.timestep_type = 'continuous'` and `config.prediction_type = 'v_prediction'`.r   rn   rA   rc   r   r0   rd   re   zY is not supported. Please make sure to choose one of 'linspace', 'leading' or 'trailing'.rS   r\   zY is not implemented. Please specify interpolation_type to either 'linear' or 'log_linear')	in_sigmasr~   r`   rl   zC`final_sigmas_type` must be one of 'zero', or 'sigma_min', but got )r1   rq   ro   rp   rr   )(r2   rs   r]   r^   r_   rf   rW   lenr~   ry   r   arrayrG   astyper7   _sigma_to_trb   rc   rO   r{   arangeroundri   r[   interpr   r%   numpy_convert_to_karras_convert_to_exponential_convert_to_betark   concatenater|   r}   r   r   r   r   r   )	r   r~   rq   r   r   
log_sigmasr   
step_ratio
sigma_lasts	            r    set_timestepsz$EulerDiscreteScheduler.set_timestepsW  s   4  V%7QRR&9+<hii*	0EI[eff T[[%B%B]^^ T[[%G%Gbcc T[[%@%@[\\!))\9++~= C  &4=4I#i.sSY{]^#6 1t/B/B+BdFYFY*Y^a)a bcJXXf%,,RZZ8FSYZ][]S^!_%$"2"25*"E!_`I $HHY/66rzzB	 ;;//:= "4;;::Q>@S[][e[e!d! DF  [[11Y>!%!@!@DD\D\!\J 1&9:ZGNNPQUSUQUV[[]ddegeoeop  !9!99I[[11Z?!%!@!@4C[C[![J 4;;#B#BA
{SZZ\aacjjkmkukuv  NI$;;778  9R  S  XXD$7$7 74;N;NNSVVWFJ{{--99bii3v;.GP//<?vbz(:BFF6!9<MObefOfgkkmssu {{556 70 0 
 {{,,006W[WoWo0pHHW]%^ed&6&6uj&I%^_	3355\o5pHHW]%^ed&6&6uj&I%^_	,,..Uh.iHHW]%^ed&6&6uj&I%^_	{{,,; 4#6#6q#99T=P=PQR=SSX[[
..&8
 YZ^ZeZeZwZwYxy  ^^Vj\$:;BB2::NF!!&),,5==,P ;;$$49T9TXf9f"\\6RUSU;*W%4%))++=*WX[[ci[jDN"--i.>.>rzz.JKNNV\N]DN ii&[ "`\ &_ &_ &_" +Xs   _-_2_7<_<
`r   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   )	ry   r   maximumnewaxiscumsumargmaxclipshapereshape)r   r   r   	log_sigmadistslow_idxhigh_idxlowhighwr-   s              r    r   z"EulerDiscreteScheduler._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   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`   Nra   rA   r   g      @r   )hasattrrs   r`   ra   itemry   rc   )
r   r   r~   r`   ra   rhorampmin_inv_rhomax_inv_rhor   s
             r    r   z)EulerDiscreteScheduler._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`   Nra   rA   r   )
r   rs   r`   ra   r   ry   r%   rc   r)   r   )r   r   r~   r`   ra   r   s         r    r   z.EulerDiscreteScheduler._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`   Nra   rA   r   r   )r   rs   r`   ra   r   ry   r   rc   scipystatsr   ppf)
r   r   r~   r   r   r`   ra   r   r   r   s
             r    r   z'EulerDiscreteScheduler._convert_to_betaI  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schedule_timestepsc                     || j                   }||k(  j                         }t        |      dkD  rdnd}||   j                         S )ak  
        Find the index of a given timestep in the timestep schedule.

        Args:
            timestep (`float` or `torch.Tensor`):
                The timestep value to find in the schedule.
            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. For the very first step, returns the second index if
                multiple matches exist to avoid skipping a sigma when starting mid-schedule (e.g., for image-to-image).
        r   r   )r   nonzeror   r   )r   r   r   indicesposs        r    index_for_timestepz)EulerDiscreteScheduler.index_for_timestepy  sN    " %!%%1::< w<!#as|  ""r   c                     | j                   Vt        |t        j                        r%|j	                  | j
                  j                        }| j                  |      | _        y| j                  | _        y)z
        Initialize the step index for the scheduler based on the given timestep.

        Args:
            timestep (`float` or `torch.Tensor`):
                The current timestep to initialize the step index from.
        N)
r   r   r   r   r}   r   rq   r   r   r   )r   r   s     r    r   z'EulerDiscreteScheduler._init_step_index  sW     #(ELL1#;;t~~'<'<=#66x@D#00Dr           infr>   Tmodel_outputs_churns_tmins_tmaxs_noise	generatorreturn_dictc
                    t        |t        t        j                  t        j                  f      rt        d      | j                  st        j                  d       | j                  | j                  |       |j                  t        j                        }| j                  | j                     }
||
cxk  r|k  r(n n%t        |t        | j                        dz
  z  d      nd}|
|dz   z  }|dkD  rFt!        |j"                  |j$                  |j&                  |      }||z  }|||dz  |
dz  z
  d	z  z  z   }| j(                  j*                  d
k(  s| j(                  j*                  dk(  r|}n}| j(                  j*                  dk(  r	|||z  z
  }n[| j(                  j*                  dk(  r||
 |
dz  dz   d	z  z  z  ||
dz  dz   z  z   }n#t        d| j(                  j*                   d      ||z
  |z  }| j                  | j                  dz      |z
  }|||z  z   }|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 diffusion
        process from the learned model outputs (most often the predicted noise).

        Args:
            model_output (`torch.Tensor`):
                The direct output from the learned diffusion model.
            timestep (`float` or `torch.Tensor`):
                The current discrete timestep in the diffusion chain.
            sample (`torch.Tensor`):
                A current instance of a sample created by the diffusion process.
            s_churn (`float`, *optional*, defaults to `0.0`):
                Stochasticity parameter that controls the amount of noise added during sampling. Higher values increase
                randomness.
            s_tmin (`float`, *optional*, defaults to `0.0`):
                Minimum timestep threshold for applying stochasticity. Only timesteps above this value will have noise
                added.
            s_tmax (`float`, *optional*, defaults to `inf`):
                Maximum timestep threshold for applying stochasticity. Only timesteps below this value will have noise
                added.
            s_noise (`float`, *optional*, defaults to `1.0`):
                Scaling factor for noise added to the sample.
            generator (`torch.Generator`, *optional*):
                A random number generator for reproducible sampling.
            return_dict (`bool`, *optional*, defaults to `True`):
                Whether or not to return a [`~schedulers.scheduling_euler_discrete.EulerDiscreteSchedulerOutput`] or
                tuple.

        Returns:
            [`~schedulers.scheduling_euler_discrete.EulerDiscreteSchedulerOutput`] or `tuple`:
                If `return_dict` is `True`, [`~schedulers.scheduling_euler_discrete.EulerDiscreteSchedulerOutput`] is
                returned, otherwise a tuple is returned where the first element is the sample tensor and the second
                element is the predicted original sample.
        zPassing integer indices (e.g. from `enumerate(timesteps)`) as timesteps to `EulerDiscreteScheduler.step()` is not supported. Make sure to pass one of the `scheduler.timesteps` as a timestep.zThe `scale_model_input` function should be called before `step` to ensure correct denoising. See `StableDiffusionPipeline` for a usage example.r   g4y?r   r   )r1   rq   r   r	   rn   original_samplerY   rX   rZ   zprediction_type given as z, must be one of `epsilon`, or `v_prediction`)r   r   )r   intr   	IntTensor
LongTensorr2   r   loggerwarningr   r   r}   r7   r   r5   r   r   r   r1   rq   rs   rW   r   r   )r   r   r   rY   r   r   r   r   r   r   r   gamma	sigma_hatnoiseepsr   
derivativedtr   s                      r    stepzEulerDiscreteScheduler.step  sk   ^ heoou7G7G HIG  ))NNE
 ??"!!(+ 5==)DOO,EKuE^X^E^Gs4;;/!34jAdgUQY'	19 "",*<*<\EXEXdmE '/CcY\E1H%<$DDDF
 ;;&&*;;t{{?Z?Z^f?f#/ [[((I5#)I,D#D [[((N:#/E6UAX\c<Q3Q#RV\`egh`hkl`lVm#n +DKK,G,G+HHtu 
 33y@
[[1,-	9zB. "nn\%7%78 	A$ 
 ,Znoor   original_samplesr   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 )am  
        Add noise to the original samples according to the noise schedule at the specified timesteps.

        Args:
            original_samples (`torch.Tensor`):
                The original samples to which noise will be added.
            noise (`torch.Tensor`):
                The noise tensor to add to the original samples.
            timesteps (`torch.Tensor`):
                The timesteps at which to add noise, determining the noise level from the schedule.

        Returns:
            `torch.Tensor`:
                The noisy samples with added noise scaled according to the timestep schedule.
        )rq   r1   mpsr0   r   rA   )r   r}   rq   r1   typer   is_floating_pointr   r7   r   r   r   r   flattenr   	unsqueeze)
r   r   r   r   r   r   r-   step_indicesr   noisy_sampless
             r    	add_noisez EulerDiscreteScheduler.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                    t        |t              s4t        |t        j                        st        |t        j                        rt        d      |j                  j                  dk(  rvt        j                  |      ra| j                  j                  |j                  t        j                        }|j                  |j                  t        j                        }n@| j                  j                  |j                        }|j                  |j                        }|D cg c]  }| j                  ||       }}| j                  j                  |      }||   dz  }|j                         }t        |j                         t        |j                         k  r=|j#                  d      }t        |j                         t        |j                         k  r=d||   z
  dz  }	|	j                         }	t        |	j                         t        |j                         k  r=|	j#                  d      }	t        |	j                         t        |j                         k  r=||z  |	|z  z
  }
|
S c c}w )a  
        Compute the velocity prediction for the given sample and noise at the specified timesteps.

        This method implements the velocity prediction used in v-prediction models, which predicts a linear combination
        of the sample and noise.

        Args:
            sample (`torch.Tensor`):
                The input sample for which to compute the velocity.
            noise (`torch.Tensor`):
                The noise tensor corresponding to the sample.
            timesteps (`torch.Tensor`):
                The timesteps at which to compute the velocity.

        Returns:
            `torch.Tensor`:
                The velocity prediction computed as `sqrt(alpha_prod) * noise - sqrt(1 - alpha_prod) * sample`.
        zPassing integer indices (e.g. from `enumerate(timesteps)`) as timesteps to `EulerDiscreteScheduler.get_velocity()` is not supported. Make sure to pass one of the `scheduler.timesteps` as a timestep.r   r0   rn   rA   r   )r   r   r   r   r   r2   rq   r   r   r   r}   r7   r   rG   r   r   r   r   )r   rY   r   r   r   r-   r   rG   sqrt_alpha_prodsqrt_one_minus_alpha_prodvelocitys              r    get_velocityz#EulerDiscreteScheduler.get_velocityK  s   ( y#&)U__5)U%5%56G  ==&5+B+B9+M!%!2!26==!2!V!V]]%--HI!%!2!26==!A!V]]3IPYZ1//3EFZZ,,//7(6#=)113/''(3v||+<<-77;O /''(3v||+<< &')E%E#$M!$=$E$E$G!+112S5FF(A(K(KB(O% +112S5FF #U*-F-OO [s   #I)c                 .    | j                   j                  S N)rs   rO   r   s    r    __len__zEulerDiscreteScheduler.__len__  s    {{...r   )i  g-C6?g{Gz?rS   NrX   rS   FFFNNrc   rg   r   Frl   )r   )NNNN)333333?r   r   )+r   r   r   r   r   name_compatiblesorderr   r   rz   r   r   r   ry   ndarrayr   boolr   propertyr   r   r   r   r   r   r   strrq   r   r   r   r   r   r   r   	Generatorr   r   r   r   r   r   ).0es   00r    rN   rN      s   5n %>>qAFF>LE $("QYBFHQ>F,116*/%)%)GQ;E',:@%H, H, H, 	H,
 MNH,  bjj$u+&= >?H, !!DEH, $$:;H, $D>H, !)H, "$H, E?H, E?H, ""CDH, 78H,  !H," !%#H,$ ##67%H, H,T )%u||(;"< ) )  HSM     !Xc] ! !(3 (t ( eU\\FY@Z _d_k_k 4 .259)-(,C'%c]C' sELL012C' DI&	C'
 e%C' 
C'J" " "

 "J$ELL $s $W\WcWc $N TW \a\h\h D dg..<?.HM.[`.	.b bf#eU\\12#HPQVQ]Q]H^#	#<1uell/B)C 1 1( e/3 spllsp u||+,sp 	sp
 sp sp sp sp EOO,sp sp 
+U2	3spj.,,. ||. <<	.
 
.`55<< 5 5QVQ]Q] 5bgbnbn 5n/ /E ?s   KrN   )g+?r$   )$r)   dataclassesr   typingr   r   r   r   r   r   ry   r   configuration_utilsr
   r   utilsr   r   r   utils.torch_utilsr   scheduling_utilsr   r   scipy.statsr   
get_loggerr   r   r   r   rz   r   r<   rL   rN   r   r   r    <module>r     s     ! 8 8   A ; ; , G 			H	% 8: 8 8( 5=*4 *4*4 "/2*4 \\	*4\!U\\ !ell !H{/^[ {/r   