




"""simple docstring"""




import math
from collections import defaultdict
from typing import List, Optional, Tuple, Union

import numpy as np
import torch

from ..configuration_utils import ConfigMixin, register_to_config
from .scheduling_utils import KarrasDiffusionSchedulers, SchedulerMixin, SchedulerOutput







def      __UpperCAmelCase     ( __UpperCamelCase	,				__UpperCamelCase=0.999	,				__UpperCamelCase="cosine"	,				):





			if alpha_transform_type == "cosine":

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

			elif alpha_transform_type == "exp":

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

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

			__lowercase			:  str								=       []
			for i in range(UpperCAmelCase_	):
						__lowercase			:  Optional[int]								=       i / num_diffusion_timesteps
						__lowercase			:  Union[str, Any]								=       (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   UpperCAmelCase_    (			_lowerCAmelCase   ,					_lowerCAmelCase		):
		UpperCamelCase							=[e.name for e in KarrasDiffusionSchedulers]
		UpperCamelCase							=2
		@register_to_config
		def __init__(						self				,						UpperCamelCase_ = 10_00				,						UpperCamelCase_ = 0.0_0_0_8_5				,						UpperCamelCase_ = 0.0_1_2				,						UpperCamelCase_ = "linear"				,						UpperCamelCase_ = None				,						UpperCamelCase_ = "epsilon"				,						UpperCamelCase_ = False				,						UpperCamelCase_ = False				,						UpperCamelCase_ = 1.0				,						UpperCamelCase_ = "linspace"				,						UpperCamelCase_ = 0				,						)						->       Optional[int]:
					if trained_betas is not None:
								__lowercase			:  Any								=       torch.tensor(SCREAMING_SNAKE_CASE__				,						dtype=torch.floataa       )
					elif beta_schedule == "linear":
								__lowercase			:  Optional[int]								=       torch.linspace(SCREAMING_SNAKE_CASE__				,						SCREAMING_SNAKE_CASE__				,						SCREAMING_SNAKE_CASE__				,						dtype=torch.floataa       )
					elif beta_schedule == "scaled_linear":
								# this schedule is very specific to the latent diffusion model.
								__lowercase			:  Any								=       (
								    torch.linspace(beta_start**0.5				,						beta_end**0.5				,						SCREAMING_SNAKE_CASE__				,						dtype=torch.floataa       ) ** 2
								)
					elif beta_schedule == "squaredcos_cap_v2":
								# Glide cosine schedule
								__lowercase			:  Optional[int]								=       betas_for_alpha_bar(SCREAMING_SNAKE_CASE__				,						alpha_transform_type='''cosine'''       )
					elif beta_schedule == "exp":
								__lowercase			:  str								=       betas_for_alpha_bar(SCREAMING_SNAKE_CASE__				,						alpha_transform_type='''exp'''       )
					else:
								raise NotImplementedError(F"""{beta_schedule} does is not implemented for {self.__class__}"""       )

					__lowercase			:  Union[str, Any]								=       1.0 - self.betas
					__lowercase			:  str								=       torch.cumprod(self.alphas				,						dim=0       )

					#  set all values
					self.set_timesteps(SCREAMING_SNAKE_CASE__				,						SCREAMING_SNAKE_CASE__				,						SCREAMING_SNAKE_CASE__       )
					__lowercase			:  int								=       use_karras_sigmas
		def 	_lowerCamelCase							(						self				,						UpperCamelCase_				,						UpperCamelCase_=None       )						->       Optional[int]:
					if schedule_timesteps is None:
								__lowercase			:  int								=       self.timesteps

					__lowercase			:  Any								=       (schedule_timesteps == timestep).nonzero()

					# The sigma index that is taken for the **very** first `step`
					# is always the second index (or the last index if there is only 1)
					# This way we can ensure we don't accidentally skip a sigma in
					# case we start in the middle of the denoising schedule (e.g. for image-to-image)
					if len(self._index_counter       ) == 0:
								__lowercase			:  Union[str, Any]								=       1 if len(SCREAMING_SNAKE_CASE__       ) > 1 else 0
					else:
								__lowercase			:  int								=       timestep.cpu().item() if torch.is_tensor(SCREAMING_SNAKE_CASE__       ) else timestep
								__lowercase			:  Any								=       self._index_counter[timestep_int]

					return indices[pos].item()
		@property
		def 	_lowerCamelCase							(						self       )						->       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 	_lowerCamelCase							(						self				,						UpperCamelCase_				,						UpperCamelCase_				,						)						->       torch.FloatTensor:
					__lowercase			:  Tuple								=       self.index_for_timestep(SCREAMING_SNAKE_CASE__       )

					__lowercase			:  Union[str, Any]								=       self.sigmas[step_index]
					__lowercase			:  Dict								=       sample / ((sigma**2 + 1) ** 0.5)
					return sample
		def 	_lowerCamelCase							(						self				,						UpperCamelCase_				,						UpperCamelCase_ = None				,						UpperCamelCase_ = None				,						)						->       Dict:
					__lowercase			:  Union[str, Any]								=       num_inference_steps

					__lowercase			:  Dict								=       num_train_timesteps or self.config.num_train_timesteps

					# "linspace", "leading", "trailing" corresponds to annotation of Table 2. of https://arxiv.org/abs/2305.08891
					if self.config.timestep_spacing == "linspace":
								__lowercase			:  Optional[int]								=       np.linspace(0				,						num_train_timesteps - 1				,						SCREAMING_SNAKE_CASE__				,						dtype=SCREAMING_SNAKE_CASE__       )[::-1].copy()
					elif self.config.timestep_spacing == "leading":
								__lowercase			:  List[str]								=       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
								__lowercase			:  Optional[Any]								=       (np.arange(0				,						SCREAMING_SNAKE_CASE__       ) * step_ratio).round()[::-1].copy().astype(SCREAMING_SNAKE_CASE__       )
								timesteps += self.config.steps_offset
					elif self.config.timestep_spacing == "trailing":
								__lowercase			:  Tuple								=       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
								__lowercase			:  List[Any]								=       (np.arange(SCREAMING_SNAKE_CASE__				,						0				,						-step_ratio       )).round().copy().astype(SCREAMING_SNAKE_CASE__       )
								timesteps -= 1
					else:
								raise ValueError(
								    F"""{self.config.timestep_spacing} is not supported. Please make sure to choose one of 'linspace', 'leading' or 'trailing'."""       )

					__lowercase			:  Any								=       np.array(((1 - self.alphas_cumprod) / self.alphas_cumprod) ** 0.5       )
					__lowercase			:  Optional[Any]								=       np.log(SCREAMING_SNAKE_CASE__       )
					__lowercase			:  Dict								=       np.interp(SCREAMING_SNAKE_CASE__				,						np.arange(0				,						len(SCREAMING_SNAKE_CASE__       )       )				,						SCREAMING_SNAKE_CASE__       )

					if self.config.use_karras_sigmas:
								__lowercase			:  Dict								=       self._convert_to_karras(in_sigmas=SCREAMING_SNAKE_CASE__				,						num_inference_steps=self.num_inference_steps       )
								__lowercase			:  str								=       np.array([self._sigma_to_t(SCREAMING_SNAKE_CASE__				,						SCREAMING_SNAKE_CASE__       ) for sigma in sigmas]       )

					__lowercase			:  List[Any]								=       np.concatenate([sigmas, [0.0]]       ).astype(np.floataa       )
					__lowercase			:  Optional[Any]								=       torch.from_numpy(SCREAMING_SNAKE_CASE__       ).to(device=SCREAMING_SNAKE_CASE__       )
					__lowercase			:  List[str]								=       torch.cat([sigmas[:1], sigmas[1:-1].repeat_interleave(2       ), sigmas[-1:]]       )

					__lowercase			:  Dict								=       torch.from_numpy(SCREAMING_SNAKE_CASE__       )
					__lowercase			:  List[Any]								=       torch.cat([timesteps[:1], timesteps[1:].repeat_interleave(2       )]       )

					if str(SCREAMING_SNAKE_CASE__       ).startswith('''mps'''       ):
								# mps does not support float64
								__lowercase			:  Union[str, Any]								=       timesteps.to(SCREAMING_SNAKE_CASE__				,						dtype=torch.floataa       )
					else:
								__lowercase			:  Dict								=       timesteps.to(device=SCREAMING_SNAKE_CASE__       )

					# empty dt and derivative
					__lowercase			:  List[Any]								=       None
					__lowercase			:  Optional[Any]								=       None

					# for exp beta schedules, such as the one for `pipeline_shap_e.py`
					# we need an index counter
					__lowercase			:  List[Any]								=       defaultdict(SCREAMING_SNAKE_CASE__       )
		def 	_lowerCamelCase							(						self				,						UpperCamelCase_				,						UpperCamelCase_       )						->       List[str]:
					# get log sigma
					__lowercase			:  str								=       np.log(SCREAMING_SNAKE_CASE__       )

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

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

					__lowercase			:  Tuple								=       log_sigmas[low_idx]
					__lowercase			:  List[Any]								=       log_sigmas[high_idx]

					# interpolate sigmas
					__lowercase			:  str								=       (low - log_sigma) / (low - high)
					__lowercase			:  int								=       np.clip(SCREAMING_SNAKE_CASE__				,						0				,						1       )

					# transform interpolation to time range
					__lowercase			:  List[str]								=       (1 - w) * low_idx + w * high_idx
					__lowercase			:  List[Any]								=       t.reshape(sigma.shape       )
					return t
		def 	_lowerCamelCase							(						self				,						UpperCamelCase_				,						UpperCamelCase_       )						->       torch.FloatTensor:
					__lowercase			:  str								=       in_sigmas[-1].item()
					__lowercase			:  str								=       in_sigmas[0].item()

					__lowercase			:  Optional[Any]								=       7.0  # 7.0 is the value used in the paper
					__lowercase			:  List[Any]								=       np.linspace(0				,						1				,						SCREAMING_SNAKE_CASE__       )
					__lowercase			:  List[str]								=       sigma_min ** (1 / rho)
					__lowercase			:  str								=       sigma_max ** (1 / rho)
					__lowercase			:  Optional[Any]								=       (max_inv_rho + ramp * (min_inv_rho - max_inv_rho)) ** rho
					return sigmas
		@property
		def 	_lowerCamelCase							(						self       )						->       Optional[Any]:
					return self.dt is None
		def 	_lowerCamelCase							(						self				,						UpperCamelCase_				,						UpperCamelCase_				,						UpperCamelCase_				,						UpperCamelCase_ = True				,						)						->       Union[SchedulerOutput, Tuple]:
					__lowercase			:  List[Any]								=       self.index_for_timestep(SCREAMING_SNAKE_CASE__       )

					# advance index counter by 1
					__lowercase			:  List[str]								=       timestep.cpu().item() if torch.is_tensor(SCREAMING_SNAKE_CASE__       ) else timestep
					self._index_counter[timestep_int] += 1

					if self.state_in_first_order:
								__lowercase			:  Optional[int]								=       self.sigmas[step_index]
								__lowercase			:  Union[str, Any]								=       self.sigmas[step_index + 1]
					else:
								# 2nd order / Heun's method
								__lowercase			:  int								=       self.sigmas[step_index - 1]
								__lowercase			:  Tuple								=       self.sigmas[step_index]

					# currently only gamma=0 is supported. This usually works best anyways.
					# We can support gamma in the future but then need to scale the timestep before
					# passing it to the model which requires a change in API
					__lowercase			:  Optional[int]								=       0
					__lowercase			:  Dict								=       sigma * (gamma + 1)  # Note: sigma_hat == sigma for now

					# 1. compute predicted original sample (x_0) from sigma-scaled predicted noise
					if self.config.prediction_type == "epsilon":
								__lowercase			:  Dict								=       sigma_hat if self.state_in_first_order else sigma_next
								__lowercase			:  Optional[int]								=       sample - sigma_input * model_output
					elif self.config.prediction_type == "v_prediction":
								__lowercase			:  Union[str, Any]								=       sigma_hat if self.state_in_first_order else sigma_next
								__lowercase			:  str								=       model_output * (-sigma_input / (sigma_input**2 + 1) ** 0.5) + (
								    sample / (sigma_input**2 + 1)
								)
					elif self.config.prediction_type == "sample":
								__lowercase			:  Optional[Any]								=       model_output
					else:
								raise ValueError(
								    F"""prediction_type given as {self.config.prediction_type} must be one of `epsilon`, or `v_prediction`"""       )

					if self.config.clip_sample:
								__lowercase			:  Optional[int]								=       pred_original_sample.clamp(
								    -self.config.clip_sample_range				,						self.config.clip_sample_range       )

					if self.state_in_first_order:
								# 2. Convert to an ODE derivative for 1st order
								__lowercase			:  int								=       (sample - pred_original_sample) / sigma_hat
								# 3. delta timestep
								__lowercase			:  str								=       sigma_next - sigma_hat

								# store for 2nd order step
								__lowercase			:  str								=       derivative
								__lowercase			:  List[str]								=       dt
								__lowercase			:  Dict								=       sample
					else:
								# 2. 2nd order / Heun's method
								__lowercase			:  str								=       (sample - pred_original_sample) / sigma_next
								__lowercase			:  Tuple								=       (self.prev_derivative + derivative) / 2

								# 3. take prev timestep & sample
								__lowercase			:  Optional[int]								=       self.dt
								__lowercase			:  int								=       self.sample

								# free dt and derivative
								# Note, this puts the scheduler in "first order mode"
								__lowercase			:  List[str]								=       None
								__lowercase			:  List[str]								=       None
								__lowercase			:  Dict								=       None

					__lowercase			:  List[str]								=       sample + derivative * dt

					if not return_dict:
								return (prev_sample,)

					return SchedulerOutput(prev_sample=SCREAMING_SNAKE_CASE__       )
		def 	_lowerCamelCase							(						self				,						UpperCamelCase_				,						UpperCamelCase_				,						UpperCamelCase_				,						)						->       torch.FloatTensor:
					# Make sure sigmas and timesteps have the same device and dtype as original_samples
					__lowercase			:  int								=       self.sigmas.to(device=original_samples.device				,						dtype=original_samples.dtype       )
					if original_samples.device.type == "mps" and torch.is_floating_point(SCREAMING_SNAKE_CASE__       ):
								# mps does not support float64
								__lowercase			:  Tuple								=       self.timesteps.to(original_samples.device				,						dtype=torch.floataa       )
								__lowercase			:  Union[str, Any]								=       timesteps.to(original_samples.device				,						dtype=torch.floataa       )
					else:
								__lowercase			:  str								=       self.timesteps.to(original_samples.device       )
								__lowercase			:  Tuple								=       timesteps.to(original_samples.device       )

					__lowercase			:  Dict								=       [self.index_for_timestep(SCREAMING_SNAKE_CASE__				,						SCREAMING_SNAKE_CASE__       ) for t in timesteps]

					__lowercase			:  Dict								=       sigmas[step_indices].flatten()
					while len(sigma.shape       ) < len(original_samples.shape       ):
								__lowercase			:  Optional[Any]								=       sigma.unsqueeze(-1       )

					__lowercase			:  Tuple								=       original_samples + noise * sigma
					return noisy_samples
		def __len__(						self       )						->       Tuple:
					return self.config.num_train_timesteps








"""simple docstring"""







import json
from typing import List, Optional, Tuple

from tokenizers import normalizers

from ...tokenization_utils_fast import PreTrainedTokenizerFast
from .tokenization_electra import ElectraTokenizer


UpperCamelCase     =							{"""vocab_file""": """vocab.txt""", """tokenizer_file""": """tokenizer.json"""}

UpperCamelCase     =							{
    """vocab_file""": {
        """google/electra-small-generator""": (
            """https://huggingface.co/google/electra-small-generator/resolve/main/vocab.txt"""
        ),
        """google/electra-base-generator""": """https://huggingface.co/google/electra-base-generator/resolve/main/vocab.txt""",
        """google/electra-large-generator""": (
            """https://huggingface.co/google/electra-large-generator/resolve/main/vocab.txt"""
        ),
        """google/electra-small-discriminator""": (
            """https://huggingface.co/google/electra-small-discriminator/resolve/main/vocab.txt"""
        ),
        """google/electra-base-discriminator""": (
            """https://huggingface.co/google/electra-base-discriminator/resolve/main/vocab.txt"""
        ),
        """google/electra-large-discriminator""": (
            """https://huggingface.co/google/electra-large-discriminator/resolve/main/vocab.txt"""
        ),
    },
    """tokenizer_file""": {
        """google/electra-small-generator""": (
            """https://huggingface.co/google/electra-small-generator/resolve/main/tokenizer.json"""
        ),
        """google/electra-base-generator""": (
            """https://huggingface.co/google/electra-base-generator/resolve/main/tokenizer.json"""
        ),
        """google/electra-large-generator""": (
            """https://huggingface.co/google/electra-large-generator/resolve/main/tokenizer.json"""
        ),
        """google/electra-small-discriminator""": (
            """https://huggingface.co/google/electra-small-discriminator/resolve/main/tokenizer.json"""
        ),
        """google/electra-base-discriminator""": (
            """https://huggingface.co/google/electra-base-discriminator/resolve/main/tokenizer.json"""
        ),
        """google/electra-large-discriminator""": (
            """https://huggingface.co/google/electra-large-discriminator/resolve/main/tokenizer.json"""
        ),
    },
}

UpperCamelCase     =							{
    """google/electra-small-generator""": 512,
    """google/electra-base-generator""": 512,
    """google/electra-large-generator""": 512,
    """google/electra-small-discriminator""": 512,
    """google/electra-base-discriminator""": 512,
    """google/electra-large-discriminator""": 512,
}

UpperCamelCase     =							{
    """google/electra-small-generator""": {"""do_lower_case""": True},
    """google/electra-base-generator""": {"""do_lower_case""": True},
    """google/electra-large-generator""": {"""do_lower_case""": True},
    """google/electra-small-discriminator""": {"""do_lower_case""": True},
    """google/electra-base-discriminator""": {"""do_lower_case""": True},
    """google/electra-large-discriminator""": {"""do_lower_case""": True},
}






class       UpperCamelCase__			(   _lowerCAmelCase      ):

			"""simple docstring"""


			A__	:					Dict							  =     VOCAB_FILES_NAMES
			A__	:					str							  =     PRETRAINED_VOCAB_FILES_MAP
			A__	:					List[Any]							  =     PRETRAINED_INIT_CONFIGURATION
			A__	:					Any							  =     PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
			A__	:					List[str]							  =     ElectraTokenizer


			def __init__(      self						,	SCREAMING_SNAKE_CASE__=None						,	SCREAMING_SNAKE_CASE__=None						,	SCREAMING_SNAKE_CASE__=True						,	SCREAMING_SNAKE_CASE__="[UNK]"						,	SCREAMING_SNAKE_CASE__="[SEP]"						,	SCREAMING_SNAKE_CASE__="[PAD]"						,	SCREAMING_SNAKE_CASE__="[CLS]"						,	SCREAMING_SNAKE_CASE__="[MASK]"						,	SCREAMING_SNAKE_CASE__=True						,	SCREAMING_SNAKE_CASE__=None						,	**SCREAMING_SNAKE_CASE__						,	)      ->	str:
				super().__init__(
				    SCREAMING_SNAKE_CASE__						,	tokenizer_file=SCREAMING_SNAKE_CASE__						,	do_lower_case=SCREAMING_SNAKE_CASE__						,	unk_token=SCREAMING_SNAKE_CASE__						,	sep_token=SCREAMING_SNAKE_CASE__						,	pad_token=SCREAMING_SNAKE_CASE__						,	cls_token=SCREAMING_SNAKE_CASE__						,	mask_token=SCREAMING_SNAKE_CASE__						,	tokenize_chinese_chars=SCREAMING_SNAKE_CASE__						,	strip_accents=SCREAMING_SNAKE_CASE__						,	**SCREAMING_SNAKE_CASE__						,	)

				A__											=					json.loads(self.backend_tokenizer.normalizer.__getstate__()		)
				if (
				    normalizer_state.get("lowercase"						,	SCREAMING_SNAKE_CASE__		) != do_lower_case
				    or normalizer_state.get("strip_accents"						,	SCREAMING_SNAKE_CASE__		) != strip_accents
				    or normalizer_state.get("handle_chinese_chars"						,	SCREAMING_SNAKE_CASE__		) != tokenize_chinese_chars
				):
					A__											=					getattr(SCREAMING_SNAKE_CASE__						,	normalizer_state.pop("type"		)		)
					A__											=					do_lower_case
					A__											=					strip_accents
					A__											=					tokenize_chinese_chars
					A__											=					normalizer_class(**SCREAMING_SNAKE_CASE__		)

				A__											=					do_lower_case


			def   snake_case__	(      self						,	SCREAMING_SNAKE_CASE__						,	SCREAMING_SNAKE_CASE__=None		)      ->	List[str]:
				A__											=					[self.cls_token_id] + token_ids_a + [self.sep_token_id]

				if token_ids_a:
					output += token_ids_a + [self.sep_token_id]

				return output


			def   snake_case__	(      self						,	SCREAMING_SNAKE_CASE__						,	SCREAMING_SNAKE_CASE__ = None		)      ->	List[int]:
				A__											=					[self.sep_token_id]
				A__											=					[self.cls_token_id]
				if token_ids_a is None:
					return len(cls + token_ids_a + sep		) * [0]
				return len(cls + token_ids_a + sep		) * [0] + len(token_ids_a + sep		) * [1]







			def   snake_case__	(      self						,	SCREAMING_SNAKE_CASE__						,	SCREAMING_SNAKE_CASE__ = None		)      ->	Tuple[str]:
				A__											=					self._tokenizer.model.save(SCREAMING_SNAKE_CASE__						,	name=SCREAMING_SNAKE_CASE__		)
				return tuple(SCREAMING_SNAKE_CASE__		)




