





'''simple docstring'''






import math
from collections import OrderedDict

import torch
from packaging import version
from torch import Tensor, nn

from .utils import logging


__UpperCamelCase										=  logging.get_logger(__name__)




class    _A   (				nn.Module		):

		def __init__(      self				:      str )				->						Tuple:


					"""simple docstring"""

					super().__init__()
					if version.parse(torch.__version__ ) < version.parse("""1.12.0""" ):
								raise ImportError(
								    f'''You are using torch=={torch.__version__}, but torch>=1.12.0 is required to use '''
								    """PytorchGELUTanh. Please upgrade torch.""" )

		def   lowercase__    (      self				:      List[Any]     ,			__magic_name__				:      Optional[int] )				->						List[Any]:


					"""simple docstring"""

					return nn.functional.gelu(_lowerCamelCase     ,			approximate="""tanh""" )





class    _A   (				nn.Module		):

		def   lowercase__    (      self				:      Union[str, Any]     ,			__magic_name__				:      str )				->						Tuple:


					"""simple docstring"""

					return 0.5 * input * (1.0 + torch.tanh(math.sqrt(2.0 / math.pi ) * (input + 0.044715 * torch.pow(_lowerCamelCase     ,			3.0 )) ))





class    _A   (				nn.Module		):

		def __init__(      self				:      Dict     ,			__magic_name__				:      Any = False )				->						List[str]:


					"""simple docstring"""

					super().__init__()
					if use_gelu_python:
								__snake_case				:			int       			=    self._gelu_python
					else:
								__snake_case				:			Dict       			=    nn.functional.gelu

		def   lowercase__    (      self				:      Optional[int]     ,			__magic_name__				:      Optional[Any] )				->						Optional[int]:


					"""simple docstring"""

					return input * 0.5 * (1.0 + torch.erf(input / math.sqrt(2.0 ) ))

		def   lowercase__    (      self				:      str     ,			__magic_name__				:      List[Any] )				->						List[Any]:


					"""simple docstring"""

					return self.act(_lowerCamelCase )





class    _A   (				nn.Module		):

		def   lowercase__    (      self				:      List[Any]     ,			__magic_name__				:      Dict )				->						Dict:


					"""simple docstring"""

					return 0.5 * input * (1.0 + torch.tanh(input * 0.7978845608 * (1.0 + 0.044715 * input * input) ))





class    _A   (				nn.Module		):

		def   lowercase__    (      self				:      Union[str, Any]     ,			__magic_name__				:      Dict )				->						Any:


					"""simple docstring"""

					return input * torch.sigmoid(1.702 * input )





class    _A   (				nn.Module		):

		def __init__(      self				:      Optional[Any]     ,			__magic_name__				:      Tuple     ,			__magic_name__				:      Any )				->						int:


					"""simple docstring"""

					if min > max:
								raise ValueError(f'''min should be < max (got min: {min}, max: {max})''' )

					super().__init__()
					__snake_case				:			Dict       			=    min
					__snake_case				:			Dict       			=    max

		def   lowercase__    (      self				:      Dict     ,			__magic_name__				:      Any )				->						int:


					"""simple docstring"""

					return torch.clip(gelu(_lowerCamelCase )     ,			self.min     ,			self.max )





class    _A   (				nn.Module		):

		def __init__(      self				:      Union[str, Any] )				->						Optional[int]:


					"""simple docstring"""

					super().__init__()
					__snake_case				:			Dict       			=    math.sqrt(2 / math.pi )

		def   lowercase__    (      self				:      Dict     ,			__magic_name__				:      Union[str, Any] )				->						List[Any]:


					"""simple docstring"""

					return 0.5 * input * (1 + torch.tanh(self.precomputed_constant * (input + 0.044715 * torch.pow(_lowerCamelCase     ,			3 )) ))





class    _A   (				nn.Module		):

		def   lowercase__    (      self				:      List[str]     ,			__magic_name__				:      Optional[int] )				->						List[Any]:


					"""simple docstring"""

					return nn.functional.silu(_lowerCamelCase )





