






"""simple docstring"""





from dataclasses import dataclass
from typing import Any, Dict, Optional

import torch
import torch.nn.functional as F
from torch import nn

from ..configuration_utils import ConfigMixin, register_to_config
from ..models.embeddings import ImagePositionalEmbeddings
from ..utils import BaseOutput, deprecate
from .attention import BasicTransformerBlock
from .embeddings import PatchEmbed
from .modeling_utils import ModelMixin







@dataclass
class 		_a       (						UpperCamelCase_   ):





   '''simple docstring'''






   UpperCamelCase__      					=    42







class 		_a       (						UpperCamelCase_    ,					UpperCamelCase_   ):





   '''simple docstring'''






   @register_to_config
   def __init__(   self			,				UpperCAmelCase_ = 16			,				UpperCAmelCase_ = 88			,				UpperCAmelCase_ = None			,				UpperCAmelCase_ = None			,				UpperCAmelCase_ = 1			,				UpperCAmelCase_ = 0.0			,				UpperCAmelCase_ = 32			,				UpperCAmelCase_ = None			,				UpperCAmelCase_ = False			,				UpperCAmelCase_ = None			,				UpperCAmelCase_ = None			,				UpperCAmelCase_ = None			,				UpperCAmelCase_ = "geglu"			,				UpperCAmelCase_ = None			,				UpperCAmelCase_ = False			,				UpperCAmelCase_ = False			,				UpperCAmelCase_ = False			,				UpperCAmelCase_ = "layer_norm"			,				UpperCAmelCase_ = True			,				)	-> Optional[int]:




          '''simple docstring'''




          super().__init__()
          lowercase__:    Tuple        =      use_linear_projection
          lowercase__:    Optional[Any]        =      num_attention_heads
          lowercase__:    Optional[int]        =      attention_head_dim
          lowercase__:    Dict        =      num_attention_heads * attention_head_dim

          # 1. Transformer2DModel can process both standard continuous images of shape `(batch_size, num_channels, width, height)` as well as quantized image embeddings of shape `(batch_size, num_image_vectors)`
          # Define whether input is continuous or discrete depending on configuration
          lowercase__:    Dict        =      (in_channels is not None) and (patch_size is None)
          lowercase__:    Optional[int]        =      num_vector_embeds is not None
          lowercase__:    Union[str, Any]        =      in_channels is not None and patch_size is not None

          if norm_type == "layer_norm" and num_embeds_ada_norm is not None:
                 lowercase__:    Optional[int]        =      (
                     F"""The configuration file of this model: {self.__class__} is outdated. `norm_type` is either not set or"""
                     " incorrectly set to `\'layer_norm\'`.Make sure to set `norm_type` to `\'ada_norm\'` in the config."
                     " Please make sure to update the config accordingly as leaving `norm_type` might led to incorrect"
                     " results in future versions. If you have downloaded this checkpoint from the Hugging Face Hub, it"
                     " would be very nice if you could open a Pull request for the `transformer/config.json` file"
                 )
                 deprecate("norm_type!=num_embeds_ada_norm"			,				"1.0.0"			,				__SCREAMING_SNAKE_CASE			,				standard_warn=__SCREAMING_SNAKE_CASE)
                 lowercase__:    Any        =      "ada_norm"

          if self.is_input_continuous and self.is_input_vectorized:
                 raise ValueError(
                     F"""Cannot define both `in_channels`: {in_channels} and `num_vector_embeds`: {num_vector_embeds}. Make"""
                     " sure that either `in_channels` or `num_vector_embeds` is None.")
          elif self.is_input_vectorized and self.is_input_patches:
                 raise ValueError(
                     F"""Cannot define both `num_vector_embeds`: {num_vector_embeds} and `patch_size`: {patch_size}. Make"""
                     " sure that either `num_vector_embeds` or `num_patches` is None.")
          elif not self.is_input_continuous and not self.is_input_vectorized and not self.is_input_patches:
                 raise ValueError(
                     F"""Has to define `in_channels`: {in_channels}, `num_vector_embeds`: {num_vector_embeds}, or patch_size:"""
                     F""" {patch_size}. Make sure that `in_channels`, `num_vector_embeds` or `num_patches` is not None.""")

          # 2. Define input layers
          if self.is_input_continuous:
                 lowercase__:    Dict        =      in_channels

                 lowercase__:    Optional[int]        =      torch.nn.GroupNorm(num_groups=__SCREAMING_SNAKE_CASE			,				num_channels=__SCREAMING_SNAKE_CASE			,				eps=1E-6			,				affine=__SCREAMING_SNAKE_CASE)
                 if use_linear_projection:
                        lowercase__:    Union[str, Any]        =      nn.Linear(__SCREAMING_SNAKE_CASE			,				__SCREAMING_SNAKE_CASE)
                 else:
                        lowercase__:    Tuple        =      nn.Convad(__SCREAMING_SNAKE_CASE			,				__SCREAMING_SNAKE_CASE			,				kernel_size=1			,				stride=1			,				padding=0)
          elif self.is_input_vectorized:
                 assert sample_size is not None, "Transformer2DModel over discrete input must provide sample_size"
                 assert num_vector_embeds is not None, "Transformer2DModel over discrete input must provide num_embed"

                 lowercase__:    Optional[int]        =      sample_size
                 lowercase__:    Optional[Any]        =      sample_size
                 lowercase__:    List[str]        =      num_vector_embeds
                 lowercase__:    str        =      self.height * self.width

                 lowercase__:    int        =      ImagePositionalEmbeddings(
                     num_embed=__SCREAMING_SNAKE_CASE			,				embed_dim=__SCREAMING_SNAKE_CASE			,				height=self.height			,				width=self.width)
          elif self.is_input_patches:
                 assert sample_size is not None, "Transformer2DModel over patched input must provide sample_size"

                 lowercase__:    List[Any]        =      sample_size
                 lowercase__:    List[str]        =      sample_size

                 lowercase__:    int        =      patch_size
                 lowercase__:    Union[str, Any]        =      PatchEmbed(
                     height=__SCREAMING_SNAKE_CASE			,				width=__SCREAMING_SNAKE_CASE			,				patch_size=__SCREAMING_SNAKE_CASE			,				in_channels=__SCREAMING_SNAKE_CASE			,				embed_dim=__SCREAMING_SNAKE_CASE			,				)

          # 3. Define transformers blocks
          lowercase__:    Dict        =      nn.ModuleList(
              [
                  BasicTransformerBlock(
                      __SCREAMING_SNAKE_CASE			,				__SCREAMING_SNAKE_CASE			,				__SCREAMING_SNAKE_CASE			,				dropout=__SCREAMING_SNAKE_CASE			,				cross_attention_dim=__SCREAMING_SNAKE_CASE			,				activation_fn=__SCREAMING_SNAKE_CASE			,				num_embeds_ada_norm=__SCREAMING_SNAKE_CASE			,				attention_bias=__SCREAMING_SNAKE_CASE			,				only_cross_attention=__SCREAMING_SNAKE_CASE			,				upcast_attention=__SCREAMING_SNAKE_CASE			,				norm_type=__SCREAMING_SNAKE_CASE			,				norm_elementwise_affine=__SCREAMING_SNAKE_CASE			,				)
                  for d in range(__SCREAMING_SNAKE_CASE)
              ])

          # 4. Define output layers
          lowercase__:    Any        =      in_channels if out_channels is None else out_channels
          if self.is_input_continuous:
                 # TODO: should use out_channels for continuous projections
                 if use_linear_projection:
                        lowercase__:    str        =      nn.Linear(__SCREAMING_SNAKE_CASE			,				__SCREAMING_SNAKE_CASE)
                 else:
                        lowercase__:    List[str]        =      nn.Convad(__SCREAMING_SNAKE_CASE			,				__SCREAMING_SNAKE_CASE			,				kernel_size=1			,				stride=1			,				padding=0)
          elif self.is_input_vectorized:
                 lowercase__:    Union[str, Any]        =      nn.LayerNorm(__SCREAMING_SNAKE_CASE)
                 lowercase__:    Tuple        =      nn.Linear(__SCREAMING_SNAKE_CASE			,				self.num_vector_embeds - 1)
          elif self.is_input_patches:
                 lowercase__:    List[Any]        =      nn.LayerNorm(__SCREAMING_SNAKE_CASE			,				elementwise_affine=__SCREAMING_SNAKE_CASE			,				eps=1E-6)
                 lowercase__:    Dict        =      nn.Linear(__SCREAMING_SNAKE_CASE			,				2 * inner_dim)
                 lowercase__:    Dict        =      nn.Linear(__SCREAMING_SNAKE_CASE			,				patch_size * patch_size * self.out_channels)





   def __lowercase    (   self			,				UpperCAmelCase_			,				UpperCAmelCase_ = None			,				UpperCAmelCase_ = None			,				UpperCAmelCase_ = None			,				UpperCAmelCase_ = None			,				UpperCAmelCase_ = None			,				UpperCAmelCase_ = None			,				UpperCAmelCase_ = True			,				)	-> List[Any]:




          '''simple docstring'''




          if attention_mask is not None and attention_mask.ndim == 2:
                 # assume that mask is expressed as:
                 #   (1 = keep,      0 = discard)
                 # convert mask into a bias that can be added to attention scores:
                 #       (keep = +0,     discard = -10000.0)
                 lowercase__:    Optional[int]        =      (1 - attention_mask.to(hidden_states.dtype)) * -10_000.0
                 lowercase__:    List[Any]        =      attention_mask.unsqueeze(1)

          # convert encoder_attention_mask to a bias the same way we do for attention_mask
          if encoder_attention_mask is not None and encoder_attention_mask.ndim == 2:
                 lowercase__:    int        =      (1 - encoder_attention_mask.to(hidden_states.dtype)) * -10_000.0
                 lowercase__:    int        =      encoder_attention_mask.unsqueeze(1)

          # 1. Input
          if self.is_input_continuous:
                 lowercase__  ,     lowercase__  ,     lowercase__  ,     lowercase__:    List[str]        =      hidden_states.shape
                 lowercase__:    Union[str, Any]        =      hidden_states

                 lowercase__:    Dict        =      self.norm(__SCREAMING_SNAKE_CASE)
                 if not self.use_linear_projection:
                        lowercase__:    List[Any]        =      self.proj_in(__SCREAMING_SNAKE_CASE)
                        lowercase__:    int        =      hidden_states.shape[1]
                        lowercase__:    Any        =      hidden_states.permute(0			,				2			,				3			,				1).reshape(__SCREAMING_SNAKE_CASE			,				height * width			,				__SCREAMING_SNAKE_CASE)
                 else:
                        lowercase__:    Dict        =      hidden_states.shape[1]
                        lowercase__:    Union[str, Any]        =      hidden_states.permute(0			,				2			,				3			,				1).reshape(__SCREAMING_SNAKE_CASE			,				height * width			,				__SCREAMING_SNAKE_CASE)
                        lowercase__:    List[str]        =      self.proj_in(__SCREAMING_SNAKE_CASE)
          elif self.is_input_vectorized:
                 lowercase__:    Union[str, Any]        =      self.latent_image_embedding(__SCREAMING_SNAKE_CASE)
          elif self.is_input_patches:
                 lowercase__:    Dict        =      self.pos_embed(__SCREAMING_SNAKE_CASE)

          # 2. Blocks
          for block in self.transformer_blocks:
                 lowercase__:    int        =      block(
                     __SCREAMING_SNAKE_CASE			,				attention_mask=__SCREAMING_SNAKE_CASE			,				encoder_hidden_states=__SCREAMING_SNAKE_CASE			,				encoder_attention_mask=__SCREAMING_SNAKE_CASE			,				timestep=__SCREAMING_SNAKE_CASE			,				cross_attention_kwargs=__SCREAMING_SNAKE_CASE			,				class_labels=__SCREAMING_SNAKE_CASE			,				)

          # 3. Output
          if self.is_input_continuous:
                 if not self.use_linear_projection:
                        lowercase__:    List[Any]        =      hidden_states.reshape(__SCREAMING_SNAKE_CASE			,				__SCREAMING_SNAKE_CASE			,				__SCREAMING_SNAKE_CASE			,				__SCREAMING_SNAKE_CASE).permute(0			,				3			,				1			,				2).contiguous()
                        lowercase__:    Any        =      self.proj_out(__SCREAMING_SNAKE_CASE)
                 else:
                        lowercase__:    Any        =      self.proj_out(__SCREAMING_SNAKE_CASE)
                        lowercase__:    int        =      hidden_states.reshape(__SCREAMING_SNAKE_CASE			,				__SCREAMING_SNAKE_CASE			,				__SCREAMING_SNAKE_CASE			,				__SCREAMING_SNAKE_CASE).permute(0			,				3			,				1			,				2).contiguous()

                 lowercase__:    Optional[Any]        =      hidden_states + residual
          elif self.is_input_vectorized:
                 lowercase__:    Union[str, Any]        =      self.norm_out(__SCREAMING_SNAKE_CASE)
                 lowercase__:    Tuple        =      self.out(__SCREAMING_SNAKE_CASE)
                 # (batch, self.num_vector_embeds - 1, self.num_latent_pixels)
                 lowercase__:    Union[str, Any]        =      logits.permute(0			,				2			,				1)

                 # log(p(x_0))
                 lowercase__:    Tuple        =      F.log_softmax(logits.double()			,				dim=1).float()
          elif self.is_input_patches:
                 # TODO: cleanup!
                 lowercase__:    int        =      self.transformer_blocks[0].norma.emb(
                     __SCREAMING_SNAKE_CASE			,				__SCREAMING_SNAKE_CASE			,				hidden_dtype=hidden_states.dtype)
                 lowercase__  ,     lowercase__:    Tuple        =      self.proj_out_a(F.silu(__SCREAMING_SNAKE_CASE)).chunk(2			,				dim=1)
                 lowercase__:    Optional[int]        =      self.norm_out(__SCREAMING_SNAKE_CASE) * (1 + scale[:, None]) + shift[:, None]
                 lowercase__:    Optional[int]        =      self.proj_out_a(__SCREAMING_SNAKE_CASE)

                 # unpatchify
                 lowercase__:    Union[str, Any]        =      int(hidden_states.shape[1] ** 0.5)
                 lowercase__:    Dict        =      hidden_states.reshape(
                     shape=(-1, height, width, self.patch_size, self.patch_size, self.out_channels))
                 lowercase__:    List[Any]        =      torch.einsum("nhwpqc->nchpwq"			,				__SCREAMING_SNAKE_CASE)
                 lowercase__:    List[Any]        =      hidden_states.reshape(
                     shape=(-1, self.out_channels, height * self.patch_size, width * self.patch_size))

          if not return_dict:
                 return (output,)

          return TransformeraDModelOutput(sample=__SCREAMING_SNAKE_CASE)














