
    bi                        d dl Z d dlmZ d dlmZmZmZmZ d dlZ	d dl
Z
ddlmZmZ ddlmZmZmZ ddlmZ dd	lmZmZ  e       rd dlZ ej2                  e      Ze G d
 de             Z	 	 ddZd Z G d dee      Zy)    N)	dataclass)List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        i/home/cdr/jupyterlab/.venv/lib/python3.12/site-packages/diffusers/schedulers/scheduling_euler_discrete.pyr   r   "   s'    
 37(5<<07r   r   c           
      $   |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 )a  
    Create a beta schedule that discretizes the given alpha_t_bar function, which defines the cumulative product of
    (1-beta) over time from t = [0,1].

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


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

    Returns:
        betas (`np.ndarray`): the betas used by the scheduler to step the model outputs
    cosinec                 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_fnO   s-    88QY%/$''9A=>!CCr   expc                 2    t        j                  | dz        S )Ng      ()r#   r)   r&   s    r   r(   z)betas_for_alpha_bar.<locals>.alpha_bar_fnT   s    88AI&&r   z"Unsupported alpha_transform_type: r   dtype)
ValueErrorrangeappendminr   tensorfloat32)num_diffusion_timestepsmax_betaalpha_transform_typer(   betasit1t2s           r   betas_for_alpha_barr:   6   s    . x'	D 
	&	' =>R=STUUE*+ M((!e..S\"-R0@@@(KLM <<U]]33r   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)r6   alphasalphas_cumprodalphas_bar_sqrtalphas_bar_sqrt_0alphas_bar_sqrt_T
alphas_bars          r   rescale_zero_terminal_snrrJ   c   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            $       d   e Zd ZdZeD  cg c]  }|j
                   c}} ZdZe	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d>de	de
de
dedeeej                  ee
   f      d	ed
edee   dee   dee   dee
   dee
   dedede	dedef"d       Zed        Zed        Zed        Zd?de	fdZdej2                  dee
ej2                  f   dej2                  fdZ	 	 	 	 d@de	d eeej6                  f   d!eee	      d"eee
      fd#Zd$ Zd%ej2                  dej2                  fd&Zd%ej2                  de	dej2                  fd'Z	 dAd%ej2                  de	d(e