class    _A   (				nn.Module		):

		def __init__(      self				:      int )				->						Optional[int]:


					"""simple docstring"""

					super().__init__()
					if version.parse(torch.__version__ ) < version.parse("""1.9.0""" ):
								__snake_case				:			List[str]       			=    self._mish_python
					else:
								__snake_case				:			Optional[int]       			=    nn.functional.mish

		def   lowercase__    (      self				:      Tuple     ,			__magic_name__				:      Tuple )				->						str:


					"""simple docstring"""

					return input * torch.tanh(nn.functional.softplus(_lowerCamelCase ) )

		def   lowercase__    (      self				:      int     ,			__magic_name__				:      Union[str, Any] )				->						Any:


					"""simple docstring"""

					return self.act(_lowerCamelCase )





class    _A   (				nn.Module		):

		def   lowercase__    (      self				:      List[Any]     ,			__magic_name__				:      Any )				->						Optional[Any]:


					"""simple docstring"""

					return input





class    _A   (				nn.Module		):

		def   lowercase__    (      self				:      Union[str, Any]     ,			__magic_name__				:      List[str]     ,			__magic_name__				:      Optional[Any]=0.707107     ,			__magic_name__				:      Optional[int]=0.282095 )				->						str:


					"""simple docstring"""

					__snake_case				:			Tuple       			=    (input - mu).div(sigma * math.sqrt(2.0 ) )
					return 0.5 * (1.0 + torch.erf(_lowerCamelCase ))





class    _A   (				nn.Module		):

		def   lowercase__    (      self				:      Optional[Any]     ,			__magic_name__				:      Optional[Any] )				->						Dict:


					"""simple docstring"""

					__snake_case				:			int       			=    nn.functional.relu(_lowerCamelCase )
					__snake_case				:			int       			=    torch.square(_lowerCamelCase )
					return squared





class    _A   (				lowerCAmelCase__		):

		def __getitem__(      self				:      List[str]     ,			__magic_name__				:      str )				->						int:


					"""simple docstring"""

					__snake_case				:			Dict       			=    super().__getitem__(_lowerCamelCase )
					__snake_case				:			List[str]       			=    content if isinstance(_lowerCamelCase     ,			_lowerCamelCase ) else (content, {})
					return cls(**_lowerCamelCase )





__UpperCamelCase										=  {
    "gelu": GELUActivation,
    "gelu_10": (ClippedGELUActivation, {"min": -10, "max": 10}),
    "gelu_fast": FastGELUActivation,
    "gelu_new": NewGELUActivation,
    "gelu_python": (GELUActivation, {"use_gelu_python": True}),
    "gelu_pytorch_tanh": PytorchGELUTanh,
    "gelu_accurate": AccurateGELUActivation,
    "laplace": LaplaceActivation,
    "linear": LinearActivation,
    "mish": MishActivation,
    "quick_gelu": QuickGELUActivation,
    "relu": nn.ReLU,
    "relu2": ReLUSquaredActivation,
    "relu6": nn.ReLUa,
    "sigmoid": nn.Sigmoid,
    "silu": SiLUActivation,
    "swish": SiLUActivation,
    "tanh": nn.Tanh,
}
__UpperCamelCase										=  ClassInstantier(ACTaCLS)







def 				_a	(					_lowerCamelCase   ):



			"""simple docstring"""


			if activation_string in ACTaFN:
						return ACTaFN[activation_string]
			else:
						raise KeyError(F'''function {activation_string} not found in ACT2FN mapping {list(ACTaFN.keys()   )}'''   )


# For backwards compatibility with: from activations import gelu_python
__UpperCamelCase										=  get_activation("gelu_python")
__UpperCamelCase										=  get_activation("gelu_new")
__UpperCamelCase										=  get_activation("gelu")
__UpperCamelCase										=  get_activation("gelu_fast")
__UpperCamelCase										=  get_activation("quick_gelu")
__UpperCamelCase										=  get_activation("silu")
__UpperCamelCase										=  get_activation("mish")

__UpperCamelCase										=  get_activation("linear")









'''simple docstring'''






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

import numpy as np
import torch
from scipy import integrate

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




@dataclass
# Copied from diffusers.schedulers.scheduling_ddpm.DDPMSchedulerOutput with DDPM->LMSDiscrete
class    _A   (				__lowercase		):
		lowercase__:      torch.FloatTensor
		lowercase__:      Optional[torch.FloatTensor]							    =      None







