



"""simple docstring"""




import gc
import unittest

from parameterized import parameterized

from diffusers import FlaxUNetaDConditionModel
from diffusers.utils import is_flax_available
from diffusers.utils.testing_utils import load_hf_numpy, require_flax, slow


if is_flax_available():
 import jax
 import jax.numpy as jnp






@slow
@require_flax
class      UpperCAmelCase_  (    unittest.TestCase						):



      def 						snake_case_ (					self					:     Union[str, Any]					,     A					:     Dict					,     A					:     List[Any]						):
           return f'gaussian_noise_s={seed}_shape={"_".join([str(A						) for s in shape]						)}.npy'



      def 						snake_case_ (					self					:     Union[str, Any]						):
           # clean up the VRAM after each test
           super().tearDown()
           gc.collect()



      def 						snake_case_ (					self					:     List[Any]					,     A					:     Dict=0					,     A					:     Union[str, Any]=(4, 4, 6_4, 6_4)					,     A					:     Any=False						):
           _UpperCAmelCase      :     Optional[int]        =   jnp.bfloataa if fpaa else jnp.floataa
           _UpperCAmelCase      :     Union[str, Any]        =   jnp.array(load_hf_numpy(self.get_file_format(A					,     A						)						)					,     dtype=A						)
           return image



      def 						snake_case_ (					self					:     Any					,     A					:     Tuple=False					,     A					:     Optional[Any]="CompVis/stable-diffusion-v1-4"						):
           _UpperCAmelCase      :     Optional[Any]        =   jnp.bfloataa if fpaa else jnp.floataa
           _UpperCAmelCase      :     List[Any]        =   "bf16" if fpaa else None

           _UpperCAmelCase      :     Tuple        =   FlaxUNetaDConditionModel.from_pretrained(
               A					,     subfolder="unet"					,     dtype=A					,     revision=A						)
           return model, params



      def 						snake_case_ (					self					:     Any					,     A					:     Tuple=0					,     A					:     Optional[Any]=(4, 7_7, 7_6_8)					,     A					:     Dict=False						):
           _UpperCAmelCase      :     Dict        =   jnp.bfloataa if fpaa else jnp.floataa
           _UpperCAmelCase      :     Dict        =   jnp.array(load_hf_numpy(self.get_file_format(A					,     A						)						)					,     dtype=A						)
           return hidden_states



      @parameterized.expand(
          [
              # fmt: off
              [8_3, 4, [-0.2_323, -0.1_304, 0.0_813, -0.3_093, -0.0_919, -0.1_571, -0.1_125, -0.5_806]],
              [1_7, 0.55, [-0.0_831, -0.2_443, 0.0_901, -0.0_919, 0.3_396, 0.0_103, -0.3_743, 0.0_701]],
              [8, 0.89, [-0.4_863, 0.0_859, 0.0_875, -0.1_658, 0.9_199, -0.0_114, 0.4_839, 0.4_639]],
              [3, 1_0_0_0, [-0.5_649, 0.2_402, -0.5_518, 0.1_248, 1.1_328, -0.2_443, -0.0_325, -1.0_078]],
              # fmt: on
          ]						)
      def 						snake_case_ (					self					:     int					,     A					:     Union[str, Any]					,     A					:     Tuple					,     A					:     List[Any]						):
           _UpperCAmelCase      :     Union[str, Any]        =   self.get_unet_model(model_id="CompVis/stable-diffusion-v1-4"					,     fpaa=A						)
           _UpperCAmelCase      :     Optional[Any]        =   self.get_latents(A					,     fpaa=A						)
           _UpperCAmelCase      :     Tuple        =   self.get_encoder_hidden_states(A					,     fpaa=A						)

           _UpperCAmelCase      :     Optional[Any]        =   model.apply(
               {"params": params}					,     A					,     jnp.array(A					,     dtype=jnp.intaa						)					,     encoder_hidden_states=A					,     ).sample

           assert sample.shape == latents.shape

           _UpperCAmelCase      :     Optional[int]        =   jnp.asarray(jax.device_get((sample[-1, -2:, -2:, :2].flatten())						)					,     dtype=jnp.floataa						)
           _UpperCAmelCase      :     List[str]        =   jnp.array(A					,     dtype=jnp.floataa						)

           # Found torch (float16) and flax (bfloat16) outputs to be within this tolerance, in the same hardware
           assert jnp.allclose(A					,     A					,     atol=1e-2						)



      @parameterized.expand(
          [
              # fmt: off
              [8_3, 4, [0.1_514, 0.0_807, 0.1_624, 0.1_016, -0.1_896, 0.0_263, 0.0_677, 0.2_310]],
              [1_7, 0.55, [0.1_164, -0.0_216, 0.0_170, 0.1_589, -0.3_120, 0.1_005, -0.0_581, -0.1_458]],
              [8, 0.89, [-0.1_758, -0.0_169, 0.1_004, -0.1_411, 0.1_312, 0.1_103, -0.1_996, 0.2_139]],
              [3, 1_0_0_0, [0.1_214, 0.0_352, -0.0_731, -0.1_562, -0.0_994, -0.0_906, -0.2_340, -0.0_539]],
              # fmt: on
          ]						)
      def 						snake_case_ (					self					:     Optional[Any]					,     A					:     str					,     A					:     str					,     A					:     Optional[Any]						):
           _UpperCAmelCase      :     Optional[int]        =   self.get_unet_model(model_id="stabilityai/stable-diffusion-2"					,     fpaa=A						)
           _UpperCAmelCase      :     Tuple        =   self.get_latents(A					,     shape=(4, 4, 9_6, 9_6)					,     fpaa=A						)
           _UpperCAmelCase      :     Tuple        =   self.get_encoder_hidden_states(A					,     shape=(4, 7_7, 1_0_2_4)					,     fpaa=A						)

           _UpperCAmelCase      :     Any        =   model.apply(
               {"params": params}					,     A					,     jnp.array(A					,     dtype=jnp.intaa						)					,     encoder_hidden_states=A					,     ).sample

           assert sample.shape == latents.shape

           _UpperCAmelCase      :     str        =   jnp.asarray(jax.device_get((sample[-1, -2:, -2:, :2].flatten())						)					,     dtype=jnp.floataa						)
           _UpperCAmelCase      :     Optional[Any]        =   jnp.array(A					,     dtype=jnp.floataa						)

           # Found torch (float16) and flax (bfloat16) outputs to be within this tolerance, on the same hardware
           assert jnp.allclose(A					,     A					,     atol=1e-2						)





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