d)e
dej2                  f
d*Z dBd+Z!d, Z"d-d- e
d.      d/dd0fd1ej2                  dee
ej2                  f   dej2                  d2e
d3e
d4e
d5e
d6eejF                     d7edee$e%f   fd8Z&d9ej2                  d:ej2                  d!ej2                  dej2                  fd;Z'dej2                  d:ej2                  d!ej2                  dej2                  fd<Z(d= Z)yc c}} w )CEulerDiscreteScheduleruB  
    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 (`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` or `scaled_linear`.
        trained_betas (`np.ndarray`, *optional*):
            Pass an array of betas directly to the constructor to bypass `beta_start` and `beta_end`.
        prediction_type (`str`, defaults to `epsilon`, *optional*):
            Prediction type of the scheduler function; can be `epsilon` (predicts the noise of the diffusion process),
            `sample` (directly predicts the noisy sample`) or `v_prediction` (see section 2.4 of [Imagen
            Video](https://imagen.research.google/video/paper.pdf) paper).
        interpolation_type(`str`, defaults to `"linear"`, *optional*):
            The interpolation type to compute intermediate sigmas for the scheduler denoising steps. Should be on 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.
        timestep_spacing (`str`, defaults to `"linspace"`):
            The way the timesteps should be scaled. Refer to Table 2 of the [Common Diffusion Noise Schedules and
            Sample Steps are Flawed](https://huggingface.co/papers/2305.08891) for more information.
        steps_offset (`int`, defaults to 0):
            An offset added to the inference steps, as required by some model families.
        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 (`str`, defaults to `"zero"`):
            The final `sigma` value for the noise schedule during the sampling process. If `"sigma_min"`, the final
            sigma is the same as the last sigma in the training schedule. If `zero`, the final sigma is set to 0.
    r   Nnum_train_timesteps
beta_startbeta_endbeta_scheduletrained_betasprediction_typeinterpolation_typeuse_karras_sigmasuse_exponential_sigmasuse_beta_sigmas	sigma_min	sigma_maxtimestep_spacingtimestep_typesteps_offsetrescale_betas_zero_snrfinal_sigmas_typec                 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.r+   linearscaled_linear      ?r   squaredcos_cap_v2z is not implemented for r<   r   r=   g      p>r?   
continuousv_prediction      ?deviceFcpu)%configrV   r   ImportErrorsumrU   rT   r-   r   r1   r2   r6   linspacer:   NotImplementedError	__class__rJ   rD   r@   rE   flipnpfloatcopy
from_numpytonum_inference_stepsr   log	timestepsrC   zerosrg   sigmasis_scale_input_called_step_index_begin_index)selfrM   rN   rO   rP   rQ   rR   rS   rT   rU   rV   rW   rX   rY   rZ   r[   r\   r]   ry   rw   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"c                     t        | j                  t              rt        | j                        n| j                  j                         }| j                  j
                  dv r|S |dz  dz   dz  S )N)rl   trailingr   r   ra   )
isinstancery   listmaxri   rY   )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 )zg
        The index counter for current timestep. It will increase 1 after each scheduler step.
        )r{   r}   s    r   
step_indexz!EulerDiscreteScheduler.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"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`):
                The begin index for the scheduler.
        Nr   )r}   r   s     r   set_begin_indexz&EulerDiscreteScheduler.set_begin_index  s     (r   sampletimestepreturnc                     | j                   | j                  |       | j                  | j                      }||dz  dz   dz  z  }d| _        |S )a   
        Ensures interchangeability with schedulers that need to scale the denoising model input depending on the
        current timestep. Scales the denoising model input by `(sigma**2 + 1) ** 0.5` to match the Euler algorithm.

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

        Returns:
            `torch.Tensor`:
                A scaled input sample.
        r   r   ra   T)r   _init_step_indexry   rz   )r}   r   r   r~   s       r   scale_model_inputz(EulerDiscreteScheduler.scale_model_input'  sR     ??"!!(+DOO,E1HqLS01%)"r   ru   rg   rw   ry   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`):
                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 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 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`.rc   rd   zpCannot set `timesteps` with `config.timestep_type = 'continuous'` and `config.prediction_type = 'v_prediction'`.r   ra   r?   rl   r   r+   leadingr   zY is not supported. Please make sure to choose one of 'linspace', 'leading' or 'trailing'.r_   
log_linearzY is not implemented. Please specify interpolation_type to either 'linear' or 'log_linear')	in_sigmasru   rW   zerozC`final_sigmas_type` must be one of 'zero', or 'sigma_min', but got )r,   rg   re   rf   rh   )(r-   ri   rT   rU   rV   rZ   rR   lenru   rp   rv   arrayrE   astyper2   _sigma_to_trY   rl   rM   rr   arangeroundr[   rS   interpr   r)   numpy_convert_to_karras_convert_to_exponential_convert_to_betar]   concatenaters   rt   r   rw   r{   r|   ry   )	r}   ru   rg   rw   ry   
log_sigmasr~   
step_ratio
sigma_lasts	            r   set_timestepsz$EulerDiscreteScheduler.set_timesteps?  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<_<
`c                    t        j                  t        j                  |d            }||d d t         j                  f   z
  }t        j                  |dk\  d      j                  d      j                  |j                  d   dz
        }|dz   }||   }||   }||z
  ||z
  z  }	t        j                  |	dd      }	d|	z
  |z  |	|z  z   }
|
j                  |j                        }
|
S )Ng|=r   )axisr   )r   r   )	rp   rv   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 )z6Constructs the noise schedule of Karras et al. (2022).rW   NrX   r?   r   g      @r   )hasattrri   rW   rX   itemrp   rl   )
r}   r   ru   rW   rX   rhorampmin_inv_rhomax_inv_rhory   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 )z)Constructs an exponential noise schedule.rW   NrX   r?   r   )
r   ri   rW   rX   r   rp   r)   rl   r#   rv   )r}   r   ru   rW   rX   ry   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 )zJFrom "Beta Sampling is All You Need" [arXiv:2407.12173] (Lee et. al, 2024)rW   NrX   r?   r   r   )r   ri   rW   rX   r   rp   r   rl   scipystatsr   ppf)
r}   r   ru   r   r   rW   rX   r   r   ry   s
             r   r   z'EulerDiscreteScheduler._convert_to_beta  s     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c                     || j                   }||k(  j                         }t        |      dkD  rdnd}||   j                         S )Nr   r   )rw   nonzeror   r   )r}   r   schedule_timestepsindicesposs        r   index_for_timestepz)EulerDiscreteScheduler.index_for_timestep*  sL    %!%%1::< w<!#as|  ""r   c                     | j                   Vt        |t        j                        r%|j	                  | j
                  j                        }| j                  |      | _        y | j                  | _        y N)
