






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_(						lowercase__					):



     """simple docstring"""



     __snake_case						:							torch.FloatTensor
     __snake_case						:							Optional[torch.FloatTensor]       			=None





def 		A_			(		lowercase_					,       lowercase_=0.9_9_9					,       lowercase_="cosine"					,       )							->Dict:







 """simple docstring"""

 if alpha_transform_type == "cosine":

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

 elif alpha_transform_type == "exp":

  def alpha_bar_fn(lowercase_	):
   return math.exp(t * -1_2.0	)

 else:
  raise ValueError(f'''Unsupported alpha_tranform_type: {alpha_transform_type}'''	)

 SCREAMING_SNAKE_CASE							  =						[]
 for i in range(lowercase_	):
  SCREAMING_SNAKE_CASE							  =						i / num_diffusion_timesteps
  SCREAMING_SNAKE_CASE							  =						(i + 1) / num_diffusion_timesteps
  betas.append(min(1 - alpha_bar_fn(lowercase_	) / alpha_bar_fn(lowercase_	)					,       lowercase_	)	)
 return torch.tensor(lowercase_					,       dtype=torch.floataa	)
class 					a_(						lowercase__	,    lowercase__					):



     """simple docstring"""



     __snake_case						:							Dict       			=[e.name for e in KarrasDiffusionSchedulers]
     __snake_case						:							str       			=1





     @register_to_config
     def __init__(						self			:					List[Any]       ,       lowerCAmelCase__			:					int = 1_0_0_0       ,       lowerCAmelCase__			:					float = 0.00_01       ,       lowerCAmelCase__			:					float = 0.02       ,       lowerCAmelCase__			:					str = "linear"       ,       lowerCAmelCase__			:					Optional[Union[np.ndarray, List[float]]] = None       ,       lowerCAmelCase__			:					str = "epsilon"       ,       lowerCAmelCase__			:					str = "linear"       ,       lowerCAmelCase__			:					Optional[bool] = False       ,       lowerCAmelCase__			:					str = "linspace"       ,       lowerCAmelCase__			:					int = 0       ,       )    ->					Optional[Any]:

      """simple docstring"""
      if trained_betas is not None:
       SCREAMING_SNAKE_CASE							  =						torch.tensor(lowerCAmelCase__       ,       dtype=torch.floataa)
      elif beta_schedule == "linear":
       SCREAMING_SNAKE_CASE							  =						torch.linspace(lowerCAmelCase__       ,       lowerCAmelCase__       ,       lowerCAmelCase__       ,       dtype=torch.floataa)
      elif beta_schedule == "scaled_linear":
       # this schedule is very specific to the latent diffusion model.
       SCREAMING_SNAKE_CASE							  =						(
           torch.linspace(beta_start**0.5       ,       beta_end**0.5       ,       lowerCAmelCase__       ,       dtype=torch.floataa) ** 2
       )
      elif beta_schedule == "squaredcos_cap_v2":
       # Glide cosine schedule
       SCREAMING_SNAKE_CASE							  =						betas_for_alpha_bar(lowerCAmelCase__)
      else:
       raise NotImplementedError(f'''{beta_schedule} does is not implemented for {self.__class__}''')

      SCREAMING_SNAKE_CASE							  =						1.0 - self.betas
      SCREAMING_SNAKE_CASE							  =						torch.cumprod(self.alphas       ,       dim=0)

      SCREAMING_SNAKE_CASE							  =						np.array(((1 - self.alphas_cumprod) / self.alphas_cumprod) ** 0.5)
      SCREAMING_SNAKE_CASE							  =						np.concatenate([sigmas[::-1], [0.0]]).astype(np.floataa)
      SCREAMING_SNAKE_CASE							  =						torch.from_numpy(lowerCAmelCase__)

      # setable values
      SCREAMING_SNAKE_CASE							  =						None
      SCREAMING_SNAKE_CASE							  =						np.linspace(0       ,       num_train_timesteps - 1       ,       lowerCAmelCase__       ,       dtype=lowerCAmelCase__)[::-1].copy()
      SCREAMING_SNAKE_CASE							  =						torch.from_numpy(lowerCAmelCase__)
      SCREAMING_SNAKE_CASE							  =						False
      SCREAMING_SNAKE_CASE							  =						use_karras_sigmas





     @property
     def   __UpperCamelCase		(						self			:					List[Any])    ->					List[Any]:

      """simple docstring"""
      # standard deviation of the initial noise distribution
      if self.config.timestep_spacing in ["linspace", "trailing"]:
       return self.sigmas.max()

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





     def   __UpperCamelCase		(						self			:					List[Any]       ,       lowerCAmelCase__			:					torch.FloatTensor       ,       lowerCAmelCase__			:					Union[float, torch.FloatTensor])    ->					torch.FloatTensor:

      """simple docstring"""
      if isinstance(lowerCAmelCase__       ,       torch.Tensor):
       SCREAMING_SNAKE_CASE							  =						timestep.to(self.timesteps.device)
      SCREAMING_SNAKE_CASE							  =						(self.timesteps == timestep).nonzero().item()
      SCREAMING_SNAKE_CASE							  =						self.sigmas[step_index]

      SCREAMING_SNAKE_CASE							  =						sample / ((sigma**2 + 1) ** 0.5)

      SCREAMING_SNAKE_CASE							  =						True
      return sample





     def   __UpperCamelCase		(						self			:					str       ,       lowerCAmelCase__			:					int       ,       lowerCAmelCase__			:					Union[str, torch.device] = None)    ->					List[str]:

      """simple docstring"""
      SCREAMING_SNAKE_CASE							  =						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":
       SCREAMING_SNAKE_CASE							  =						np.linspace(0       ,       self.config.num_train_timesteps - 1       ,       lowerCAmelCase__       ,       dtype=lowerCAmelCase__)[
           ::-1
       ].copy()
      elif self.config.timestep_spacing == "leading":
       SCREAMING_SNAKE_CASE							  =						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
       SCREAMING_SNAKE_CASE							  =						(np.arange(0       ,       lowerCAmelCase__) * step_ratio).round()[::-1].copy().astype(lowerCAmelCase__)
       timesteps += self.config.steps_offset
      elif self.config.timestep_spacing == "trailing":
       SCREAMING_SNAKE_CASE							  =						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
       SCREAMING_SNAKE_CASE							  =						(np.arange(self.config.num_train_timesteps       ,       0       ,       -step_ratio)).round().copy().astype(lowerCAmelCase__)
       timesteps -= 1
      else:
       raise ValueError(
           f'''{self.config.timestep_spacing} is not supported. Please make sure to choose one of \'linspace\', \'leading\' or \'trailing\'.''')

      SCREAMING_SNAKE_CASE							  =						np.array(((1 - self.alphas_cumprod) / self.alphas_cumprod) ** 0.5)
      SCREAMING_SNAKE_CASE							  =						np.log(lowerCAmelCase__)

      if self.config.interpolation_type == "linear":
       SCREAMING_SNAKE_CASE							  =						np.interp(lowerCAmelCase__       ,       np.arange(0       ,       len(lowerCAmelCase__))       ,       lowerCAmelCase__)
      elif self.config.interpolation_type == "log_linear":
       SCREAMING_SNAKE_CASE							  =						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:
       SCREAMING_SNAKE_CASE							  =						self._convert_to_karras(in_sigmas=lowerCAmelCase__       ,       num_inference_steps=self.num_inference_steps)
       SCREAMING_SNAKE_CASE							  =						np.array([self._sigma_to_t(lowerCAmelCase__       ,       lowerCAmelCase__) for sigma in sigmas])

      SCREAMING_SNAKE_CASE							  =						np.concatenate([sigmas, [0.0]]).astype(np.floataa)
      SCREAMING_SNAKE_CASE							  =						torch.from_numpy(lowerCAmelCase__).to(device=lowerCAmelCase__)
      if str(lowerCAmelCase__).startswith('mps'):
       # mps does not support float64
       SCREAMING_SNAKE_CASE							  =						torch.from_numpy(lowerCAmelCase__).to(lowerCAmelCase__       ,       dtype=torch.floataa)
      else:
       SCREAMING_SNAKE_CASE							  =						torch.from_numpy(lowerCAmelCase__).to(device=lowerCAmelCase__)





     def   __UpperCamelCase		(						self			:					List[str]       ,       lowerCAmelCase__			:					Union[str, Any]       ,       lowerCAmelCase__			:					List[Any])    ->					Optional[Any]:

      """simple docstring"""
      # get log sigma
      SCREAMING_SNAKE_CASE							  =						np.log(lowerCAmelCase__)

      # get distribution
      SCREAMING_SNAKE_CASE							  =						log_sigma - log_sigmas[:, np.newaxis]

      # get sigmas range
      SCREAMING_SNAKE_CASE							  =						np.cumsum((dists >= 0)       ,       axis=0).argmax(axis=0).clip(max=log_sigmas.shape[0] - 2)
      SCREAMING_SNAKE_CASE							  =						low_idx + 1

      SCREAMING_SNAKE_CASE							  =						log_sigmas[low_idx]
      SCREAMING_SNAKE_CASE							  =						log_sigmas[high_idx]

      # interpolate sigmas
      SCREAMING_SNAKE_CASE							  =						(low - log_sigma) / (low - high)
      SCREAMING_SNAKE_CASE							  =						np.clip(lowerCAmelCase__       ,       0       ,       1)

      # transform interpolation to time range
      SCREAMING_SNAKE_CASE							  =						(1 - w) * low_idx + w * high_idx
      SCREAMING_SNAKE_CASE							  =						t.reshape(sigma.shape)
      return t





     def   __UpperCamelCase		(						self			:					List[str]       ,       lowerCAmelCase__			:					torch.FloatTensor       ,       lowerCAmelCase__			:					List[Any])    ->					torch.FloatTensor:

      """simple docstring"""
      SCREAMING_SNAKE_CASE							  =						in_sigmas[-1].item()
      SCREAMING_SNAKE_CASE							  =						in_sigmas[0].item()

      SCREAMING_SNAKE_CASE							  =						7.0  # 7.0 is the value used in the paper
      SCREAMING_SNAKE_CASE							  =						np.linspace(0       ,       1       ,       lowerCAmelCase__)
      SCREAMING_SNAKE_CASE							  =						sigma_min ** (1 / rho)
      SCREAMING_SNAKE_CASE							  =						sigma_max ** (1 / rho)
      SCREAMING_SNAKE_CASE							  =						(max_inv_rho + ramp * (min_inv_rho - max_inv_rho)) ** rho
      return sigmas





     def   __UpperCamelCase		(						self			:					Union[str, Any]       ,       lowerCAmelCase__			:					torch.FloatTensor       ,       lowerCAmelCase__			:					Union[float, torch.FloatTensor]       ,       lowerCAmelCase__			:					torch.FloatTensor       ,       lowerCAmelCase__			:					float = 0.0       ,       lowerCAmelCase__			:					float = 0.0       ,       lowerCAmelCase__			:					float = float('inf')       ,       lowerCAmelCase__			:					float = 1.0       ,       lowerCAmelCase__			:					Optional[torch.Generator] = None       ,       lowerCAmelCase__			:					bool = True       ,       )    ->					Union[EulerDiscreteSchedulerOutput, Tuple]:

      """simple docstring"""

      if (
          isinstance(lowerCAmelCase__       ,       lowerCAmelCase__)
          or isinstance(lowerCAmelCase__       ,       torch.IntTensor)
          or isinstance(lowerCAmelCase__       ,       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(lowerCAmelCase__       ,       torch.Tensor):
       SCREAMING_SNAKE_CASE							  =						timestep.to(self.timesteps.device)

      SCREAMING_SNAKE_CASE							  =						(self.timesteps == timestep).nonzero().item()
      SCREAMING_SNAKE_CASE							  =						self.sigmas[step_index]

      SCREAMING_SNAKE_CASE							  =						min(s_churn / (len(self.sigmas) - 1)       ,       2**0.5 - 1) if s_tmin <= sigma <= s_tmax else 0.0

      SCREAMING_SNAKE_CASE							  =						randn_tensor(
          model_output.shape       ,       dtype=model_output.dtype       ,       device=model_output.device       ,       generator=lowerCAmelCase__)

      SCREAMING_SNAKE_CASE							  =						noise * s_noise
      SCREAMING_SNAKE_CASE							  =						sigma * (gamma + 1)

      if gamma > 0:
       SCREAMING_SNAKE_CASE							  =						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":
       SCREAMING_SNAKE_CASE							  =						model_output
      elif self.config.prediction_type == "epsilon":
       SCREAMING_SNAKE_CASE							  =						sample - sigma_hat * model_output
      elif self.config.prediction_type == "v_prediction":
       # * c_out + input * c_skip
       SCREAMING_SNAKE_CASE							  =						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
      SCREAMING_SNAKE_CASE							  =						(sample - pred_original_sample) / sigma_hat

      SCREAMING_SNAKE_CASE							  =						self.sigmas[step_index + 1] - sigma_hat

      SCREAMING_SNAKE_CASE							  =						sample + derivative * dt

      if not return_dict:
       return (prev_sample,)

      return EulerDiscreteSchedulerOutput(prev_sample=lowerCAmelCase__       ,       pred_original_sample=lowerCAmelCase__)





     def   __UpperCamelCase		(						self			:					Tuple       ,       lowerCAmelCase__			:					torch.FloatTensor       ,       lowerCAmelCase__			:					torch.FloatTensor       ,       lowerCAmelCase__			:					torch.FloatTensor       ,       )    ->					torch.FloatTensor:

      """simple docstring"""
      # Make sure sigmas and timesteps have the same device and dtype as original_samples
      SCREAMING_SNAKE_CASE							  =						self.sigmas.to(device=original_samples.device       ,       dtype=original_samples.dtype)
      if original_samples.device.type == "mps" and torch.is_floating_point(lowerCAmelCase__):
       # mps does not support float64
       SCREAMING_SNAKE_CASE							  =						self.timesteps.to(original_samples.device       ,       dtype=torch.floataa)
       SCREAMING_SNAKE_CASE							  =						timesteps.to(original_samples.device       ,       dtype=torch.floataa)
      else:
       SCREAMING_SNAKE_CASE							  =						self.timesteps.to(original_samples.device)
       SCREAMING_SNAKE_CASE							  =						timesteps.to(original_samples.device)

      SCREAMING_SNAKE_CASE							  =						[(schedule_timesteps == t).nonzero().item() for t in timesteps]

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

      SCREAMING_SNAKE_CASE							  =						original_samples + noise * sigma
      return noisy_samples





     def __len__(						self			:					str)    ->					str:

      """simple docstring"""
      return self.config.num_train_timesteps












import random
from typing import List, Optional, Union

import numpy as np
import torch

from ..state import AcceleratorState
from .constants import CUDA_DISTRIBUTED_TYPES
from .dataclasses import DistributedType, RNGType
from .imports import is_npu_available, is_tpu_available, is_xpu_available


if is_tpu_available(check_device=False):
      import torch_xla.core.xla_model as xm





def 		A_			(		lowercase_					,       lowercase_ = False	)							->Union[str, Any]:







 """simple docstring"""

 if device_specific:
  seed += AcceleratorState().process_index
 random.seed(lowercase_	)
 np.random.seed(lowercase_	)
 torch.manual_seed(lowercase_	)
 if is_xpu_available():
  torch.xpu.manual_seed_all(lowercase_	)
 elif is_npu_available():
  torch.npu.manual_seed_all(lowercase_	)
 else:
  torch.cuda.manual_seed_all(lowercase_	)
 # ^^ safe to call this function even if cuda is not available
 if is_tpu_available():
  xm.set_rng_state(lowercase_	)





def 		A_			(		lowercase_ = None					,       lowercase_ = None	)							->Optional[Any]:







 """simple docstring"""

 if rng_type == RNGType.TORCH:
  SCREAMING_SNAKE_CASE							  =						torch.get_rng_state()
 elif rng_type == RNGType.CUDA:
  SCREAMING_SNAKE_CASE							  =						torch.cuda.get_rng_state()
 elif rng_type == RNGType.XLA:
  assert is_tpu_available(), "Can't synchronize XLA seeds on an environment without TPUs."
  SCREAMING_SNAKE_CASE							  =						torch.tensor(xm.get_rng_state()	)
 elif rng_type == RNGType.NPU:
  assert is_npu_available(), "Can't synchronize NPU seeds on an environment without NPUs."
  SCREAMING_SNAKE_CASE							  =						torch.npu.get_rng_state()
 elif rng_type == RNGType.XPU:
  assert is_xpu_available(), "Can't synchronize XPU seeds on an environment without XPUs."
  SCREAMING_SNAKE_CASE							  =						torch.xpu.get_rng_state()
 elif rng_type == RNGType.GENERATOR:
  assert generator is not None, "Need a generator to synchronize its seed."
  SCREAMING_SNAKE_CASE							  =						generator.get_state()

 # Broadcast the rng state from device 0 to other devices
 SCREAMING_SNAKE_CASE							  =						AcceleratorState()
 if state.distributed_type == DistributedType.TPU:
  SCREAMING_SNAKE_CASE							  =						rng_state.to(xm.xla_device()	)
  xm.collective_broadcast([rng_state]	)
  xm.mark_step()
  SCREAMING_SNAKE_CASE							  =						rng_state.cpu()
 elif (
     state.distributed_type in CUDA_DISTRIBUTED_TYPES
     or state.distributed_type == DistributedType.MULTI_NPU
     or state.distributed_type == DistributedType.MULTI_XPU
 ):
  SCREAMING_SNAKE_CASE							  =						rng_state.to(state.device	)
  torch.distributed.broadcast(lowercase_					,       0	)
  SCREAMING_SNAKE_CASE							  =						rng_state.cpu()
 elif state.distributed_type == DistributedType.MULTI_CPU:
  torch.distributed.broadcast(lowercase_					,       0	)

 # Set the broadcast rng state
 if rng_type == RNGType.TORCH:
  torch.set_rng_state(lowercase_	)
 elif rng_type == RNGType.CUDA:
  torch.cuda.set_rng_state(lowercase_	)
 elif rng_type == RNGType.NPU:
  torch.npu.set_rng_state(lowercase_	)
 elif rng_type == RNGType.XPU:
  torch.xpu.set_rng_state(lowercase_	)
 elif rng_type == RNGType.XLA:
  xm.set_rng_state(rng_state.item()	)
 elif rng_type == RNGType.GENERATOR:
  generator.set_state(lowercase_	)





def 		A_			(		lowercase_					,       lowercase_ = None	)							->str:







 """simple docstring"""

 for rng_type in rng_types:
  synchronize_rng_state(RNGType(lowercase_	)					,       generator=lowercase_	)