def 				_a	(					_lowerCamelCase						,  _lowerCamelCase=0.9_99						,  _lowerCamelCase="cosine"						,  )   ->							int:



			"""simple docstring"""


			if alpha_transform_type == "cosine":

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

			elif alpha_transform_type == "exp":

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

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

			__snake_case				:			int       			=    []
			for i in range(_lowerCamelCase   ):
						__snake_case				:			int       			=    i / num_diffusion_timesteps
						__snake_case				:			Any       			=    (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    _A   (				__lowercase	,				__lowercase		):
		lowercase__:      Tuple							    =      [e.name for e in KarrasDiffusionSchedulers]
		lowercase__:      List[Any]							    =      1

		@register_to_config
		def __init__(      self				:      Optional[int]     ,			__magic_name__				:      int = 10_00     ,			__magic_name__				:      float = 0.0001     ,			__magic_name__				:      float = 0.02     ,			__magic_name__				:      str = "linear"     ,			__magic_name__				:      Optional[Union[np.ndarray, List[float]]] = None     ,			__magic_name__				:      Optional[bool] = False     ,			__magic_name__				:      str = "epsilon"     ,			__magic_name__				:      str = "linspace"     ,			__magic_name__				:      int = 0     ,			)				->						List[Any]:


					"""simple docstring"""

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

					__snake_case				:			Tuple       			=    1.0 - self.betas
					__snake_case				:			Optional[Any]       			=    torch.cumprod(self.alphas     ,			dim=0 )

					__snake_case				:			Any       			=    np.array(((1 - self.alphas_cumprod) / self.alphas_cumprod) ** 0.5 )
					__snake_case				:			Tuple       			=    np.concatenate([sigmas[::-1], [0.0]] ).astype(np.floataa )
					__snake_case				:			Optional[Any]       			=    torch.from_numpy(__magic_name__ )

					# setable values
					__snake_case				:			str       			=    None
					__snake_case				:			Union[str, Any]       			=    use_karras_sigmas
					self.set_timesteps(__magic_name__     ,			__magic_name__ )
					__snake_case				:			str       			=    []
					__snake_case				:			str       			=    False

		@property
		def   lowercase__    (      self				:      Optional[Any] )				->						Optional[int]:


					"""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				:      str     ,			__magic_name__				:      torch.FloatTensor     ,			__magic_name__				:      Union[float, torch.FloatTensor] )				->						torch.FloatTensor:


					"""simple docstring"""

					if isinstance(__magic_name__     ,			torch.Tensor ):
								__snake_case				:			int       			=    timestep.to(self.timesteps.device )
					__snake_case				:			str       			=    (self.timesteps == timestep).nonzero().item()
					__snake_case				:			str       			=    self.sigmas[step_index]
					__snake_case				:			Optional[int]       			=    sample / ((sigma**2 + 1) ** 0.5)
					__snake_case				:			List[Any]       			=    True
					return sample

		def   lowercase__    (      self				:      Dict     ,			__magic_name__				:      Optional[Any]     ,			__magic_name__				:      Tuple     ,			__magic_name__				:      int )				->						List[str]:


					"""simple docstring"""

					def lms_derivative(__magic_name__				:      Optional[int] ):
								__snake_case				:			Any       			=    1.0
								for k in range(__magic_name__ ):
											if current_order == k:
														continue
											prod *= (tau - self.sigmas[t - k]) / (self.sigmas[t - current_order] - self.sigmas[t - k])
								return prod

					__snake_case				:			str       			=    integrate.quad(__magic_name__     ,			self.sigmas[t]     ,			self.sigmas[t + 1]     ,			epsrel=1E-4 )[0]

					return integrated_coeff

		def   lowercase__    (      self				:      List[Any]     ,			__magic_name__				:      int     ,			__magic_name__				:      Union[str, torch.device] = None )				->						Tuple:


					"""simple docstring"""

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

					__snake_case				:			List[Any]       			=    np.array(((1 - self.alphas_cumprod) / self.alphas_cumprod) ** 0.5 )
					__snake_case				:			int       			=    np.log(__magic_name__ )
					__snake_case				:			Union[str, Any]       			=    np.interp(__magic_name__     ,			np.arange(0     ,			len(__magic_name__ ) )     ,			__magic_name__ )

					if self.use_karras_sigmas:
								__snake_case				:			Optional[Any]       			=    self._convert_to_karras(in_sigmas=__magic_name__ )
								__snake_case				:			Union[str, Any]       			=    np.array([self._sigma_to_t(__magic_name__     ,			__magic_name__ ) for sigma in sigmas] )

					__snake_case				:			Tuple       			=    np.concatenate([sigmas, [0.0]] ).astype(np.floataa )

					__snake_case				:			Optional[int]       			=    torch.from_numpy(__magic_name__ ).to(device=__magic_name__ )
					if str(__magic_name__ ).startswith("""mps""" ):
								# mps does not support float64
								__snake_case				:			int       			=    torch.from_numpy(__magic_name__ ).to(__magic_name__     ,			dtype=torch.floataa )
					else:
								__snake_case				:			Dict       			=    torch.from_numpy(__magic_name__ ).to(device=__magic_name__ )

					__snake_case				:			Optional[int]       			=    []

		def   lowercase__    (      self				:      Dict     ,			__magic_name__				:      Optional[Any]     ,			__magic_name__				:      List[Any] )				->						List[Any]:


					"""simple docstring"""

					__snake_case				:			List[str]       			=    np.log(__magic_name__ )

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

					# get sigmas range
					__snake_case				:			Optional[int]       			=    np.cumsum((dists >= 0)     ,			axis=0 ).argmax(axis=0 ).clip(max=log_sigmas.shape[0] - 2 )
					__snake_case				:			List[str]       			=    low_idx + 1

					__snake_case				:			Dict       			=    log_sigmas[low_idx]
					__snake_case				:			Any       			=    log_sigmas[high_idx]

					# interpolate sigmas
					__snake_case				:			List[Any]       			=    (low - log_sigma) / (low - high)
					__snake_case				:			Optional[int]       			=    np.clip(__magic_name__     ,			0     ,			1 )

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

		def   lowercase__    (      self				:      Optional[int]     ,			__magic_name__				:      torch.FloatTensor )				->						torch.FloatTensor:


					"""simple docstring"""

					__snake_case				:			float       			=    in_sigmas[-1].item()
					__snake_case				:			float       			=    in_sigmas[0].item()

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

		def   lowercase__    (      self				:      Dict     ,			__magic_name__				:      torch.FloatTensor     ,			__magic_name__				:      Union[float, torch.FloatTensor]     ,			__magic_name__				:      torch.FloatTensor     ,			__magic_name__				:      int = 4     ,			__magic_name__				:      bool = True     ,			)				->						Union[LMSDiscreteSchedulerOutput, Tuple]:


					"""simple docstring"""

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

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

					# 1. compute predicted original sample (x_0) from sigma-scaled predicted noise
					if self.config.prediction_type == "epsilon":
								__snake_case				:			int       			=    sample - sigma * model_output
					elif self.config.prediction_type == "v_prediction":
								# * c_out + input * c_skip
								__snake_case				:			str       			=    model_output * (-sigma / (sigma**2 + 1) ** 0.5) + (sample / (sigma**2 + 1))
					elif self.config.prediction_type == "sample":
								__snake_case				:			int       			=    model_output
					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
					__snake_case				:			Union[str, Any]       			=    (sample - pred_original_sample) / sigma
					self.derivatives.append(__magic_name__ )
					if len(self.derivatives ) > order:
								self.derivatives.pop(0 )

					# 3. Compute linear multistep coefficients
					__snake_case				:			List[Any]       			=    min(step_index + 1     ,			__magic_name__ )
					__snake_case				:			List[str]       			=    [self.get_lms_coefficient(__magic_name__     ,			__magic_name__     ,			__magic_name__ ) for curr_order in range(__magic_name__ )]

					# 4. Compute previous sample based on the derivatives path
					__snake_case				:			Any       			=    sample + sum(
					    coeff * derivative for coeff, derivative in zip(__magic_name__     ,			reversed(self.derivatives ) ) )

					if not return_dict:
								return (prev_sample,)

					return LMSDiscreteSchedulerOutput(prev_sample=__magic_name__     ,			pred_original_sample=__magic_name__ )

		def   lowercase__    (      self				:      Dict     ,			__magic_name__				:      torch.FloatTensor     ,			__magic_name__				:      torch.FloatTensor     ,			__magic_name__				:      torch.FloatTensor     ,			)				->						torch.FloatTensor:


					"""simple docstring"""

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

					__snake_case				:			int       			=    [(schedule_timesteps == t).nonzero().item() for t in timesteps]

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

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

		def __len__(      self				:      Union[str, Any] )				->						Union[str, Any]:


					"""simple docstring"""

					return self.config.num_train_timesteps