r   r   r   r   rt   rw   rg   r   r{   r|   )r}   r   s     r   r   z'EulerDiscreteScheduler._init_step_index8  sU    #(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 )aI  
        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 learned diffusion model.
            timestep (`float`):
                The current discrete timestep in the diffusion chain.
            sample (`torch.Tensor`):
                A current instance of a sample created by the diffusion process.
            s_churn (`float`):
            s_tmin  (`float`):
            s_tmax  (`float`):
            s_noise (`float`, defaults to 1.0):
                Scaling factor for noise added to the sample.
            generator (`torch.Generator`, *optional*):
                A random number generator.
            return_dict (`bool`):
                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.
        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   )r,   rg   r   r   ra   original_sampler   epsilonrd   zprediction_type given as z, must be one of `epsilon`, or `v_prediction`)r   r   )r   intr   	IntTensor
LongTensorr-   rz   loggerwarningr   r   rt   r2   ry   r0   r   r   r   r,   rg   ri   rR   r{   r   )r}   r   r   r   r   r   r   r   r   r   r~   gamma	sigma_hatnoiseepsr   
derivativedtr   s                      r   stepzEulerDiscreteScheduler.step@  sk   P 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 )N)rg   r,   mpsr+   r   r?   )ry   rt   rg   r,   typer   is_floating_pointrw   r2   r   r   r   r   flattenr   	unsqueeze)
r}   r   r   rw   ry   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 )NzPassing 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   r+   ra   r?   r   )r   r   r   r   r   r-   rg   r   r   rw   rt   r2   r   rE   r   r   r   r   )r}   r   r   rw   r   r'   r   rE   sqrt_alpha_prodsqrt_one_minus_alpha_prodvelocitys              r   get_velocityz#EulerDiscreteScheduler.get_velocity  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 r   )ri   rM   r   s    r   __len__zEulerDiscreteScheduler.__len__  s    {{...r   )i  g-C6?g{Gz?r_   Nr   r_   FFFNNrl   discreter   Fr   )r   )NNNN)333333?r   r   )*r   r   r   r   r   name_compatiblesorderr
   r   rq   strr   r   rp   ndarrayr   boolr   propertyr   r   r   r   r   r   r   rg   r   r   r   r   r   r   r   	Generatorr   r   r   r   r   r   ).0es   00r   rL   rL      s   -^ %>>qAFF>LE $("%BF("*,116*/%)%) *'',!'%H, H, H, 	H,
 H,  bjj$u+&= >?H, H,  H, $D>H, !)H, "$H, E?H, E?H, H, H,  !H," !%#H,$ %H, H,T ) )     ! !(3 ( eU\\FY@Z _d_k_k 4 $(+/)-(,C' C' c5<<'(C' DI&	C'
 e%C'J0ELL RWR^R^ 4 TW \a\h\h , dg<?HM[`	>#1 e/3 lplllp u||+,lp 	lp
 lp lp lp lp EOO,lp lp 
+U2	3lp\,, || <<	
 
B#5<< # #QVQ]Q] #bgbnbn #J/{ ?s   H,rL   )g+?r!   ) r#   dataclassesr   typingr   r   r   r   r   rp   r   configuration_utilsr	   r
   utilsr   r   r   utils.torch_utilsr   scheduling_utilsr   r   scipy.statsr   
get_loggerr   r   r   r:   rJ   rL   r   r   r   <module>r     s     ! / /   A ; ; , G 			H	% 8: 8 8( !)4Z!Hn	/^[ n	/r   