






"""simple docstring"""





import math
from dataclasses import dataclass
from typing import List, Optional, Tuple, Union

import numpy as np
import torch

from ..configuration_utils import ConfigMixin, register_to_config
from ..utils import BaseOutput, logging, randn_tensor
from .scheduling_utils import KarrasDiffusionSchedulers, SchedulerMixin


UpperCamelCase					=     logging.get_logger(__name__)  # pylint: disable=invalid-name







@dataclass
# Copied from diffusers.schedulers.scheduling_ddpm.DDPMSchedulerOutput with DDPM->EulerDiscrete
class 						_a  (		a__       ):





   '''simple docstring'''






   UpperCamelCase__     	=							42
   UpperCamelCase__     	=							None







def 							A(    snake_case_		,  snake_case_=0.9_99		,  snake_case_="cosine"		,  ):
       """simple docstring"""





       if alpha_transform_type == "cosine":

              def alpha_bar_fn(snake_case_						):
                     return math.cos((t + 0.0_08) / 1.0_08 * math.pi / 2						) ** 2

       elif alpha_transform_type == "exp":

              def alpha_bar_fn(snake_case_						):
                     return math.exp(t * -12.0						)

       else:
              raise ValueError(F"""Unsupported alpha_tranform_type: {alpha_transform_type}"""						)

       lowercase__:							Optional[Any]         =     []
       for i in range(__A						):
              lowercase__:							str         =     i / num_diffusion_timesteps
              lowercase__:							Union[str, Any]         =     (i + 1) / num_diffusion_timesteps
              betas.append(min(1 - alpha_bar_fn(__A						) / alpha_bar_fn(__A						)		,  __A						)						)
       return torch.tensor(__A		,  dtype=torch.floataa						)