_lowerCAmelCase    : List[str]							=							{"vocab_file": "vocab.txt", "tokenizer_file": "tokenizer.json"}

_lowerCAmelCase    : int							=							{
    "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"
        ),
    },
}

_lowerCAmelCase    : List[Any]							=							{
    "google/electra-small-generator": 5_12,
    "google/electra-base-generator": 5_12,
    "google/electra-large-generator": 5_12,
    "google/electra-small-discriminator": 5_12,
    "google/electra-base-discriminator": 5_12,
    "google/electra-large-discriminator": 5_12,
}

_lowerCAmelCase    : Optional[Any]							=							{
    "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_  (    _UpperCamelCase						):
      __SCREAMING_SNAKE_CASE						:       Optional[Any]								=			VOCAB_FILES_NAMES
      __SCREAMING_SNAKE_CASE						:       Any								=			PRETRAINED_VOCAB_FILES_MAP
      __SCREAMING_SNAKE_CASE						:       List[str]								=			PRETRAINED_INIT_CONFIGURATION
      __SCREAMING_SNAKE_CASE						:       List[str]								=			PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
      __SCREAMING_SNAKE_CASE						:       Tuple								=			ElectraTokenizer



      def __init__(					self					:     Dict					,     A					:     Dict=None					,     A					:     Optional[int]=None					,     A					:     Dict=True					,     A					:     Optional[Any]="[UNK]"					,     A					:     Any="[SEP]"					,     A					:     str="[PAD]"					,     A					:     Tuple="[CLS]"					,     A					:     Optional[Any]="[MASK]"					,     A					:     Any=True					,     A					:     Tuple=None					,     **A					:     Any					,     ):
           super().__init__(
               A					,     tokenizer_file=A					,     do_lower_case=A					,     unk_token=A					,     sep_token=A					,     pad_token=A					,     cls_token=A					,     mask_token=A					,     tokenize_chinese_chars=A					,     strip_accents=A					,     **A					,     )

           _UpperCAmelCase      :     List[str]        =   json.loads(self.backend_tokenizer.normalizer.__getstate__()						)
           if (
               normalizer_state.get("lowercase"					,     A						) != do_lower_case
               or normalizer_state.get("strip_accents"					,     A						) != strip_accents
               or normalizer_state.get("handle_chinese_chars"					,     A						) != tokenize_chinese_chars
           ):
                _UpperCAmelCase      :     Union[str, Any]        =   getattr(A					,     normalizer_state.pop("type"						)						)
                _UpperCAmelCase      :     Dict        =   do_lower_case
                _UpperCAmelCase      :     Optional[int]        =   strip_accents
                _UpperCAmelCase      :     Any        =   tokenize_chinese_chars
                _UpperCAmelCase      :     Optional[Any]        =   normalizer_class(**A						)

           _UpperCAmelCase      :     int        =   do_lower_case



      def 						snake_case_ (					self					:     Tuple					,     A					:     str					,     A					:     int=None						):
           _UpperCAmelCase      :     Dict        =   [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					:     Any					,     A					:     List[int]					,     A					:     Optional[List[int]] = None						):
           _UpperCAmelCase      :     Any        =   [self.sep_token_id]
           _UpperCAmelCase      :     Dict        =   [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					:     Any					,     A					:     str					,     A					:     Optional[str] = None						):
           _UpperCAmelCase      :     List[Any]        =   self._tokenizer.model.save(A					,     name=A						)
           return tuple(A						)
