




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


_lowerCAmelCase  :				Any						=				logging.get_logger(__name__)  # pylint: disable=invalid-name
@dataclass
# Copied from diffusers.schedulers.scheduling_ddpm.DDPMSchedulerOutput with DDPM->EulerDiscrete
class      _UpperCamelCase (			lowerCAmelCase						):
      UpperCAmelCase_            =						42
      UpperCAmelCase_            =						None



def   lowerCAmelCase						(						_lowerCAmelCase							:				Dict  ,							_lowerCAmelCase							:				Tuple=0.999  ,							_lowerCAmelCase							:				Any="cosine"  ,							):




 """simple docstring"""







 if alpha_transform_type == "cosine":

  def alpha_bar_fn(_lowerCAmelCase							:				str		):
   return math.cos((t + 0.008) / 1.008 * math.pi / 2		) ** 2

 elif alpha_transform_type == "exp":

  def alpha_bar_fn(_lowerCAmelCase							:				List[str]		):
   return math.exp(t * -12.0		)

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

 UpperCAmelCase__								=  []
 for i in range(_lowerCAmelCase		):
  UpperCAmelCase__								=  i / num_diffusion_timesteps
  UpperCAmelCase__								=  (i + 1) / num_diffusion_timesteps
  betas.append(min(1 - alpha_bar_fn(_lowerCAmelCase		) / alpha_bar_fn(_lowerCAmelCase		)  ,							_lowerCAmelCase		)		)
 return torch.tensor(_lowerCAmelCase  ,							dtype=torch.floataa		)


class      _UpperCamelCase (			lowerCAmelCase		,    lowerCAmelCase						):
      UpperCAmelCase_            =						[e.name for e in KarrasDiffusionSchedulers]
      UpperCAmelCase_            =						1
      @register_to_config
      def __init__(     self				:Any	, lowerCamelCase				:int = 1000	, 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	, )       ->     Union[str, Any]:
       if trained_betas is not None:
        UpperCAmelCase__								=  torch.tensor(lowerCamelCase	, dtype=torch.floataa )
       elif beta_schedule == "linear":
        UpperCAmelCase__								=  torch.linspace(lowerCamelCase	, lowerCamelCase	, lowerCamelCase	, dtype=torch.floataa )
       elif beta_schedule == "scaled_linear":
        # this schedule is very specific to the latent diffusion model.
        UpperCAmelCase__								=  (
            torch.linspace(beta_start**0.5	, beta_end**0.5	, lowerCamelCase	, dtype=torch.floataa ) ** 2
        )
       elif beta_schedule == "squaredcos_cap_v2":
        # Glide cosine schedule
        UpperCAmelCase__								=  betas_for_alpha_bar(lowerCamelCase )
       else:
        raise NotImplementedError(f'''{beta_schedule} does is not implemented for {self.__class__}''' )

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

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

       # setable values
       UpperCAmelCase__								=  None
       UpperCAmelCase__								=  np.linspace(0	, num_train_timesteps - 1	, lowerCamelCase	, dtype=lowerCamelCase )[::-1].copy()
       UpperCAmelCase__								=  torch.from_numpy(lowerCamelCase )
       UpperCAmelCase__								=  False
       UpperCAmelCase__								=  use_karras_sigmas
      @property
      def 		UpperCAmelCase_  (     self				:Optional[int] )       ->     Union[str, Any]:
       # 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				:str	, lowerCamelCase				:torch.FloatTensor	, lowerCamelCase				:Union[float, torch.FloatTensor] )       ->     torch.FloatTensor:
       if isinstance(lowerCamelCase	, torch.Tensor ):
        UpperCAmelCase__								=  timestep.to(self.timesteps.device )
       UpperCAmelCase__								=  (self.timesteps == timestep).nonzero().item()
       UpperCAmelCase__								=  self.sigmas[step_index]

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

       UpperCAmelCase__								=  True
       return sample
      def 		UpperCAmelCase_  (     self				:Any	, lowerCamelCase				:int	, lowerCamelCase				:Union[str, torch.device] = None )       ->     Any:
       UpperCAmelCase__								=  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":
        UpperCAmelCase__								=  np.linspace(0	, self.config.num_train_timesteps - 1	, lowerCamelCase	, dtype=lowerCamelCase )[
            ::-1
        ].copy()
       elif self.config.timestep_spacing == "leading":
        UpperCAmelCase__								=  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
        UpperCAmelCase__								=  (np.arange(0	, lowerCamelCase ) * step_ratio).round()[::-1].copy().astype(lowerCamelCase )
        timesteps += self.config.steps_offset
       elif self.config.timestep_spacing == "trailing":
        UpperCAmelCase__								=  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
        UpperCAmelCase__								=  (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\'.''' )

       UpperCAmelCase__								=  np.array(((1 - self.alphas_cumprod) / self.alphas_cumprod) ** 0.5 )
       UpperCAmelCase__								=  np.log(lowerCamelCase )

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

       UpperCAmelCase__								=  np.concatenate([sigmas, [0.0]] ).astype(np.floataa )
       UpperCAmelCase__								=  torch.from_numpy(lowerCamelCase ).to(device=lowerCamelCase )
       if str(lowerCamelCase ).startswith("mps" ):
        # mps does not support float64
        UpperCAmelCase__								=  torch.from_numpy(lowerCamelCase ).to(lowerCamelCase	, dtype=torch.floataa )
       else:
        UpperCAmelCase__								=  torch.from_numpy(lowerCamelCase ).to(device=lowerCamelCase )
      def 		UpperCAmelCase_  (     self				:Any	, lowerCamelCase				:List[str]	, lowerCamelCase				:Any )       ->     Dict:
       # get log sigma
       UpperCAmelCase__								=  np.log(lowerCamelCase )

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

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

       UpperCAmelCase__								=  log_sigmas[low_idx]
       UpperCAmelCase__								=  log_sigmas[high_idx]

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

       # transform interpolation to time range
       UpperCAmelCase__								=  (1 - w) * low_idx + w * high_idx
       UpperCAmelCase__								=  t.reshape(sigma.shape )
       return t
      def 		UpperCAmelCase_  (     self				:int	, lowerCamelCase				:torch.FloatTensor	, lowerCamelCase				:Optional[int] )       ->     torch.FloatTensor:
       UpperCAmelCase__								=  in_sigmas[-1].item()
       UpperCAmelCase__								=  in_sigmas[0].item()

       UpperCAmelCase__								=  7.0  # 7.0 is the value used in the paper
       UpperCAmelCase__								=  np.linspace(0	, 1	, lowerCamelCase )
       UpperCAmelCase__								=  sigma_min ** (1 / rho)
       UpperCAmelCase__								=  sigma_max ** (1 / rho)
       UpperCAmelCase__								=  (max_inv_rho + ramp * (min_inv_rho - max_inv_rho)) ** rho
       return sigmas
      def 		UpperCAmelCase_  (     self				: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]:

       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 ):
        UpperCAmelCase__								=  timestep.to(self.timesteps.device )

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

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

       UpperCAmelCase__								=  randn_tensor(
           model_output.shape	, dtype=model_output.dtype	, device=model_output.device	, generator=lowerCamelCase )

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

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

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

       UpperCAmelCase__								=  sample + derivative * dt

       if not return_dict:
        return (prev_sample,)

       return EulerDiscreteSchedulerOutput(prev_sample=lowerCamelCase	, pred_original_sample=lowerCamelCase )
      def 		UpperCAmelCase_  (     self				:Dict	, lowerCamelCase				:torch.FloatTensor	, lowerCamelCase				:torch.FloatTensor	, lowerCamelCase				:torch.FloatTensor	, )       ->     torch.FloatTensor:
       # Make sure sigmas and timesteps have the same device and dtype as original_samples
       UpperCAmelCase__								=  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
        UpperCAmelCase__								=  self.timesteps.to(original_samples.device	, dtype=torch.floataa )
        UpperCAmelCase__								=  timesteps.to(original_samples.device	, dtype=torch.floataa )
       else:
        UpperCAmelCase__								=  self.timesteps.to(original_samples.device )
        UpperCAmelCase__								=  timesteps.to(original_samples.device )

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

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

       UpperCAmelCase__								=  original_samples + noise * sigma
       return noisy_samples







      def __len__(     self				:Union[str, Any] )       ->     int:
       return self.config.num_train_timesteps











