


'''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_  :    Dict      =			logging.get_logger(__name__)  # pylint: disable=invalid-name





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





  """simple docstring"""




  _lowerCamelCase		   =  42
  _lowerCamelCase		   =  None





def __snake_case (				UpperCAmelCase_						:						Optional[Any] ,    UpperCAmelCase_						:						Tuple=0.999 ,    UpperCAmelCase_						:						List[Any]="cosine" ,    ):
 if alpha_transform_type == "cosine":

  def alpha_bar_fn(UpperCAmelCase_						:						List[str]		):
   return math.cos((t + 0.008) / 1.008 * math.pi / 2		) ** 2

 elif alpha_transform_type == "exp":

  def alpha_bar_fn(UpperCAmelCase_						:						Union[str, Any]		):
   return math.exp(t * -12.0		)

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

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







class 					snake_case   (   lowercase      ,						lowercase      ):





  """simple docstring"""




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






  @register_to_config
  def __init__(   self      ,  UpperCamelCase = 1000      ,  UpperCamelCase = 0.0_001      ,  UpperCamelCase = 0.02      ,  UpperCamelCase = "linear"      ,  UpperCamelCase = None      ,  UpperCamelCase = "epsilon"      ,  UpperCamelCase = "linear"      ,  UpperCamelCase = False      ,  UpperCamelCase = "linspace"      ,  UpperCamelCase = 0      ,  ):







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

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

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

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






  @property
  def   snake_case		(   self					):







   """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   snake_case		(   self      ,  UpperCamelCase      ,  UpperCamelCase					):







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

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

   lowerCamelCase_								=  True
   return sample






  def   snake_case		(   self      ,  UpperCamelCase      ,  UpperCamelCase = None					):







   """simple docstring"""
   lowerCamelCase_								=  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":
    lowerCamelCase_								=  np.linspace(0      ,  self.config.num_train_timesteps - 1      ,  UpperCamelCase      ,  dtype=UpperCamelCase					)[
        ::-1
    ].copy()
   elif self.config.timestep_spacing == "leading":
    lowerCamelCase_								=  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
    lowerCamelCase_								=  (np.arange(0      ,  UpperCamelCase					) * step_ratio).round()[::-1].copy().astype(UpperCamelCase					)
    timesteps += self.config.steps_offset
   elif self.config.timestep_spacing == "trailing":
    lowerCamelCase_								=  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
    lowerCamelCase_								=  (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\'.'''					)

   lowerCamelCase_								=  np.array(((1 - self.alphas_cumprod) / self.alphas_cumprod) ** 0.5					)
   lowerCamelCase_								=  np.log(UpperCamelCase					)

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

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






  def   snake_case		(   self      ,  UpperCamelCase      ,  UpperCamelCase					):







   """simple docstring"""
   # get log sigma
   lowerCamelCase_								=  np.log(UpperCamelCase					)

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

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

   lowerCamelCase_								=  log_sigmas[low_idx]
   lowerCamelCase_								=  log_sigmas[high_idx]

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

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






  def   snake_case		(   self      ,  UpperCamelCase      ,  UpperCamelCase					):







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

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






  def   snake_case		(   self      ,  UpperCamelCase      ,  UpperCamelCase      ,  UpperCamelCase      ,  UpperCamelCase = 0.0      ,  UpperCamelCase = 0.0      ,  UpperCamelCase = float("inf"					)      ,  UpperCamelCase = 1.0      ,  UpperCamelCase = None      ,  UpperCamelCase = True      ,  ):







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

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

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

   lowerCamelCase_								=  randn_tensor(
       model_output.shape      ,  dtype=model_output.dtype      ,  device=model_output.device      ,  generator=UpperCamelCase					)

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

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

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

   lowerCamelCase_								=  sample + derivative * dt

   if not return_dict:
    return (prev_sample,)

   return EulerDiscreteSchedulerOutput(prev_sample=UpperCamelCase      ,  pred_original_sample=UpperCamelCase					)






  def   snake_case		(   self      ,  UpperCamelCase      ,  UpperCamelCase      ,  UpperCamelCase      ,  ):







   """simple docstring"""
   # Make sure sigmas and timesteps have the same device and dtype as original_samples
   lowerCamelCase_								=  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
    lowerCamelCase_								=  self.timesteps.to(original_samples.device      ,  dtype=torch.floataa					)
    lowerCamelCase_								=  timesteps.to(original_samples.device      ,  dtype=torch.floataa					)
   else:
    lowerCamelCase_								=  self.timesteps.to(original_samples.device					)
    lowerCamelCase_								=  timesteps.to(original_samples.device					)

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

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

   lowerCamelCase_								=  original_samples + noise * sigma
   return noisy_samples







  def __len__(   self					):







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







