






"""simple docstring"""





import argparse
import os
import re
import zipfile

import torch

from transformers import MegatronBertConfig






def     A(  snake_case_						,       snake_case_						,       snake_case_=0		):
       """simple docstring"""





       if name is None:
              lowercase__:    Tuple        =      None
       else:
              lowercase__:    List[Any]        =      "." * max(0						,       spaces - 2		) + "# {:" + str(50 - spaces		) + "s}"
              lowercase__:    Tuple        =      fmt.format(snake_case_		)

       # Print and recurse (if needed).
       if isinstance(snake_case_						,       snake_case_		):
              if msg is not None:
                     print(snake_case_		)
              for k in val.keys():
                     recursive_print(snake_case_						,       val[k]						,       spaces + 2		)
       elif isinstance(snake_case_						,       torch.Tensor		):
              print(snake_case_						,       ":"						,       val.size()		)
       else:
              print(snake_case_						,       ":"						,       snake_case_		)






def     A(  snake_case_						,       snake_case_						,       snake_case_						,       snake_case_						,       snake_case_		):
       """simple docstring"""





       lowercase__:    Union[str, Any]        =      param.size()
       if checkpoint_version == 1.0:
              # version 1.0 stores [num_heads * hidden_size * num_splits, :]
              lowercase__:    str        =      (num_heads, hidden_size, num_splits) + input_shape[1:]
              lowercase__:    Optional[Any]        =      param.view(*snake_case_		)
              lowercase__:    Optional[int]        =      param.transpose(0						,       2		)
              lowercase__:    Optional[Any]        =      param.transpose(1						,       2		).contiguous()
       elif checkpoint_version >= 2.0:
              # other versions store [num_heads * num_splits * hidden_size, :]
              lowercase__:    List[Any]        =      (num_heads, num_splits, hidden_size) + input_shape[1:]
              lowercase__:    Optional[int]        =      param.view(*snake_case_		)
              lowercase__:    List[Any]        =      param.transpose(0						,       1		).contiguous()
       lowercase__:    Any        =      param.view(*snake_case_		)
       return param






