






'''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


__A   :							Optional[int]     	=						logging.get_logger(__name__)  # pylint: disable=invalid-name






@dataclass
# Copied from diffusers.schedulers.scheduling_ddpm.DDPMSchedulerOutput with DDPM->EulerAncestralDiscrete
class        a__     (      lowerCamelCase    ):
     '''simple docstring'''







     _snake_case							   =	42
     _snake_case							   =	None







def     _UpperCamelCase				(  snake_case__				,      snake_case__=0.999				,      snake_case__="cosine"				,      ):
      if alpha_transform_type == "cosine":

            def alpha_bar_fn(snake_case__				):
                  return math.cos((t + 0.008) / 1.008 * 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}"				)

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






class        a__     (      lowerCamelCase			,    lowerCamelCase    ):
     '''simple docstring'''







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






     @register_to_config
     def __init__(self     :						Tuple					,					lowercase__     :						int = 1000					,					lowercase__     :						float = 0.00_01					,					lowercase__     :						float = 0.02					,					lowercase__     :						str = "linear"					,					lowercase__     :						Optional[Union[np.ndarray, List[float]]] = None					,					lowercase__     :						str = "epsilon"					,					lowercase__     :						str = "linspace"					,					lowercase__     :						int = 0					,					)	->							Union[str, Any]:
           if trained_betas is not None:
                 __A		 =   torch.tensor(lowercase__					,					dtype=torch.floataa       )
           elif beta_schedule == "linear":
                 __A		 =   torch.linspace(lowercase__					,					lowercase__					,					lowercase__					,					dtype=torch.floataa       )
           elif beta_schedule == "scaled_linear":
                 # this schedule is very specific to the latent diffusion model.
                 __A		 =   (
                     torch.linspace(beta_start**0.5					,					beta_end**0.5					,					lowercase__					,					dtype=torch.floataa       ) ** 2
                 )
           elif beta_schedule == "squaredcos_cap_v2":
                 # Glide cosine schedule
                 __A		 =   betas_for_alpha_bar(lowercase__       )
           else:
                 raise NotImplementedError(f"{beta_schedule} does is not implemented for {self.__class__}"       )

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

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

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






     @property
     def      _UpperCamelCase (self     :						List[str]       )	->							str:
           # 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[str]					,					lowercase__     :						torch.FloatTensor					,					lowercase__     :						Union[float, torch.FloatTensor]       )	->							torch.FloatTensor:
           if isinstance(lowercase__					,					torch.Tensor       ):
                 __A		 =   timestep.to(self.timesteps.device       )
           __A		 =   (self.timesteps == timestep).nonzero().item()
           __A		 =   self.sigmas[step_index]
           __A		 =   sample / ((sigma**2 + 1) ** 0.5)
           __A		 =   True
           return sample






     def      _UpperCamelCase (self     :						Dict					,					lowercase__     :						int					,					lowercase__     :						Union[str, torch.device] = None       )	->							Union[str, Any]:
           __A		 =   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":
                 __A		 =   np.linspace(0					,					self.config.num_train_timesteps - 1					,					lowercase__					,					dtype=lowercase__       )[
                     ::-1
                 ].copy()
           elif self.config.timestep_spacing == "leading":
                 __A		 =   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
                 __A		 =   (np.arange(0					,					lowercase__       ) * step_ratio).round()[::-1].copy().astype(lowercase__       )
                 timesteps += self.config.steps_offset
           elif self.config.timestep_spacing == "trailing":
                 __A		 =   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
                 __A		 =   (np.arange(self.config.num_train_timesteps					,					0					,					-step_ratio       )).round().copy().astype(lowercase__       )
                 timesteps -= 1
           else:
                 raise ValueError(
                     f"{self.config.timestep_spacing} is not supported. Please make sure to choose one of 'linspace', 'leading' or 'trailing'."       )

           __A		 =   np.array(((1 - self.alphas_cumprod) / self.alphas_cumprod) ** 0.5       )
           __A		 =   np.interp(lowercase__					,					np.arange(0					,					len(lowercase__       )       )					,					lowercase__       )
           __A		 =   np.concatenate([sigmas, [0.0]]       ).astype(np.floataa       )
           __A		 =   torch.from_numpy(lowercase__       ).to(device=lowercase__       )
           if str(lowercase__       ).startswith("mps"       ):
                 # mps does not support float64
                 __A		 =   torch.from_numpy(lowercase__       ).to(lowercase__					,					dtype=torch.floataa       )
           else:
                 __A		 =   torch.from_numpy(lowercase__       ).to(device=lowercase__       )






     def      _UpperCamelCase (self     :						Optional[int]					,					lowercase__     :						torch.FloatTensor					,					lowercase__     :						Union[float, torch.FloatTensor]					,					lowercase__     :						torch.FloatTensor					,					lowercase__     :						Optional[torch.Generator] = None					,					lowercase__     :						bool = True					,					)	->							Union[EulerAncestralDiscreteSchedulerOutput, Tuple]:

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

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

           # 1. compute predicted original sample (x_0) from sigma-scaled predicted noise
           if self.config.prediction_type == "epsilon":
                 __A		 =   sample - sigma * model_output
           elif self.config.prediction_type == "v_prediction":
                 # * c_out + input * c_skip
                 __A		 =   model_output * (-sigma / (sigma**2 + 1) ** 0.5) + (sample / (sigma**2 + 1))
           elif self.config.prediction_type == "sample":
                 raise NotImplementedError("prediction_type not implemented yet: sample"       )
           else:
                 raise ValueError(
                     f"prediction_type given as {self.config.prediction_type} must be one of `epsilon`, or `v_prediction`"       )

           __A		 =   self.sigmas[step_index]
           __A		 =   self.sigmas[step_index + 1]
           __A		 =   (sigma_to**2 * (sigma_from**2 - sigma_to**2) / sigma_from**2) ** 0.5
           __A		 =   (sigma_to**2 - sigma_up**2) ** 0.5

           # 2. Convert to an ODE derivative
           __A		 =   (sample - pred_original_sample) / sigma

           __A		 =   sigma_down - sigma

           __A		 =   sample + derivative * dt

           __A		 =   model_output.device
           __A		 =   randn_tensor(model_output.shape					,					dtype=model_output.dtype					,					device=lowercase__					,					generator=lowercase__       )

           __A		 =   prev_sample + noise * sigma_up

           if not return_dict:
                 return (prev_sample,)

           return EulerAncestralDiscreteSchedulerOutput(
               prev_sample=lowercase__					,					pred_original_sample=lowercase__       )






     def      _UpperCamelCase (self     :						int					,					lowercase__     :						torch.FloatTensor					,					lowercase__     :						torch.FloatTensor					,					lowercase__     :						torch.FloatTensor					,					)	->							torch.FloatTensor:
           # Make sure sigmas and timesteps have the same device and dtype as original_samples
           __A		 =   self.sigmas.to(device=original_samples.device					,					dtype=original_samples.dtype       )
           if original_samples.device.type == "mps" and torch.is_floating_point(lowercase__       ):
                 # mps does not support float64
                 __A		 =   self.timesteps.to(original_samples.device					,					dtype=torch.floataa       )
                 __A		 =   timesteps.to(original_samples.device					,					dtype=torch.floataa       )
           else:
                 __A		 =   self.timesteps.to(original_samples.device       )
                 __A		 =   timesteps.to(original_samples.device       )

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

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

           __A		 =   original_samples + noise * sigma
           return noisy_samples






     def __len__(self     :						Dict       )	->							Optional[int]:
           return self.config.num_train_timesteps










'''simple docstring'''







import torch

from diffusers import KDPMaAncestralDiscreteScheduler
from diffusers.utils import torch_device

from .test_schedulers import SchedulerCommonTest






class        a__     (      lowerCamelCase    ):
     '''simple docstring'''







     _snake_case							   =	(KDPMaAncestralDiscreteScheduler,)
     _snake_case							   =	10






     def      _UpperCamelCase (self     :						int					,					**lowercase__     :						Optional[int]       )	->							Dict:
           __A		 =   {
               "num_train_timesteps": 1100,
               "beta_start": 0.00_01,
               "beta_end": 0.02,
               "beta_schedule": "linear",
           }

           config.update(**lowercase__       )
           return config






     def      _UpperCamelCase (self     :						str       )	->							Optional[Any]:
           for timesteps in [10, 50, 100, 1000]:
                 self.check_over_configs(num_train_timesteps=lowercase__       )






     def      _UpperCamelCase (self     :						List[Any]       )	->							int:
           for beta_start, beta_end in zip([0.0_00_01, 0.00_01, 0.0_01]					,					[0.00_02, 0.0_02, 0.02]       ):
                 self.check_over_configs(beta_start=lowercase__					,					beta_end=lowercase__       )






     def      _UpperCamelCase (self     :						int       )	->							Tuple:
           for schedule in ["linear", "scaled_linear"]:
                 self.check_over_configs(beta_schedule=lowercase__       )






     def      _UpperCamelCase (self     :						int       )	->							Any:
           if torch_device == "mps":
                 return
           __A		 =   self.scheduler_classes[0]
           __A		 =   self.get_scheduler_config()
           __A		 =   scheduler_class(**lowercase__       )

           scheduler.set_timesteps(self.num_inference_steps       )

           __A		 =   torch.manual_seed(0       )

           __A		 =   self.dummy_model()
           __A		 =   self.dummy_sample_deter * scheduler.init_noise_sigma
           __A		 =   sample.to(lowercase__       )

           for i, t in enumerate(scheduler.timesteps       ):
                 __A		 =   scheduler.scale_model_input(lowercase__					,					lowercase__       )

                 __A		 =   model(lowercase__					,					lowercase__       )

                 __A		 =   scheduler.step(lowercase__					,					lowercase__					,					lowercase__					,					generator=lowercase__       )
                 __A		 =   output.prev_sample

           __A		 =   torch.sum(torch.abs(lowercase__       )       )
           __A		 =   torch.mean(torch.abs(lowercase__       )       )

           assert abs(result_sum.item() - 1_38_49.38_77       ) < 1e-2
           assert abs(result_mean.item() - 18.03_31       ) < 5e-3






     def      _UpperCamelCase (self     :						Optional[Any]       )	->							str:
           for prediction_type in ["epsilon", "v_prediction"]:
                 self.check_over_configs(prediction_type=lowercase__       )






     def      _UpperCamelCase (self     :						List[Any]       )	->							List[Any]:
           if torch_device == "mps":
                 return
           __A		 =   self.scheduler_classes[0]
           __A		 =   self.get_scheduler_config(prediction_type="v_prediction"       )
           __A		 =   scheduler_class(**lowercase__       )

           scheduler.set_timesteps(self.num_inference_steps       )

           __A		 =   self.dummy_model()
           __A		 =   self.dummy_sample_deter * scheduler.init_noise_sigma
           __A		 =   sample.to(lowercase__       )

           __A		 =   torch.manual_seed(0       )

           for i, t in enumerate(scheduler.timesteps       ):
                 __A		 =   scheduler.scale_model_input(lowercase__					,					lowercase__       )

                 __A		 =   model(lowercase__					,					lowercase__       )

                 __A		 =   scheduler.step(lowercase__					,					lowercase__					,					lowercase__					,					generator=lowercase__       )
                 __A		 =   output.prev_sample

           __A		 =   torch.sum(torch.abs(lowercase__       )       )
           __A		 =   torch.mean(torch.abs(lowercase__       )       )

           assert abs(result_sum.item() - 3_28.99_70       ) < 1e-2
           assert abs(result_mean.item() - 0.42_84       ) < 1e-3






     def      _UpperCamelCase (self     :						Optional[Any]       )	->							int:
           if torch_device == "mps":
                 return
           __A		 =   self.scheduler_classes[0]
           __A		 =   self.get_scheduler_config()
           __A		 =   scheduler_class(**lowercase__       )

           scheduler.set_timesteps(self.num_inference_steps					,					device=lowercase__       )
           __A		 =   torch.manual_seed(0       )

           __A		 =   self.dummy_model()
           __A		 =   self.dummy_sample_deter.to(lowercase__       ) * scheduler.init_noise_sigma

           for t in scheduler.timesteps:
                 __A		 =   scheduler.scale_model_input(lowercase__					,					lowercase__       )

                 __A		 =   model(lowercase__					,					lowercase__       )

                 __A		 =   scheduler.step(lowercase__					,					lowercase__					,					lowercase__					,					generator=lowercase__       )
                 __A		 =   output.prev_sample

           __A		 =   torch.sum(torch.abs(lowercase__       )       )
           __A		 =   torch.mean(torch.abs(lowercase__       )       )

           assert abs(result_sum.item() - 1_38_49.38_18       ) < 1e-1
           assert abs(result_mean.item() - 18.03_31       ) < 1e-3