class 						_a  (		a__							,	a__       ):





   '''simple docstring'''






   UpperCamelCase__     	=							[e.name for e in KarrasDiffusionSchedulers]
   UpperCamelCase__     	=							1





   @register_to_config
   def __init__(       self					, UpperCAmelCase_ = 1_000					, UpperCAmelCase_ = 0.00_01					, UpperCAmelCase_ = 0.02					, UpperCAmelCase_ = "linear"					, UpperCAmelCase_ = None					, UpperCAmelCase_ = "epsilon"					, UpperCAmelCase_ = "linear"					, UpperCAmelCase_ = False					, UpperCAmelCase_ = "linspace"					, UpperCAmelCase_ = 0					, )			->   int:




          '''simple docstring'''




          if trained_betas is not None:
                 lowercase__:							Optional[int]         =     torch.tensor(UpperCAmelCase_					, dtype=torch.floataa)
          elif beta_schedule == "linear":
                 lowercase__:							List[str]         =     torch.linspace(UpperCAmelCase_					, UpperCAmelCase_					, UpperCAmelCase_					, dtype=torch.floataa)
          elif beta_schedule == "scaled_linear":
                 # this schedule is very specific to the latent diffusion model.
                 lowercase__:							Union[str, Any]         =     (
                     torch.linspace(beta_start**0.5					, beta_end**0.5					, UpperCAmelCase_					, dtype=torch.floataa) ** 2
                 )
          elif beta_schedule == "squaredcos_cap_v2":
                 # Glide cosine schedule
                 lowercase__:							str         =     betas_for_alpha_bar(UpperCAmelCase_)
          else:
                 raise NotImplementedError(F"""{beta_schedule} does is not implemented for {self.__class__}""")

          lowercase__:							int         =     1.0 - self.betas
          lowercase__:							int         =     torch.cumprod(self.alphas					, dim=0)

          lowercase__:							str         =     np.array(((1 - self.alphas_cumprod) / self.alphas_cumprod) ** 0.5)
          lowercase__:							Union[str, Any]         =     np.concatenate([sigmas[::-1], [0.0]]).astype(np.floataa)
          lowercase__:							Dict         =     torch.from_numpy(UpperCAmelCase_)

          # setable values
          lowercase__:							List[str]         =     None
          lowercase__:							List[str]         =     np.linspace(0					, num_train_timesteps - 1					, UpperCAmelCase_					, dtype=UpperCAmelCase_)[::-1].copy()
          lowercase__:							List[Any]         =     torch.from_numpy(UpperCAmelCase_)
          lowercase__:							Optional[Any]         =     False
          lowercase__:							str         =     use_karras_sigmas





   @property
   def __lowercase							(       self)			->   List[str]:




          '''simple docstring'''




          if self.config.timestep_spacing in ["linspace", "trailing"]:
                 return self.sigmas.max()

          return (self.sigmas.max() ** 2 + 1) ** 0.5





   def __lowercase							(       self					, UpperCAmelCase_					, UpperCAmelCase_)			->   List[str]:




          '''simple docstring'''




          if isinstance(UpperCAmelCase_					, torch.Tensor):
                 lowercase__:							Optional[Any]         =     timestep.to(self.timesteps.device)
          lowercase__:							Tuple         =     (self.timesteps == timestep).nonzero().item()
          lowercase__:							Dict         =     self.sigmas[step_index]

          lowercase__:							Dict         =     sample / ((sigma**2 + 1) ** 0.5)

          lowercase__:							Union[str, Any]         =     True
          return sample





   def __lowercase							(       self					, UpperCAmelCase_					, UpperCAmelCase_ = None)			->   Optional[int]:




          '''simple docstring'''




          lowercase__:							List[str]         =     num_inference_steps

          # "linspace", "leading", "trailing" corresponds to annotation of Table 2. of https://arxiv.org/abs/2305.08891
          if self.config.timestep_spacing == "linspace":
                 lowercase__:							Dict         =     np.linspace(0					, self.config.num_train_timesteps - 1					, UpperCAmelCase_					, dtype=UpperCAmelCase_)[
                     ::-1
                 ].copy()
          elif self.config.timestep_spacing == "leading":
                 lowercase__:							Optional[int]         =     self.config.num_train_timesteps // self.num_inference_steps
                 # creates integer timesteps by multiplying by ratio
                 # casting to int to avoid issues when num_inference_step is power of 3
                 lowercase__:							Any         =     (np.arange(0					, UpperCAmelCase_) * step_ratio).round()[::-1].copy().astype(UpperCAmelCase_)
                 timesteps += self.config.steps_offset
          elif self.config.timestep_spacing == "trailing":
                 lowercase__:							Dict         =     self.config.num_train_timesteps / self.num_inference_steps
                 # creates integer timesteps by multiplying by ratio
                 # casting to int to avoid issues when num_inference_step is power of 3
                 lowercase__:							int         =     (np.arange(self.config.num_train_timesteps					, 0					, -step_ratio)).round().copy().astype(UpperCAmelCase_)
                 timesteps -= 1
          else:
                 raise ValueError(
                     F"""{self.config.timestep_spacing} is not supported. Please make sure to choose one of \'linspace\', \'leading\' or \'trailing\'.""")

          lowercase__:							Optional[int]         =     np.array(((1 - self.alphas_cumprod) / self.alphas_cumprod) ** 0.5)
          lowercase__:							Tuple         =     np.log(UpperCAmelCase_)

          if self.config.interpolation_type == "linear":
                 lowercase__:							Tuple         =     np.interp(UpperCAmelCase_					, np.arange(0					, len(UpperCAmelCase_))					, UpperCAmelCase_)
          elif self.config.interpolation_type == "log_linear":
                 lowercase__:							List[Any]         =     torch.linspace(np.log(sigmas[-1])					, np.log(sigmas[0])					, num_inference_steps + 1).exp()
          else:
                 raise ValueError(
                     F"""{self.config.interpolation_type} is not implemented. Please specify interpolation_type to either"""
                     " 'linear' or 'log_linear'")

          if self.use_karras_sigmas:
                 lowercase__:							Any         =     self._convert_to_karras(in_sigmas=UpperCAmelCase_					, num_inference_steps=self.num_inference_steps)
                 lowercase__:							int         =     np.array([self._sigma_to_t(UpperCAmelCase_					, UpperCAmelCase_) for sigma in sigmas])

          lowercase__:							Union[str, Any]         =     np.concatenate([sigmas, [0.0]]).astype(np.floataa)
          lowercase__:							List[Any]         =     torch.from_numpy(UpperCAmelCase_).to(device=UpperCAmelCase_)
          if str(UpperCAmelCase_).startswith("mps"):
                 # mps does not support float64
                 lowercase__:							str         =     torch.from_numpy(UpperCAmelCase_).to(UpperCAmelCase_					, dtype=torch.floataa)
          else:
                 lowercase__:							List[Any]         =     torch.from_numpy(UpperCAmelCase_).to(device=UpperCAmelCase_)





   def __lowercase							(       self					, UpperCAmelCase_					, UpperCAmelCase_)			->   Dict:




          '''simple docstring'''




          lowercase__:							Dict         =     np.log(UpperCAmelCase_)

          # get distribution
          lowercase__:							Optional[int]         =     log_sigma - log_sigmas[:, np.newaxis]

          # get sigmas range
          lowercase__:							Union[str, Any]         =     np.cumsum((dists >= 0)					, axis=0).argmax(axis=0).clip(max=log_sigmas.shape[0] - 2)
          lowercase__:							Dict         =     low_idx + 1

          lowercase__:							int         =     log_sigmas[low_idx]
          lowercase__:							Any         =     log_sigmas[high_idx]

          # interpolate sigmas
          lowercase__:							Tuple         =     (low - log_sigma) / (low - high)
          lowercase__:							Dict         =     np.clip(UpperCAmelCase_					, 0					, 1)

          # transform interpolation to time range
          lowercase__:							Optional[int]         =     (1 - w) * low_idx + w * high_idx
          lowercase__:							Optional[int]         =     t.reshape(sigma.shape)
          return t





   def __lowercase							(       self					, UpperCAmelCase_					, UpperCAmelCase_)			->   str:




          '''simple docstring'''




          lowercase__:							List[str]         =     in_sigmas[-1].item()
          lowercase__:							List[str]         =     in_sigmas[0].item()

          lowercase__:							List[str]         =     7.0  # 7.0 is the value used in the paper
          lowercase__:							Any         =     np.linspace(0					, 1					, UpperCAmelCase_)
          lowercase__:							str         =     sigma_min ** (1 / rho)
          lowercase__:							Any         =     sigma_max ** (1 / rho)
          lowercase__:							Union[str, Any]         =     (max_inv_rho + ramp * (min_inv_rho - max_inv_rho)) ** rho
          return sigmas





   def __lowercase							(       self					, UpperCAmelCase_					, UpperCAmelCase_					, UpperCAmelCase_					, UpperCAmelCase_ = 0.0					, UpperCAmelCase_ = 0.0					, UpperCAmelCase_ = float("inf")					, UpperCAmelCase_ = 1.0					, UpperCAmelCase_ = None					, UpperCAmelCase_ = True					, )			->   Optional[int]:




          '''simple docstring'''




          if (
              isinstance(UpperCAmelCase_					, UpperCAmelCase_)
              or isinstance(UpperCAmelCase_					, torch.IntTensor)
              or isinstance(UpperCAmelCase_					, torch.LongTensor)
          ):
                 raise ValueError(
                     (
                         "Passing 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."
                     )					, )

          if not self.is_scale_input_called:
                 logger.warning(
                     "The `scale_model_input` function should be called before `step` to ensure correct denoising. "
                     "See `StableDiffusionPipeline` for a usage example.")

          if isinstance(UpperCAmelCase_					, torch.Tensor):
                 lowercase__:							str         =     timestep.to(self.timesteps.device)

          lowercase__:							Any         =     (self.timesteps == timestep).nonzero().item()
          lowercase__:							int         =     self.sigmas[step_index]

          lowercase__:							List[str]         =     min(s_churn / (len(self.sigmas) - 1)					, 2**0.5 - 1) if s_tmin <= sigma <= s_tmax else 0.0

          lowercase__:							Optional[int]         =     randn_tensor(
              model_output.shape					, dtype=model_output.dtype					, device=model_output.device					, generator=UpperCAmelCase_)

          lowercase__:							Any         =     noise * s_noise
          lowercase__:							int         =     sigma * (gamma + 1)

          if gamma > 0:
                 lowercase__:							Optional[Any]         =     sample + eps * (sigma_hat**2 - sigma**2) ** 0.5

          # 1. compute predicted original sample (x_0) from sigma-scaled predicted noise
          # NOTE: "original_sample" should not be an expected prediction_type but is left in for
          # backwards compatibility
          if self.config.prediction_type == "original_sample" or self.config.prediction_type == "sample":
                 lowercase__:							str         =     model_output
          elif self.config.prediction_type == "epsilon":
                 lowercase__:							List[str]         =     sample - sigma_hat * model_output
          elif self.config.prediction_type == "v_prediction":
                 # * c_out + input * c_skip
                 lowercase__:							List[str]         =     model_output * (-sigma / (sigma**2 + 1) ** 0.5) + (sample / (sigma**2 + 1))
          else:
                 raise ValueError(
                     F"""prediction_type given as {self.config.prediction_type} must be one of `epsilon`, or `v_prediction`""")

          # 2. Convert to an ODE derivative
          lowercase__:							Optional[Any]         =     (sample - pred_original_sample) / sigma_hat

          lowercase__:							int         =     self.sigmas[step_index + 1] - sigma_hat

          lowercase__:							List[Any]         =     sample + derivative * dt

          if not return_dict:
                 return (prev_sample,)

          return EulerDiscreteSchedulerOutput(prev_sample=UpperCAmelCase_					, pred_original_sample=UpperCAmelCase_)





   def __lowercase							(       self					, UpperCAmelCase_					, UpperCAmelCase_					, UpperCAmelCase_					, )			->   int:




          '''simple docstring'''




          lowercase__:							int         =     self.sigmas.to(device=original_samples.device					, dtype=original_samples.dtype)
          if original_samples.device.type == "mps" and torch.is_floating_point(UpperCAmelCase_):
                 # mps does not support float64
                 lowercase__:							List[str]         =     self.timesteps.to(original_samples.device					, dtype=torch.floataa)
                 lowercase__:							Tuple         =     timesteps.to(original_samples.device					, dtype=torch.floataa)
          else:
                 lowercase__:							List[Any]         =     self.timesteps.to(original_samples.device)
                 lowercase__:							Optional[int]         =     timesteps.to(original_samples.device)

          lowercase__:							Tuple         =     [(schedule_timesteps == t).nonzero().item() for t in timesteps]

          lowercase__:							Any         =     sigmas[step_indices].flatten()
          while len(sigma.shape) < len(original_samples.shape):
                 lowercase__:							Optional[Any]         =     sigma.unsqueeze(-1)

          lowercase__:							List[str]         =     original_samples + noise * sigma
          return noisy_samples





   def __len__(       self)			->   List[str]:




          '''simple docstring'''




          return self.config.num_train_timesteps