'''simple docstring'''

from collections import OrderedDict
from typing import Mapping

from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig
from ...utils import logging


a_  :    Optional[Any]      =			logging.get_logger(__name__)

a_  :    Tuple      =			{
    """google/electra-small-generator""": """https://huggingface.co/google/electra-small-generator/resolve/main/config.json""",
    """google/electra-base-generator""": """https://huggingface.co/google/electra-base-generator/resolve/main/config.json""",
    """google/electra-large-generator""": """https://huggingface.co/google/electra-large-generator/resolve/main/config.json""",
    """google/electra-small-discriminator""": (
        """https://huggingface.co/google/electra-small-discriminator/resolve/main/config.json"""
    ),
    """google/electra-base-discriminator""": (
        """https://huggingface.co/google/electra-base-discriminator/resolve/main/config.json"""
    ),
    """google/electra-large-discriminator""": (
        """https://huggingface.co/google/electra-large-discriminator/resolve/main/config.json"""
    ),
}





class 					snake_case   (   lowercase      ):





  """simple docstring"""




  _lowerCamelCase		   =  "electra"






  def __init__(   self      ,  UpperCamelCase=3_0522      ,  UpperCamelCase=128      ,  UpperCamelCase=256      ,  UpperCamelCase=12      ,  UpperCamelCase=4      ,  UpperCamelCase=1024      ,  UpperCamelCase="gelu"      ,  UpperCamelCase=0.1      ,  UpperCamelCase=0.1      ,  UpperCamelCase=512      ,  UpperCamelCase=2      ,  UpperCamelCase=0.02      ,  UpperCamelCase=1e-12      ,  UpperCamelCase="first"      ,  UpperCamelCase=True      ,  UpperCamelCase="gelu"      ,  UpperCamelCase=0.1      ,  UpperCamelCase=0      ,  UpperCamelCase="absolute"      ,  UpperCamelCase=True      ,  UpperCamelCase=None      ,  **UpperCamelCase      ,  ):







   """simple docstring"""
   super().__init__(pad_token_id=UpperCamelCase      ,  **UpperCamelCase					)

   lowerCamelCase_								=  vocab_size
   lowerCamelCase_								=  embedding_size
   lowerCamelCase_								=  hidden_size
   lowerCamelCase_								=  num_hidden_layers
   lowerCamelCase_								=  num_attention_heads
   lowerCamelCase_								=  intermediate_size
   lowerCamelCase_								=  hidden_act
   lowerCamelCase_								=  hidden_dropout_prob
   lowerCamelCase_								=  attention_probs_dropout_prob
   lowerCamelCase_								=  max_position_embeddings
   lowerCamelCase_								=  type_vocab_size
   lowerCamelCase_								=  initializer_range
   lowerCamelCase_								=  layer_norm_eps

   lowerCamelCase_								=  summary_type
   lowerCamelCase_								=  summary_use_proj
   lowerCamelCase_								=  summary_activation
   lowerCamelCase_								=  summary_last_dropout
   lowerCamelCase_								=  position_embedding_type
   lowerCamelCase_								=  use_cache
   lowerCamelCase_								=  classifier_dropout





class 					snake_case   (   lowercase      ):





  """simple docstring"""




  @property
  def   snake_case		(   self					):







   """simple docstring"""
   if self.task == "multiple-choice":
    lowerCamelCase_								=  {0: "batch", 1: "choice", 2: "sequence"}
   else:
    lowerCamelCase_								=  {0: "batch", 1: "sequence"}
   return OrderedDict(
       [
           ("input_ids", dynamic_axis),
           ("attention_mask", dynamic_axis),
           ("token_type_ids", dynamic_axis),
       ]					)