"""simple docstring"""





import os
import unittest

from transformers import ElectraTokenizerFast
from transformers.models.electra.tokenization_electra import (
    VOCAB_FILES_NAMES,
    BasicTokenizer,
    ElectraTokenizer,
    WordpieceTokenizer,
    _is_control,
    _is_punctuation,
    _is_whitespace,
)
from transformers.testing_utils import require_tokenizers, slow

from ...test_tokenization_common import TokenizerTesterMixin, filter_non_english







@require_tokenizers
class 		_a       (						lowercase_    ,					unittest.TestCase   ):





   '''simple docstring'''






   UpperCamelCase__      					=    ElectraTokenizer
   UpperCamelCase__      					=    ElectraTokenizerFast
   UpperCamelCase__      					=    True
   UpperCamelCase__      					=    True
   UpperCamelCase__      					=    filter_non_english





   def __lowercase    (   self)	-> str:




          '''simple docstring'''




          super().setUp()

          lowercase__:    List[str]        =      [
              "[UNK]",
              "[CLS]",
              "[SEP]",
              "[PAD]",
              "[MASK]",
              "want",
              "##want",
              "##ed",
              "wa",
              "un",
              "runn",
              "##ing",
              ",",
              "low",
              "lowest",
          ]
          lowercase__:    int        =      os.path.join(self.tmpdirname			,				VOCAB_FILES_NAMES["vocab_file"])
          with open(self.vocab_file			,				"w"			,				encoding="utf-8") as vocab_writer:
                 vocab_writer.write("".join([x + "\n" for x in vocab_tokens]))





   def __lowercase    (   self			,				UpperCAmelCase_)	-> Dict:




          '''simple docstring'''




          lowercase__:    str        =      "UNwant\u00E9d,running"
          lowercase__:    List[Any]        =      "unwanted, running"
          return input_text, output_text





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




          '''simple docstring'''




          lowercase__:    str        =      self.tokenizer_class(self.vocab_file)

          lowercase__:    Tuple        =      tokenizer.tokenize("UNwant\u00E9d,running")
          self.assertListEqual(UpperCAmelCase_			,				["un", "##want", "##ed", ",", "runn", "##ing"])
          self.assertListEqual(tokenizer.convert_tokens_to_ids(UpperCAmelCase_)			,				[9, 6, 7, 12, 10, 11])





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




          '''simple docstring'''




          if not self.test_rust_tokenizer:
                 return

          lowercase__:    Dict        =      self.get_tokenizer()
          lowercase__:    List[Any]        =      self.get_rust_tokenizer()

          lowercase__:    Optional[Any]        =      "UNwant\u00E9d,running"

          lowercase__:    Tuple        =      tokenizer.tokenize(UpperCAmelCase_)
          lowercase__:    Tuple        =      rust_tokenizer.tokenize(UpperCAmelCase_)
          self.assertListEqual(UpperCAmelCase_			,				UpperCAmelCase_)

          lowercase__:    List[str]        =      tokenizer.encode(UpperCAmelCase_			,				add_special_tokens=UpperCAmelCase_)
          lowercase__:    Optional[Any]        =      rust_tokenizer.encode(UpperCAmelCase_			,				add_special_tokens=UpperCAmelCase_)
          self.assertListEqual(UpperCAmelCase_			,				UpperCAmelCase_)

          lowercase__:    List[Any]        =      self.get_rust_tokenizer()
          lowercase__:    int        =      tokenizer.encode(UpperCAmelCase_)
          lowercase__:    str        =      rust_tokenizer.encode(UpperCAmelCase_)
          self.assertListEqual(UpperCAmelCase_			,				UpperCAmelCase_)

          # With lower casing
          lowercase__:    Optional[Any]        =      self.get_tokenizer(do_lower_case=UpperCAmelCase_)
          lowercase__:    List[Any]        =      self.get_rust_tokenizer(do_lower_case=UpperCAmelCase_)

          lowercase__:    str        =      "UNwant\u00E9d,running"

          lowercase__:    str        =      tokenizer.tokenize(UpperCAmelCase_)
          lowercase__:    Tuple        =      rust_tokenizer.tokenize(UpperCAmelCase_)
          self.assertListEqual(UpperCAmelCase_			,				UpperCAmelCase_)

          lowercase__:    List[Any]        =      tokenizer.encode(UpperCAmelCase_			,				add_special_tokens=UpperCAmelCase_)
          lowercase__:    List[str]        =      rust_tokenizer.encode(UpperCAmelCase_			,				add_special_tokens=UpperCAmelCase_)
          self.assertListEqual(UpperCAmelCase_			,				UpperCAmelCase_)

          lowercase__:    Any        =      self.get_rust_tokenizer()
          lowercase__:    Dict        =      tokenizer.encode(UpperCAmelCase_)
          lowercase__:    List[Any]        =      rust_tokenizer.encode(UpperCAmelCase_)
          self.assertListEqual(UpperCAmelCase_			,				UpperCAmelCase_)





   def __lowercase    (   self)	-> Dict:




          '''simple docstring'''




          lowercase__:    Optional[int]        =      BasicTokenizer()

          self.assertListEqual(tokenizer.tokenize("ah\u535A\u63A8zz")			,				["ah", "\u535A", "\u63A8", "zz"])





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




          '''simple docstring'''




          lowercase__:    str        =      BasicTokenizer(do_lower_case=UpperCAmelCase_)

          self.assertListEqual(
              tokenizer.tokenize(" \tHeLLo!how  \n Are yoU?  ")			,				["hello", "!", "how", "are", "you", "?"])
          self.assertListEqual(tokenizer.tokenize("H\u00E9llo")			,				["hello"])





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




          '''simple docstring'''




          lowercase__:    Any        =      BasicTokenizer(do_lower_case=UpperCAmelCase_			,				strip_accents=UpperCAmelCase_)

          self.assertListEqual(
              tokenizer.tokenize(" \tHäLLo!how  \n Are yoU?  ")			,				["hällo", "!", "how", "are", "you", "?"])
          self.assertListEqual(tokenizer.tokenize("H\u00E9llo")			,				["h\u00E9llo"])





   def __lowercase    (   self)	-> int:




          '''simple docstring'''




          lowercase__:    Tuple        =      BasicTokenizer(do_lower_case=UpperCAmelCase_			,				strip_accents=UpperCAmelCase_)

          self.assertListEqual(
              tokenizer.tokenize(" \tHäLLo!how  \n Are yoU?  ")			,				["hallo", "!", "how", "are", "you", "?"])
          self.assertListEqual(tokenizer.tokenize("H\u00E9llo")			,				["hello"])





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




          '''simple docstring'''




          lowercase__:    int        =      BasicTokenizer(do_lower_case=UpperCAmelCase_)

          self.assertListEqual(
              tokenizer.tokenize(" \tHäLLo!how  \n Are yoU?  ")			,				["hallo", "!", "how", "are", "you", "?"])
          self.assertListEqual(tokenizer.tokenize("H\u00E9llo")			,				["hello"])





   def __lowercase    (   self)	-> Optional[Any]:




          '''simple docstring'''




          lowercase__:    Optional[int]        =      BasicTokenizer(do_lower_case=UpperCAmelCase_)

          self.assertListEqual(
              tokenizer.tokenize(" \tHeLLo!how  \n Are yoU?  ")			,				["HeLLo", "!", "how", "Are", "yoU", "?"])





   def __lowercase    (   self)	-> Optional[Any]:




          '''simple docstring'''




          lowercase__:    Optional[Any]        =      BasicTokenizer(do_lower_case=UpperCAmelCase_			,				strip_accents=UpperCAmelCase_)

          self.assertListEqual(
              tokenizer.tokenize(" \tHäLLo!how  \n Are yoU?  ")			,				["HäLLo", "!", "how", "Are", "yoU", "?"])





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




          '''simple docstring'''




          lowercase__:    Any        =      BasicTokenizer(do_lower_case=UpperCAmelCase_			,				strip_accents=UpperCAmelCase_)

          self.assertListEqual(
              tokenizer.tokenize(" \tHäLLo!how  \n Are yoU?  ")			,				["HaLLo", "!", "how", "Are", "yoU", "?"])





   def __lowercase    (   self)	-> int:




          '''simple docstring'''




          lowercase__:    List[Any]        =      BasicTokenizer(do_lower_case=UpperCAmelCase_			,				never_split=["[UNK]"])

          self.assertListEqual(
              tokenizer.tokenize(" \tHeLLo!how  \n Are yoU? [UNK]")			,				["HeLLo", "!", "how", "Are", "yoU", "?", "[UNK]"])





   def __lowercase    (   self)	-> int:




          '''simple docstring'''




          lowercase__:    List[str]        =      ["[UNK]", "[CLS]", "[SEP]", "want", "##want", "##ed", "wa", "un", "runn", "##ing"]

          lowercase__:    Dict        =      {}
          for i, token in enumerate(UpperCAmelCase_):
                 lowercase__:    Optional[int]        =      i
          lowercase__:    str        =      WordpieceTokenizer(vocab=UpperCAmelCase_			,				unk_token="[UNK]")

          self.assertListEqual(tokenizer.tokenize("")			,				[])

          self.assertListEqual(tokenizer.tokenize("unwanted running")			,				["un", "##want", "##ed", "runn", "##ing"])

          self.assertListEqual(tokenizer.tokenize("unwantedX running")			,				["[UNK]", "runn", "##ing"])





   def __lowercase    (   self)	-> Dict:




          '''simple docstring'''




          self.assertTrue(_is_whitespace(" "))
          self.assertTrue(_is_whitespace("\t"))
          self.assertTrue(_is_whitespace("\r"))
          self.assertTrue(_is_whitespace("\n"))
          self.assertTrue(_is_whitespace("\u00A0"))

          self.assertFalse(_is_whitespace("A"))
          self.assertFalse(_is_whitespace("-"))





   def __lowercase    (   self)	-> List[Any]:




          '''simple docstring'''




          self.assertTrue(_is_control("\u0005"))

          self.assertFalse(_is_control("A"))
          self.assertFalse(_is_control(" "))
          self.assertFalse(_is_control("\t"))
          self.assertFalse(_is_control("\r"))





   def __lowercase    (   self)	-> List[Any]:




          '''simple docstring'''




          self.assertTrue(_is_punctuation("-"))
          self.assertTrue(_is_punctuation("$"))
          self.assertTrue(_is_punctuation("`"))
          self.assertTrue(_is_punctuation("."))

          self.assertFalse(_is_punctuation("A"))
          self.assertFalse(_is_punctuation(" "))





   def __lowercase    (   self)	-> Tuple:




          '''simple docstring'''




          lowercase__:    Optional[Any]        =      self.get_tokenizer()
          lowercase__:    str        =      self.get_rust_tokenizer()

          # Example taken from the issue https://github.com/huggingface/tokenizers/issues/340
          self.assertListEqual([tokenizer.tokenize(UpperCAmelCase_) for t in ["Test", "\xad", "test"]]			,				[["[UNK]"], [], ["[UNK]"]])

          self.assertListEqual(
              [rust_tokenizer.tokenize(UpperCAmelCase_) for t in ["Test", "\xad", "test"]]			,				[["[UNK]"], [], ["[UNK]"]])





   @slow
   def __lowercase    (   self)	-> int:




          '''simple docstring'''




          lowercase__:    Dict        =      self.tokenizer_class.from_pretrained("google/electra-base-discriminator")

          lowercase__:    Optional[int]        =      tokenizer.encode("sequence builders"			,				add_special_tokens=UpperCAmelCase_)
          lowercase__:    List[str]        =      tokenizer.encode("multi-sequence build"			,				add_special_tokens=UpperCAmelCase_)

          lowercase__:    Dict        =      tokenizer.build_inputs_with_special_tokens(UpperCAmelCase_)
          lowercase__:    Union[str, Any]        =      tokenizer.build_inputs_with_special_tokens(UpperCAmelCase_			,				UpperCAmelCase_)

          assert encoded_sentence == [101] + text + [102]
          assert encoded_pair == [101] + text + [102] + text_a + [102]





   def __lowercase    (   self)	-> List[Any]:




          '''simple docstring'''




          for tokenizer, pretrained_name, kwargs in self.tokenizers_list:
                 with self.subTest(F"""{tokenizer.__class__.__name__} ({pretrained_name})"""):
                        lowercase__:    Any        =      self.rust_tokenizer_class.from_pretrained(UpperCAmelCase_			,				**UpperCAmelCase_)

                        lowercase__:    int        =      F"""A, naïve {tokenizer_r.mask_token} AllenNLP sentence."""
                        lowercase__:    Tuple        =      tokenizer_r.encode_plus(
                            UpperCAmelCase_			,				return_attention_mask=UpperCAmelCase_			,				return_token_type_ids=UpperCAmelCase_			,				return_offsets_mapping=UpperCAmelCase_			,				add_special_tokens=UpperCAmelCase_			,				)

                        lowercase__:    str        =      tokenizer_r.do_lower_case if hasattr(UpperCAmelCase_			,				"do_lower_case") else False
                        lowercase__:    List[Any]        =      (
                            [
                                ((0, 0), tokenizer_r.cls_token),
                                ((0, 1), "A"),
                                ((1, 2), ","),
                                ((3, 5), "na"),
                                ((5, 6), "##ï"),
                                ((6, 8), "##ve"),
                                ((9, 15), tokenizer_r.mask_token),
                                ((16, 21), "Allen"),
                                ((21, 23), "##NL"),
                                ((23, 24), "##P"),
                                ((25, 33), "sentence"),
                                ((33, 34), "."),
                                ((0, 0), tokenizer_r.sep_token),
                            ]
                            if not do_lower_case
                            else [
                                ((0, 0), tokenizer_r.cls_token),
                                ((0, 1), "a"),
                                ((1, 2), ","),
                                ((3, 8), "naive"),
                                ((9, 15), tokenizer_r.mask_token),
                                ((16, 21), "allen"),
                                ((21, 23), "##nl"),
                                ((23, 24), "##p"),
                                ((25, 33), "sentence"),
                                ((33, 34), "."),
                                ((0, 0), tokenizer_r.sep_token),
                            ]
                        )

                        self.assertEqual(
                            [e[1] for e in expected_results]			,				tokenizer_r.convert_ids_to_tokens(tokens["input_ids"]))
                        self.assertEqual([e[0] for e in expected_results]			,				tokens["offset_mapping"])





   def __lowercase    (   self)	-> List[Any]:




          '''simple docstring'''




          lowercase__:    Union[str, Any]        =      ["的", "人", "有"]
          lowercase__:    Any        =      "".join(UpperCAmelCase_)
          for tokenizer, pretrained_name, kwargs in self.tokenizers_list:
                 with self.subTest(F"""{tokenizer.__class__.__name__} ({pretrained_name})"""):
                        lowercase__:    Optional[Any]        =      True
                        lowercase__:    List[str]        =      self.tokenizer_class.from_pretrained(UpperCAmelCase_			,				**UpperCAmelCase_)
                        lowercase__:    Dict        =      self.rust_tokenizer_class.from_pretrained(UpperCAmelCase_			,				**UpperCAmelCase_)

                        lowercase__:    str        =      tokenizer_p.encode(UpperCAmelCase_			,				add_special_tokens=UpperCAmelCase_)
                        lowercase__:    Optional[int]        =      tokenizer_r.encode(UpperCAmelCase_			,				add_special_tokens=UpperCAmelCase_)

                        lowercase__:    Union[str, Any]        =      tokenizer_r.convert_ids_to_tokens(UpperCAmelCase_)
                        lowercase__:    List[str]        =      tokenizer_p.convert_ids_to_tokens(UpperCAmelCase_)

                        # it is expected that each Chinese character is not preceded by "##"
                        self.assertListEqual(UpperCAmelCase_			,				UpperCAmelCase_)
                        self.assertListEqual(UpperCAmelCase_			,				UpperCAmelCase_)

                        lowercase__:    Dict        =      False
                        lowercase__:    Optional[int]        =      self.rust_tokenizer_class.from_pretrained(UpperCAmelCase_			,				**UpperCAmelCase_)
                        lowercase__:    int        =      self.tokenizer_class.from_pretrained(UpperCAmelCase_			,				**UpperCAmelCase_)

                        lowercase__:    str        =      tokenizer_r.encode(UpperCAmelCase_			,				add_special_tokens=UpperCAmelCase_)
                        lowercase__:    Tuple        =      tokenizer_p.encode(UpperCAmelCase_			,				add_special_tokens=UpperCAmelCase_)

                        lowercase__:    Union[str, Any]        =      tokenizer_r.convert_ids_to_tokens(UpperCAmelCase_)
                        lowercase__:    List[str]        =      tokenizer_p.convert_ids_to_tokens(UpperCAmelCase_)

                        # it is expected that only the first Chinese character is not preceded by "##".
                        lowercase__:    List[str]        =      [
                            F"""##{token}""" if idx != 0 else token for idx, token in enumerate(UpperCAmelCase_)
                        ]
                        self.assertListEqual(UpperCAmelCase_			,				UpperCAmelCase_)
                        self.assertListEqual(UpperCAmelCase_			,				UpperCAmelCase_)