'''simple docstring'''







from __future__ import annotations

from enum import Enum, unique
from typing import TypeVar

# Create a generic variable that can be 'Enum', or any subclass.
a__    :   Optional[Any]								=			TypeVar('T', bound='Enum')
@unique
class    lowercase_	(       a__  ):
    __UpperCAmelCase       =      80
    __UpperCAmelCase       =      70
    __UpperCAmelCase       =      60
    __UpperCAmelCase       =      50
    __UpperCAmelCase       =      40
    __UpperCAmelCase       =      30
    __UpperCAmelCase       =      20
    __UpperCAmelCase       =      10

@unique
class    lowercase_	(       a__  ):
    __UpperCAmelCase       =      24
    __UpperCAmelCase       =      21
    __UpperCAmelCase       =      18
    __UpperCAmelCase       =      15
    __UpperCAmelCase       =      12
    __UpperCAmelCase       =      9
    __UpperCAmelCase       =      6
    __UpperCAmelCase       =      3
    __UpperCAmelCase       =      2
    __UpperCAmelCase       =      1
    __UpperCAmelCase       =      -1
    __UpperCAmelCase       =      -2
    __UpperCAmelCase       =      -3
    __UpperCAmelCase       =      -6
    __UpperCAmelCase       =      -9
    __UpperCAmelCase       =      -12
    __UpperCAmelCase       =      -15
    __UpperCAmelCase       =      -18
    __UpperCAmelCase       =      -21
    __UpperCAmelCase       =      -24


    @classmethod
    def   __a				(	cls       ):
          return {unit.name: unit.value for unit in cls if unit.value > 0}


    @classmethod
    def   __a				(	cls       ):
          return {unit.name: unit.value for unit in cls if unit.value < 0}







def _UpperCamelCase			(	__A       )				->						str:


      '''simple docstring'''



      UpperCamelCase__      =							SIUnit.get_positive() if value > 0 else SIUnit.get_negative()
      for name_prefix, value_prefix in prefixes.items():
            UpperCamelCase__      =							value / (10**value_prefix)
            if numerical_part > 1:
                  return F'''{numerical_part!s} {name_prefix}'''
      return str(__A       )







def _UpperCamelCase			(	__A       )				->						str:


      '''simple docstring'''



      for prefix in BinaryUnit:
            UpperCamelCase__      =							value / (2**prefix.value)
            if numerical_part > 1:
                  return F'''{numerical_part!s} {prefix.name}'''
      return str(__A       )


if __name__ == "__main__":
  import doctest

  doctest.testmod()





