

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__     (			A	,		unittest.TestCase			):



 """simple docstring"""







 _lowercase  :       str  			=    ElectraTokenizer
 _lowercase  :       Optional[Any]  			=    ElectraTokenizerFast
 _lowercase  :       str  			=    True
 _lowercase  :       Any  			=    True
 _lowercase  :       Tuple  			=    filter_non_english

 def  __magic_name__							(		self			:						Dict							):






      '''simple docstring'''




      super().setUp()

      _lowerCAmelCase :       Tuple	   =     [
          "[UNK]",
          "[CLS]",
          "[SEP]",
          "[PAD]",
          "[MASK]",
          "want",
          "##want",
          "##ed",
          "wa",
          "un",
          "runn",
          "##ing",
          ",",
          "low",
          "lowest",
      ]
      _lowerCAmelCase :       Dict	   =     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  __magic_name__							(		self			:						List[str]  ,    A_			:						Union[str, Any]							):






      '''simple docstring'''




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

 def  __magic_name__							(		self			:						Dict							):






      '''simple docstring'''




      _lowerCAmelCase :       Optional[Any]	   =     self.tokenizer_class(self.vocab_file							)

      _lowerCAmelCase :       Optional[int]	   =     tokenizer.tokenize("UNwant\u00E9d,running"							)
      self.assertListEqual(A_  ,    ["un", "##want", "##ed", ",", "runn", "##ing"]							)
      self.assertListEqual(tokenizer.convert_tokens_to_ids(A_							)  ,    [9, 6, 7, 1_2, 1_0, 1_1]							)

 def  __magic_name__							(		self			:						str							):






      '''simple docstring'''




      if not self.test_rust_tokenizer:
           return

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

      _lowerCAmelCase :       str	   =     "UNwant\u00E9d,running"

      _lowerCAmelCase :       Dict	   =     tokenizer.tokenize(A_							)
      _lowerCAmelCase :       Tuple	   =     rust_tokenizer.tokenize(A_							)
      self.assertListEqual(A_  ,    A_							)

      _lowerCAmelCase :       Union[str, Any]	   =     tokenizer.encode(A_  ,    add_special_tokens=A_							)
      _lowerCAmelCase :       int	   =     rust_tokenizer.encode(A_  ,    add_special_tokens=A_							)
      self.assertListEqual(A_  ,    A_							)

      _lowerCAmelCase :       Dict	   =     self.get_rust_tokenizer()
      _lowerCAmelCase :       int	   =     tokenizer.encode(A_							)
      _lowerCAmelCase :       Any	   =     rust_tokenizer.encode(A_							)
      self.assertListEqual(A_  ,    A_							)

      # With lower casing
      _lowerCAmelCase :       Any	   =     self.get_tokenizer(do_lower_case=A_							)
      _lowerCAmelCase :       List[Any]	   =     self.get_rust_tokenizer(do_lower_case=A_							)

      _lowerCAmelCase :       Dict	   =     "UNwant\u00E9d,running"

      _lowerCAmelCase :       List[str]	   =     tokenizer.tokenize(A_							)
      _lowerCAmelCase :       int	   =     rust_tokenizer.tokenize(A_							)
      self.assertListEqual(A_  ,    A_							)

      _lowerCAmelCase :       Tuple	   =     tokenizer.encode(A_  ,    add_special_tokens=A_							)
      _lowerCAmelCase :       str	   =     rust_tokenizer.encode(A_  ,    add_special_tokens=A_							)
      self.assertListEqual(A_  ,    A_							)

      _lowerCAmelCase :       str	   =     self.get_rust_tokenizer()
      _lowerCAmelCase :       str	   =     tokenizer.encode(A_							)
      _lowerCAmelCase :       Tuple	   =     rust_tokenizer.encode(A_							)
      self.assertListEqual(A_  ,    A_							)

 def  __magic_name__							(		self			:						Optional[int]							):






      '''simple docstring'''




      _lowerCAmelCase :       str	   =     BasicTokenizer()

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

 def  __magic_name__							(		self			:						Union[str, Any]							):






      '''simple docstring'''




      _lowerCAmelCase :       List[Any]	   =     BasicTokenizer(do_lower_case=A_							)

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

 def  __magic_name__							(		self			:						Tuple							):






      '''simple docstring'''




      _lowerCAmelCase :       List[str]	   =     BasicTokenizer(do_lower_case=A_  ,    strip_accents=A_							)

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

 def  __magic_name__							(		self			:						List[str]							):






      '''simple docstring'''




      _lowerCAmelCase :       Union[str, Any]	   =     BasicTokenizer(do_lower_case=A_  ,    strip_accents=A_							)

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

 def  __magic_name__							(		self			:						Any							):






      '''simple docstring'''




      _lowerCAmelCase :       Dict	   =     BasicTokenizer(do_lower_case=A_							)

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

 def  __magic_name__							(		self			:						Optional[int]							):






      '''simple docstring'''




      _lowerCAmelCase :       int	   =     BasicTokenizer(do_lower_case=A_							)

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

 def  __magic_name__							(		self			:						str							):






      '''simple docstring'''




      _lowerCAmelCase :       Optional[Any]	   =     BasicTokenizer(do_lower_case=A_  ,    strip_accents=A_							)

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

 def  __magic_name__							(		self			:						Union[str, Any]							):






      '''simple docstring'''




      _lowerCAmelCase :       str	   =     BasicTokenizer(do_lower_case=A_  ,    strip_accents=A_							)

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

 def  __magic_name__							(		self			:						Tuple							):






      '''simple docstring'''




      _lowerCAmelCase :       Union[str, Any]	   =     BasicTokenizer(do_lower_case=A_  ,    never_split=["[UNK]"]							)

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

 def  __magic_name__							(		self			:						Union[str, Any]							):






      '''simple docstring'''




      _lowerCAmelCase :       Union[str, Any]	   =     ["[UNK]", "[CLS]", "[SEP]", "want", "##want", "##ed", "wa", "un", "runn", "##ing"]

      _lowerCAmelCase :       Union[str, Any]	   =     {}
      for i, token in enumerate(A_							):
           _lowerCAmelCase :       List[str]	   =     i
      _lowerCAmelCase :       Optional[int]	   =     WordpieceTokenizer(vocab=A_  ,    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  __magic_name__							(		self			:						Optional[int]							):






      '''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  __magic_name__							(		self			:						int							):






      '''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  __magic_name__							(		self			:						Dict							):






      '''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  __magic_name__							(		self			:						Tuple							):






      '''simple docstring'''




      _lowerCAmelCase :       Any	   =     self.get_tokenizer()
      _lowerCAmelCase :       Optional[int]	   =     self.get_rust_tokenizer()

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

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

 @slow
 def  __magic_name__							(		self			:						Optional[int]							):






      '''simple docstring'''




      _lowerCAmelCase :       str	   =     self.tokenizer_class.from_pretrained("google/electra-base-discriminator"							)

      _lowerCAmelCase :       Dict	   =     tokenizer.encode("sequence builders"  ,    add_special_tokens=A_							)
      _lowerCAmelCase :       Tuple	   =     tokenizer.encode("multi-sequence build"  ,    add_special_tokens=A_							)

      _lowerCAmelCase :       str	   =     tokenizer.build_inputs_with_special_tokens(A_							)
      _lowerCAmelCase :       Any	   =     tokenizer.build_inputs_with_special_tokens(A_  ,    A_							)

      assert encoded_sentence == [1_0_1] + text + [1_0_2]
      assert encoded_pair == [1_0_1] + text + [1_0_2] + text_a + [1_0_2]

 def  __magic_name__							(		self			:						int							):






      '''simple docstring'''




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

                _lowerCAmelCase :       Any	   =     F'''A, naïve {tokenizer_r.mask_token} AllenNLP sentence.'''
                _lowerCAmelCase :       int	   =     tokenizer_r.encode_plus(
                    A_  ,    return_attention_mask=A_  ,    return_token_type_ids=A_  ,    return_offsets_mapping=A_  ,    add_special_tokens=A_  ,    )

                _lowerCAmelCase :       int	   =     tokenizer_r.do_lower_case if hasattr(A_  ,    "do_lower_case"							) else False
                _lowerCAmelCase :       List[str]	   =     (
                    [
                        ((0, 0), tokenizer_r.cls_token),
                        ((0, 1), "A"),
                        ((1, 2), ","),
                        ((3, 5), "na"),
                        ((5, 6), "##ï"),
                        ((6, 8), "##ve"),
                        ((9, 1_5), tokenizer_r.mask_token),
                        ((1_6, 2_1), "Allen"),
                        ((2_1, 2_3), "##NL"),
                        ((2_3, 2_4), "##P"),
                        ((2_5, 3_3), "sentence"),
                        ((3_3, 3_4), "."),
                        ((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, 1_5), tokenizer_r.mask_token),
                        ((1_6, 2_1), "allen"),
                        ((2_1, 2_3), "##nl"),
                        ((2_3, 2_4), "##p"),
                        ((2_5, 3_3), "sentence"),
                        ((3_3, 3_4), "."),
                        ((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  __magic_name__							(		self			:						Optional[Any]							):






      '''simple docstring'''




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

                _lowerCAmelCase :       Optional[int]	   =     tokenizer_p.encode(A_  ,    add_special_tokens=A_							)
                _lowerCAmelCase :       Dict	   =     tokenizer_r.encode(A_  ,    add_special_tokens=A_							)

                _lowerCAmelCase :       Dict	   =     tokenizer_r.convert_ids_to_tokens(A_							)
                _lowerCAmelCase :       Optional[int]	   =     tokenizer_p.convert_ids_to_tokens(A_							)

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

                _lowerCAmelCase :       Optional[int]	   =     False
                _lowerCAmelCase :       List[Any]	   =     self.rust_tokenizer_class.from_pretrained(A_  ,    **A_							)
                _lowerCAmelCase :       Union[str, Any]	   =     self.tokenizer_class.from_pretrained(A_  ,    **A_							)

                _lowerCAmelCase :       Any	   =     tokenizer_r.encode(A_  ,    add_special_tokens=A_							)
                _lowerCAmelCase :       Optional[Any]	   =     tokenizer_p.encode(A_  ,    add_special_tokens=A_							)

                _lowerCAmelCase :       Any	   =     tokenizer_r.convert_ids_to_tokens(A_							)
                _lowerCAmelCase :       List[str]	   =     tokenizer_p.convert_ids_to_tokens(A_							)

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









import argparse

import torch

from transformers import NystromformerConfig, NystromformerForMaskedLM







def 						_snake_case		(     SCREAMING_SNAKE_CASE					)							->   Tuple:

     """simple docstring"""







     if "model" in orig_key:
          _lowerCAmelCase :       Tuple	   =     orig_key.replace("model."		,				""					)
     if "norm1" in orig_key:
          _lowerCAmelCase :       Optional[Any]	   =     orig_key.replace("norm1"		,				"attention.output.LayerNorm"					)
     if "norm2" in orig_key:
          _lowerCAmelCase :       Optional[int]	   =     orig_key.replace("norm2"		,				"output.LayerNorm"					)
     if "norm" in orig_key:
          _lowerCAmelCase :       Any	   =     orig_key.replace("norm"		,				"LayerNorm"					)
     if "transformer" in orig_key:
          _lowerCAmelCase :       str	   =     orig_key.split("."					)[0].split("_"					)[-1]
          _lowerCAmelCase :       Any	   =     orig_key.replace(f'''transformer_{layer_num}'''		,				f'''encoder.layer.{layer_num}'''					)
     if "mha.attn" in orig_key:
          _lowerCAmelCase :       int	   =     orig_key.replace("mha.attn"		,				"attention.self"					)
     if "mha" in orig_key:
          _lowerCAmelCase :       Dict	   =     orig_key.replace("mha"		,				"attention"					)
     if "W_q" in orig_key:
          _lowerCAmelCase :       Union[str, Any]	   =     orig_key.replace("W_q"		,				"self.query"					)
     if "W_k" in orig_key:
          _lowerCAmelCase :       Tuple	   =     orig_key.replace("W_k"		,				"self.key"					)
     if "W_v" in orig_key:
          _lowerCAmelCase :       Optional[int]	   =     orig_key.replace("W_v"		,				"self.value"					)
     if "ff1" in orig_key:
          _lowerCAmelCase :       Tuple	   =     orig_key.replace("ff1"		,				"intermediate.dense"					)
     if "ff2" in orig_key:
          _lowerCAmelCase :       List[Any]	   =     orig_key.replace("ff2"		,				"output.dense"					)
     if "ff" in orig_key:
          _lowerCAmelCase :       str	   =     orig_key.replace("ff"		,				"output.dense"					)
     if "mlm_class" in orig_key:
          _lowerCAmelCase :       int	   =     orig_key.replace("mlm.mlm_class"		,				"cls.predictions.decoder"					)
     if "mlm" in orig_key:
          _lowerCAmelCase :       Union[str, Any]	   =     orig_key.replace("mlm"		,				"cls.predictions.transform"					)
     if "cls" not in orig_key:
          _lowerCAmelCase :       Optional[int]	   =     "nystromformer." + orig_key

     return orig_key







def 						_snake_case		(     SCREAMING_SNAKE_CASE		,				SCREAMING_SNAKE_CASE					)							->   Any:

     """simple docstring"""







     for key in orig_state_dict.copy().keys():
          _lowerCAmelCase :       List[str]	   =     orig_state_dict.pop(SCREAMING_SNAKE_CASE					)

          if ("pooler" in key) or ("sen_class" in key) or ("conv.bias" in key):
               continue
          else:
               _lowerCAmelCase :       int	   =     val

     _lowerCAmelCase :       Tuple	   =     orig_state_dict["cls.predictions.decoder.bias"]
     _lowerCAmelCase :       Any	   =     (
         torch.arange(config.max_position_embeddings					).expand((1, -1)					) + 2
     )

     return orig_state_dict







def 						_snake_case		(     SCREAMING_SNAKE_CASE		,				SCREAMING_SNAKE_CASE		,				SCREAMING_SNAKE_CASE					)							->   Optional[Any]:

     """simple docstring"""







     _lowerCAmelCase :       Optional[Any]	   =     torch.load(SCREAMING_SNAKE_CASE		,				map_location="cpu"					)["model_state_dict"]
     _lowerCAmelCase :       Optional[Any]	   =     NystromformerConfig.from_json_file(SCREAMING_SNAKE_CASE					)
     _lowerCAmelCase :       List[str]	   =     NystromformerForMaskedLM(SCREAMING_SNAKE_CASE					)

     _lowerCAmelCase :       Union[str, Any]	   =     convert_checkpoint_helper(SCREAMING_SNAKE_CASE		,				SCREAMING_SNAKE_CASE					)

     model.load_state_dict(SCREAMING_SNAKE_CASE					)
     model.eval()
     model.save_pretrained(SCREAMING_SNAKE_CASE					)

     print(f'''Checkpoint successfuly converted. Model saved at {pytorch_dump_path}'''					)


if __name__ == "__main__":
  __UpperCAmelCase     					=  argparse.ArgumentParser()
  # Required parameters
  parser.add_argument(
      '--pytorch_model_path', default=None, type=str, required=True, help='Path to Nystromformer pytorch checkpoint.'
  )
  parser.add_argument(
      '--config_file',
      default=None,
      type=str,
      required=True,
      help='The json file for Nystromformer model config.',
  )
  parser.add_argument(
      '--pytorch_dump_path', default=None, type=str, required=True, help='Path to the output PyTorch model.'
  )
  __UpperCAmelCase     					=  parser.parse_args()
  convert_nystromformer_checkpoint(args.pytorch_model_path, args.config_file, args.pytorch_dump_path)