from __future__ import annotations



def   lowerCAmelCase						(						_lowerCAmelCase							:				int  ,							_lowerCAmelCase							:				int  ,							_lowerCAmelCase							:				int		):




 """simple docstring"""







 assert (
     c % greatest_common_divisor(_lowerCAmelCase  ,							_lowerCAmelCase		) == 0
 )  # greatest_common_divisor(a,b) function implemented below
 ((UpperCAmelCase__)	,	(UpperCAmelCase__)	,	(UpperCAmelCase__))								=  extended_gcd(_lowerCAmelCase  ,							_lowerCAmelCase		)  # extended_gcd(a,b) function implemented below
 UpperCAmelCase__								=  c / d
 return (r * x, r * y)



def   lowerCAmelCase						(						_lowerCAmelCase							:				int  ,							_lowerCAmelCase							:				int  ,							_lowerCAmelCase							:				int  ,							_lowerCAmelCase							:				int = 2		):




 """simple docstring"""







 ((UpperCAmelCase__)	,	(UpperCAmelCase__))								=  diophantine(_lowerCAmelCase  ,							_lowerCAmelCase  ,							_lowerCAmelCase		)  # Initial value
 UpperCAmelCase__								=  greatest_common_divisor(_lowerCAmelCase  ,							_lowerCAmelCase		)
 UpperCAmelCase__								=  a // d
 UpperCAmelCase__								=  b // d

 for i in range(_lowerCAmelCase		):
  UpperCAmelCase__								=  xa + i * q
  UpperCAmelCase__								=  ya - i * p
  print(_lowerCAmelCase  ,							_lowerCAmelCase		)



def   lowerCAmelCase						(						_lowerCAmelCase							:				int  ,							_lowerCAmelCase							:				int		):




 """simple docstring"""







 if a < b:
  UpperCAmelCase__	,	UpperCAmelCase__								=  b, a

 while a % b != 0:
  UpperCAmelCase__	,	UpperCAmelCase__								=  b, a % b

 return b



def   lowerCAmelCase						(						_lowerCAmelCase							:				int  ,							_lowerCAmelCase							:				int		):




 """simple docstring"""







 assert a >= 0 and b >= 0

 if b == 0:
  UpperCAmelCase__	,	UpperCAmelCase__	,	UpperCAmelCase__								=  a, 1, 0
 else:
  ((UpperCAmelCase__)	,	(UpperCAmelCase__)	,	(UpperCAmelCase__))								=  extended_gcd(_lowerCAmelCase  ,							a % b		)
  UpperCAmelCase__								=  q
  UpperCAmelCase__								=  p - q * (a // b)

 assert a % d == 0 and b % d == 0
 assert d == a * x + b * y

 return (d, x, y)


if __name__ == "__main__":
  from doctest import testmod

  testmod(name="diophantine", verbose=True)
  testmod(name="diophantine_all_soln", verbose=True)
  testmod(name="extended_gcd", verbose=True)
  testmod(name="greatest_common_divisor", verbose=True)