def     A(  snake_case_						,       snake_case_						,       snake_case_		):
       """simple docstring"""





       lowercase__:    Any        =      {}

       # old versions did not store training args
       lowercase__:    int        =      input_state_dict.get("args"						,       snake_case_		)
       if ds_args is not None:
              # do not make the user write a config file when the exact dimensions/sizes are already in the checkpoint
              # from pprint import pprint
              # pprint(vars(ds_args))

              lowercase__:    Optional[int]        =      ds_args.tokenizer_type
              lowercase__:    List[Any]        =      ds_args.padded_vocab_size
              lowercase__:    Tuple        =      ds_args.max_position_embeddings
              lowercase__:    Any        =      ds_args.hidden_size
              lowercase__:    str        =      ds_args.num_layers
              lowercase__:    Dict        =      ds_args.num_attention_heads
              lowercase__:    str        =      ds_args.ffn_hidden_size if "ffn_hidden_size" in ds_args else 4 * ds_args.hidden_size
              # pprint(config)

       # The number of heads.
       lowercase__:    List[Any]        =      config.num_attention_heads
       # The hidden_size per head.
       lowercase__:    Optional[int]        =      config.hidden_size // heads
       # Megatron-LM checkpoint version
       if "checkpoint_version" in input_state_dict.keys():
              lowercase__:    Dict        =      input_state_dict["checkpoint_version"]
       else:
              lowercase__:    str        =      0.0

       # The model.
       lowercase__:    str        =      input_state_dict["model"]
       # The language model.
       lowercase__:    str        =      model["language_model"]
       # The embeddings.
       lowercase__:    str        =      lm["embedding"]

       # The word embeddings.
       lowercase__:    str        =      embeddings["word_embeddings"]["weight"]
       # Truncate the embedding table to vocab_size rows.
       lowercase__:    int        =      word_embeddings[: config.vocab_size, :]
       # Store the word embeddings.
       lowercase__:    List[Any]        =      word_embeddings

       # The position embeddings.
       lowercase__:    Any        =      embeddings["position_embeddings"]["weight"]
       assert pos_embeddings.size(0		) == config.max_position_embeddings and pos_embeddings.size(1		) == config.hidden_size
       # Store the position embeddings.
       lowercase__:    Union[str, Any]        =      pos_embeddings

       # The token-type embeddings.
       lowercase__:    Union[str, Any]        =      embeddings["tokentype_embeddings"]["weight"]
       # Store the position embeddings.
       lowercase__:    Optional[Any]        =      tokentype_embeddings

       # The transformer.
       lowercase__:    List[Any]        =      lm["transformer"] if "transformer" in lm.keys() else lm["encoder"]

       # The regex to extract layer names.
       lowercase__:    Dict        =      re.compile(r"layers\.(\d+)\.([a-z0-9_.]+)\.([a-z]+)"		)

       # The simple map of names for "automated" rules.
       lowercase__:    Any        =      {
           "attention.dense": ".attention.output.dense.",
           "self_attention.dense": ".attention.output.dense.",
           "mlp.dense_h_to_4h": ".intermediate.dense.",
           "mlp.dense_4h_to_h": ".output.dense.",
       }

       # Keep track of the attention/query/value tensor.
       lowercase__:    Union[str, Any]        =      None

       # Extract the layers.
       for key, val in transformer.items():
              # Match the name.
              lowercase__:    List[Any]        =      layer_re.match(snake_case_		)

              # Stop if that's not a layer
              if m is None:
                     break

              # The index of the layer.
              lowercase__:    Dict        =      int(m.group(1		)		)
              # The name of the operation.
              lowercase__:    List[str]        =      m.group(2		)
              # Is it a weight or a bias?
              lowercase__:    Optional[Any]        =      m.group(3		)

              # The name of the layer.
              lowercase__:    int        =      F"""bert.encoder.layer.{layer_idx}"""

              # For layernorm(s), simply store the layer norm.
              if op_name.endswith("layernorm"		):
                     lowercase__:    Optional[Any]        =      "attention.ln" if op_name.startswith("input"		) else "ln"
                     lowercase__:    Optional[Any]        =      val

              # Transpose the QKV matrix.
              elif (
                  op_name == "attention.query_key_value" or op_name == "self_attention.query_key_value"
              ) and weight_or_bias == "weight":
                     # Make sure the QKV pointer is nil.
                     assert attention_qkv_weight is None, ""

                     lowercase__:    int        =      fix_query_key_value_ordering(snake_case_						,       snake_case_						,       3						,       snake_case_						,       snake_case_		)
                     # Store the tensor as we need the bias as well to interleave QKV and biases.
                     lowercase__:    Dict        =      out_val

              # Transpose the bias.
              elif (
                  op_name == "attention.query_key_value" or op_name == "self_attention.query_key_value"
              ) and weight_or_bias == "bias":
                     # Make sure we read the weight tensor.
                     assert attention_qkv_weight is not None, ""

                     # Split the QKV matrix into Q, K and V. Megatron stores Q,K,V interleaved.
                     lowercase__:    Dict        =      attention_qkv_weight[0 * config.hidden_size : 1 * config.hidden_size, :]
                     lowercase__:    Optional[Any]        =      attention_qkv_weight[1 * config.hidden_size : 2 * config.hidden_size, :]
                     lowercase__:    Optional[Any]        =      attention_qkv_weight[2 * config.hidden_size : 3 * config.hidden_size, :]

                     lowercase__:    Dict        =      fix_query_key_value_ordering(snake_case_						,       snake_case_						,       3						,       snake_case_						,       snake_case_		)
                     # Split the bias.
                     lowercase__:    Dict        =      out_val[0 * config.hidden_size : 1 * config.hidden_size]
                     lowercase__:    Optional[int]        =      out_val[1 * config.hidden_size : 2 * config.hidden_size]
                     lowercase__:    int        =      out_val[2 * config.hidden_size : 3 * config.hidden_size]

                     # Store.
                     lowercase__:    Tuple        =      q
                     lowercase__:    Union[str, Any]        =      q_bias
                     lowercase__:    Tuple        =      k
                     lowercase__:    int        =      k_bias
                     lowercase__:    int        =      v
                     lowercase__:    Tuple        =      v_bias

                     # Clear the stored tensor.
                     lowercase__:    Dict        =      None

              # Copy weights and biases as is.
              elif weight_or_bias in ["weight", "bias"]:
                     lowercase__:    Tuple        =      megatron_to_transformers[op_name]
                     lowercase__:    Optional[int]        =      val

    # The final layernorm.
       lowercase__:    Optional[Any]        =      transformer["final_layernorm.weight"]
       lowercase__:    List[str]        =      transformer["final_layernorm.bias"]

       # The pooler.
       lowercase__:    Optional[Any]        =      lm["pooler"]

       # Store the matrix and the bias.
       lowercase__:    Any        =      pooler["dense.weight"]
       lowercase__:    Optional[int]        =      pooler["dense.bias"]

       # The LM head from Megatron (for RACE).
       lowercase__:    str        =      model["lm_head"]

       # The transform matrix.
       lowercase__:    str        =      lm_head["dense.weight"]
       lowercase__:    Optional[Any]        =      lm_head["dense.bias"]

       # The transform LN.
       lowercase__:    int        =      lm_head["layernorm.weight"]
       lowercase__:    Dict        =      lm_head["layernorm.bias"]

       # For the decoder, we replicate the weights.
       lowercase__:    Optional[int]        =      word_embeddings
       lowercase__:    Dict        =      lm_head["bias"]

       # The classifier from Megatron (for MLNI).
       lowercase__:    Optional[Any]        =      model["binary_head"]

       # Store the classifier.
       lowercase__:    Any        =      binary_head["weight"]
       lowercase__:    str        =      binary_head["bias"]

       # It should be done!
       return output_state_dict






def     A(  ):
       """simple docstring"""





       lowercase__:    Optional[int]        =      argparse.ArgumentParser()
       parser.add_argument("--print-checkpoint-structure"						,       action="store_true"		)
       parser.add_argument("path_to_checkpoint"						,       type=snake_case_						,       help="Path to the ZIP file containing the checkpoint"		)
       parser.add_argument(
           "--config_file"						,       default=""						,       type=snake_case_						,       help="An optional config json file describing the pre-trained model."						,       )
       lowercase__:    List[Any]        =      parser.parse_args()

       # Extract the basename.
       lowercase__:    Optional[Any]        =      os.path.dirname(args.path_to_checkpoint		)

       # Load the model.
       # the .zip is very optional, let's keep it for backward compatibility
       print(F"""Extracting PyTorch state dictionary from \"{args.path_to_checkpoint}\""""		)
       if args.path_to_checkpoint.endswith(".zip"		):
              with zipfile.ZipFile(args.path_to_checkpoint						,       "r"		) as checkpoint:
                     with checkpoint.open("release/mp_rank_00/model_optim_rng.pt"		) as pytorch_dict:
                            lowercase__:    Dict        =      torch.load(snake_case_						,       map_location="cpu"		)
       else:
              lowercase__:    List[Any]        =      torch.load(args.path_to_checkpoint						,       map_location="cpu"		)

       if args.config_file == "":
              # Default config of megatron-bert 345m
              lowercase__:    Optional[Any]        =      MegatronBertConfig()

              # different megatron-bert-*-345m models have different vocab sizes, so override the default
              # config (which is for megatron-bert-cased-345m) with the actual vocab dimension
              lowercase__:    Union[str, Any]        =      input_state_dict["model"]["lm_head"]["bias"].numel()
       else:
              lowercase__:    List[Any]        =      MegatronBertConfig.from_json_file(args.config_file		)

       # Convert.
       print("Converting"		)
       lowercase__:    Optional[Any]        =      convert_megatron_checkpoint(snake_case_						,       snake_case_						,       snake_case_		)

       # Print the structure of converted state dict.
       if args.print_checkpoint_structure:
              recursive_print(snake_case_						,       snake_case_		)

       # Store the config to file.
       print("Saving config"		)
       config.save_pretrained(snake_case_		)

       # Store the state_dict to file.
       lowercase__:    Optional[int]        =      os.path.join(snake_case_						,       "pytorch_model.bin"		)
       print(F"""Saving checkpoint to \"{output_checkpoint_file}\""""		)
       torch.save(snake_case_						,       snake_case_		)


####################################################################################################

if __name__ == "__main__":
       main()

####################################################################################################














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






