






'''simple docstring'''

# HF Trainer benchmarking tool
#
# This tool can be used to run and compare multiple dimensions of the HF Trainers args.
#
# It then prints a report once in github format with all the information that needs to be shared
# with others and second time in a console-friendly format, so it's easier to use for tuning things up.
#
# The main idea is:
#
#     ./trainer-benchmark.py --base-cmd '<cmd args that don't change>' \
#     --variations '--tf32 0|--tf32 1' '--fp16 0|--fp16 1|--bf16 1' \
#     --target-metric-key train_samples_per_second
#
# The variations can be any command line argument that you want to compare and not just dtype as in
# the example.
#
# --variations allows you to compare variations in multiple dimensions.
#
# as the first dimention has 2 options and the second 3 in our example, this will run the trainer 6
# times adding one of:
#
#    1. --tf32 0 --fp16 0
#    2. --tf32 0 --fp16 1
#    3. --tf32 0 --bf16 1
#    4. --tf32 1 --fp16 0
#    5. --tf32 1 --fp16 1
#    6. --tf32 1 --bf16 1
#
# and print the results. This is just a cartesian product - and more than 2 dimensions can be used.
#
# If you want to rely on defaults, this:
#    --variations '--tf32 0|--tf32 1' '--fp16 0|--fp16 1|--bf16 1'
# is identical to this:
#    --variations '--tf32 0|--tf32 1' '|--fp16|--bf16'
#
# the leading empty variation in the 2nd dimension is a valid variation.
#
# So here we get the following 6 variations:
#
#    1. --tf32 0
#    2. --tf32 0 --fp16
#    3. --tf32 0 --bf16
#    4. --tf32 1
#    5. --tf32 1 --fp16
#    6. --tf32 1 --bf16
#
# In this particular case we don't know what the default tf32 setting is as it's normally
# pytorch-version dependent). That's why it's best to do an explicit setting of each variation:
#    `--tf32 0|--tf32 1`
#
# Here is a full example of a train:
#
# CUDA_VISIBLE_DEVICES=0 python ./scripts/benchmark/trainer-benchmark.py \
# --base-cmd \
# ' examples/pytorch/translation/run_translation.py --model_name_or_path t5-small \
# --output_dir output_dir --do_train --label_smoothing 0.1 --logging_strategy no \
# --save_strategy no --per_device_train_batch_size 32 --max_source_length 512 \
# --max_target_length 512 --num_train_epochs 1 --overwrite_output_dir \
# --source_lang en --target_lang ro --dataset_name wmt16 --dataset_config "ro-en" \
# --source_prefix "translate English to Romanian: " --warmup_steps 50 \
# --max_train_samples 20000 --dataloader_num_workers 2 ' \
# --target-metric-key train_samples_per_second --repeat-times 1 --variations \
# '|--fp16|--bf16' '--tf32 0|--tf32 1' --report-metric-keys train_loss \
# --repeat-times 1 --base-variation '--tf32 0'
#
# and here is a possible output:
#
#
# | Variation       |     Train |   Diff |   Train |
# |                 |   samples |      % |    loss |
# |                 |       per |        |         |
# |                 |    second |        |         |
# |:----------------|----------:|-------:|--------:|
# | --tf32 0        |    285.11 |      0 |    2.51 |
# | --tf32 1        |    342.09 |     20 |    2.51 |
# | --fp16 --tf32 0 |    423.49 |     49 |    2.51 |
# | --fp16 --tf32 1 |    423.13 |     48 |    2.51 |
# | --bf16 --tf32 0 |    416.80 |     46 |    2.52 |
# | --bf16 --tf32 1 |    415.87 |     46 |    2.52 |
#
#
# So you can quickly compare the different outcomes.
#
# Typically running each experiment once is enough, but if the environment is unstable you can
# re-run each multiple times, e.g., 3 using --repeat-times 3 and it will report the averaged results.
#
# By default it'll use the lowest result as the base line to use as 100% and then compare the rest to
# it as can be seen from the table above, but you can also specify which combination is the one to use as
# the baseline, e.g., to change to another entry use: --base-variation '--tf32 1 --fp16 0'
#
# --target-metric-key is there to tell the program which metrics to compare - the different metric keys are
# inside output_dir/all_results.json. e.g., to measure eval performance instead of train use:
#    --target-metric-key eval_samples_per_second
# but of course you will need to adjust the --base-cmd value in the example to perform evaluation as
# well (as currently it doesn't)
#

import argparse
import datetime
import io
import itertools
import json
import math
import os
import platform
import re
import shlex
import subprocess
import sys
from pathlib import Path
from statistics import fmean

import pandas as pd
import torch
from tqdm import tqdm

import transformers


UpperCAmelCase__						:Tuple          =			float("""nan""")







class 	SCREAMING_SNAKE_CASE	:




       def __init__(					self      : Union[str, Any]	,    A__      : Dict					):


            """simple docstring"""







            __lowerCamelCase						:       Optional[int]				   =				sys.stdout
            __lowerCamelCase						:       Optional[int]				   =				open(A__	,    """a"""					)




       def __getattr__(					self      : Dict	,    A__      : Tuple					):


            """simple docstring"""







            return getattr(self.stdout	,    A__					)




       def 					a_					(					self      : Dict	,    A__      : int					):


            """simple docstring"""







            self.stdout.write(A__					)
            # strip tqdm codes
            self.file.write(re.sub(r"""^.*\r"""	,    """"""	,    A__	,    0	,    re.M					)					)

def     __lowercase  (_lowercase=80,						_lowercase=False     )   ->     Optional[Any]:


     """simple docstring"""
     __lowerCamelCase						:       Any				   =				[]

     # deal with critical env vars
     __lowerCamelCase						:       str				   =				["""CUDA_VISIBLE_DEVICES"""]
     for key in env_keys:
          __lowerCamelCase						:       List[str]				   =				os.environ.get(_lowercase,						_lowercase     )
          if val is not None:
               cmd.append(f"{key}={val}"     )

    # python executable (not always needed if the script is executable)
     __lowerCamelCase						:       int				   =				sys.executable if full_python_path else sys.executable.split("""/"""     )[-1]
     cmd.append(_lowercase     )

     # now the normal args
     cmd += list(map(shlex.quote,						sys.argv     )     )

     # split up into up to MAX_WIDTH lines with shell multi-line escapes
     __lowerCamelCase						:       str				   =				[]
     __lowerCamelCase						:       Tuple				   =				""""""
     while len(_lowercase     ) > 0:
          current_line += f"{cmd.pop(0     )} "
          if len(_lowercase     ) == 0 or len(_lowercase     ) + len(cmd[0]     ) + 1 > max_width - 1:
               lines.append(_lowercase     )
               __lowerCamelCase						:       Optional[int]				   =				""""""
     return "\\\n".join(_lowercase     )
def     __lowercase  (_lowercase,						_lowercase     )   ->     List[Any]:


     """simple docstring"""
     # unwrap multi-line input
     __lowerCamelCase						:       str				   =				re.sub(R"""[\\\n]+""",						""" """,						args.base_cmd     )

     # remove --output_dir if any and set our own
     __lowerCamelCase						:       Optional[int]				   =				re.sub("""--output_dir\s+[^\s]+""",						"""""",						args.base_cmd     )
     args.base_cmd += f" --output_dir {output_dir}"

     # ensure we have --overwrite_output_dir
     __lowerCamelCase						:       Dict				   =				re.sub("""--overwrite_output_dir\s+""",						"""""",						args.base_cmd     )
     args.base_cmd += " --overwrite_output_dir"

     return [sys.executable] + shlex.split(args.base_cmd     )
def     __lowercase  (_lowercase,						_lowercase,						_lowercase,						_lowercase,						_lowercase,						_lowercase,						_lowercase     )   ->     Optional[Any]:


     """simple docstring"""
     # Enable to debug everything but the run itself, to do it fast and see the progress.
     # This is useful for debugging the output formatting quickly - we can remove it later once
     # everybody is happy with the output
     if 0:
          import random
          from time import sleep

          sleep(0     )
          return dict(
              {k: random.uniform(0,						100     ) for k in metric_keys},						**{target_metric_key: random.choice([nan, 10.31, 100.2, 55.6666, 222.2222_2222]     )},						)

     __lowerCamelCase						:       Optional[Any]				   =				subprocess.run(_lowercase,						capture_output=_lowercase,						text=_lowercase     )

     if verbose:
          print("""STDOUT""",						result.stdout     )
          print("""STDERR""",						result.stderr     )

     # save the streams
     __lowerCamelCase						:       Any				   =				variation.replace(""" """,						"""-"""     )
     with open(Path(_lowercase     ) / f"log.{prefix}.stdout.txt",						"""w"""     ) as f:
          f.write(result.stdout     )
     with open(Path(_lowercase     ) / f"log.{prefix}.stderr.txt",						"""w"""     ) as f:
          f.write(result.stderr     )

     if result.returncode != 0:
          if verbose:
               print("""failed"""     )
          return {target_metric_key: nan}

     with io.open(f"{output_dir}/all_results.json",						"""r""",						encoding="""utf-8"""     ) as f:
          __lowerCamelCase						:       Tuple				   =				json.load(_lowercase     )

     # filter out just the keys we want
     return {k: v for k, v in metrics.items() if k in metric_keys}
def     __lowercase  (_lowercase,						_lowercase,						_lowercase,						_lowercase,						_lowercase,						_lowercase,						_lowercase,						_lowercase,						_lowercase,						_lowercase,						)   ->     Optional[Any]:


     """simple docstring"""
     __lowerCamelCase						:       Optional[int]				   =				[]
     __lowerCamelCase						:       str				   =				[]
     __lowerCamelCase						:       Optional[int]				   =				f"{id}: {variation:<{longest_variation_len}}"
     __lowerCamelCase						:       Tuple				   =				f"{preamble}: "
     __lowerCamelCase						:       str				   =				set(report_metric_keys + [target_metric_key]     )
     for i in tqdm(range(_lowercase     ),						desc=_lowercase,						leave=_lowercase     ):
          __lowerCamelCase						:       Any				   =				process_run_single(
              _lowercase,						_lowercase,						_lowercase,						_lowercase,						_lowercase,						_lowercase,						_lowercase     )
          __lowerCamelCase						:       Tuple				   =				single_run_metrics[target_metric_key]
          if not math.isnan(_lowercase     ):
               metrics.append(_lowercase     )
               results.append(_lowercase     )
               outcome += "✓"
          else:
               outcome += "✘"
     __lowerCamelCase						:       int				   =				f"\33[2K\r{outcome}"
     if len(_lowercase     ) > 0:
          __lowerCamelCase						:       Union[str, Any]				   =				{k: fmean([x[k] for x in metrics]     ) for k in metrics[0].keys()}
          __lowerCamelCase						:       Dict				   =				round(mean_metrics[target_metric_key],						2     )
          __lowerCamelCase						:       str				   =				f"{outcome} {mean_target}"
          if len(_lowercase     ) > 1:
               results_str += f" {tuple(round(_lowercase,						2     ) for x in results     )}"
          print(_lowercase     )
          __lowerCamelCase						:       Optional[Any]				   =				variation
          return mean_metrics
     else:
          print(_lowercase     )
          return {variation_key: variation, target_metric_key: nan}
def     __lowercase  ()   ->     Any:


     """simple docstring"""
     __lowerCamelCase						:       List[Any]				   =				torch.cuda.get_device_properties(torch.device("""cuda"""     )     )
     return f"\nDatetime    : {datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'     )}\n\nSoftware:\ntransformers: {transformers.__version__}\ntorch       : {torch.__version__}\ncuda        : {torch.version.cuda}\npython      : {platform.python_version()}\n\nHardware:\n{torch.cuda.device_count()} GPUs      : {properties.name}, {properties.total_memory/2**30:0.2f}GB\n"
def     __lowercase  (_lowercase,						_lowercase,						_lowercase,						_lowercase,						_lowercase     )   ->     Union[str, Any]:


     """simple docstring"""
     __lowerCamelCase						:       Tuple				   =				pd.DataFrame(_lowercase     )
     __lowerCamelCase						:       Dict				   =				"""variation"""
     __lowerCamelCase						:       str				   =				"""diff_%"""

     __lowerCamelCase						:       Dict				   =				nan
     if base_variation is not None and len(df[df[variation_key] == base_variation]     ):
          # this may still return nan
          __lowerCamelCase						:       Union[str, Any]				   =				df.loc[df[variation_key] == base_variation][target_metric_key].item()
     if math.isnan(_lowercase     ):
          # as a fallback, use the minimal value as the sentinel
          __lowerCamelCase						:       Optional[Any]				   =				df.loc[df[target_metric_key] != nan][target_metric_key].min()

     # create diff column if possible
     if not math.isnan(_lowercase     ):
          __lowerCamelCase						:       List[str]				   =				df.apply(
              lambda _lowercase     : round(100 * (r[target_metric_key] - sentinel_value) / sentinel_value     )
              if not math.isnan(r[target_metric_key]     )
              else 0,						axis="""columns""",						)

     # re-order columns
     __lowerCamelCase						:       int				   =				[variation_key, target_metric_key, diff_key, *report_metric_keys]
     __lowerCamelCase						:       Dict				   =				df.reindex(_lowercase,						axis="""columns"""     )  # reorder cols

     # capitalize
     __lowerCamelCase						:       Optional[Any]				   =				df.rename(str.capitalize,						axis="""columns"""     )

     # make the cols as narrow as possible
     __lowerCamelCase						:       List[str]				   =				df.rename(lambda _lowercase     : c.replace("""_""",						"""<br>"""     ),						axis="""columns"""     )
     __lowerCamelCase						:       str				   =				df.rename(lambda _lowercase     : c.replace("""_""",						"""\n"""     ),						axis="""columns"""     )

     __lowerCamelCase						:       Tuple				   =				["""""", """Copy between the cut-here-lines and paste as is to github or a forum"""]
     report += ["----------8<-----------------8<--------"]
     report += ["*** Results:", df_github.to_markdown(index=_lowercase,						floatfmt=""".2f"""     )]
     report += ["```"]
     report += ["*** Setup:", get_versions()]
     report += ["*** The benchmark command line was:", get_original_command()]
     report += ["```"]
     report += ["----------8<-----------------8<--------"]
     report += ["*** Results (console):", df_console.to_markdown(index=_lowercase,						floatfmt=""".2f"""     )]

     print("""\n\n""".join(_lowercase     )     )
def     __lowercase  ()   ->     List[Any]:


     """simple docstring"""
     __lowerCamelCase						:       List[Any]				   =				argparse.ArgumentParser()
     parser.add_argument(
         """--base-cmd""",						default=_lowercase,						type=_lowercase,						required=_lowercase,						help="""Base cmd""",						)
     parser.add_argument(
         """--variations""",						default=_lowercase,						type=_lowercase,						nargs="""+""",						required=_lowercase,						help="""Multi-dimensional variations, example: '|--fp16|--bf16' '|--tf32'""",						)
     parser.add_argument(
         """--base-variation""",						default=_lowercase,						type=_lowercase,						help="""Baseline variation to compare to. if None the minimal target value will be used to compare against""",						)
     parser.add_argument(
         """--target-metric-key""",						default=_lowercase,						type=_lowercase,						required=_lowercase,						help="""Target metric key in output_dir/all_results.json, e.g., train_samples_per_second""",						)
     parser.add_argument(
         """--report-metric-keys""",						default="""""",						type=_lowercase,						help="""Report metric keys - other metric keys from output_dir/all_results.json to report, e.g., train_loss. Use a single argument e.g., 'train_loss train_samples""",						)
     parser.add_argument(
         """--repeat-times""",						default=1,						type=_lowercase,						help="""How many times to re-run each variation - an average will be reported""",						)
     parser.add_argument(
         """--output_dir""",						default="""output_benchmark""",						type=_lowercase,						help="""The output directory where all the benchmark reports will go to and additionally this directory will be used to override --output_dir in the script that is being benchmarked""",						)
     parser.add_argument(
         """--verbose""",						default=_lowercase,						action="""store_true""",						help="""Whether to show the outputs of each run or just the benchmark progress""",						)
     __lowerCamelCase						:       List[str]				   =				parser.parse_args()

     __lowerCamelCase						:       Union[str, Any]				   =				args.output_dir
     Path(_lowercase     ).mkdir(exist_ok=_lowercase     )
     __lowerCamelCase						:       List[Any]				   =				get_base_command(_lowercase,						_lowercase     )

     # split each dimension into its --foo variations
     __lowerCamelCase						:       str				   =				[list(map(str.strip,						re.split(R"""\|""",						_lowercase     )     )     ) for x in args.variations]
     # build a cartesian product of dimensions and convert those back into cmd-line arg strings,
     # while stripping white space for inputs that were empty
     __lowerCamelCase						:       int				   =				list(map(str.strip,						map(""" """.join,						itertools.product(*_lowercase     )     )     )     )
     __lowerCamelCase						:       Union[str, Any]				   =				max(len(_lowercase     ) for x in variations     )

     # split wanted keys
     __lowerCamelCase						:       Union[str, Any]				   =				args.report_metric_keys.split()

     # capture prints into a log file for convenience
     __lowerCamelCase						:       Optional[int]				   =				f"benchmark-report-{datetime.datetime.now().strftime('%Y-%m-%d-%H-%M-%S'     )}.txt"
     print(f"\nNote: each run's output is also logged under {output_dir}/log.*.std*.txt"     )
     print(f"and this script's output is also piped into {report_fn}"     )

     __lowerCamelCase						:       Union[str, Any]				   =				Tee(_lowercase     )

     print(f"\n*** Running {len(_lowercase     )} benchmarks:"     )
     print(f"Base command: {' '.join(_lowercase     )}"     )

     __lowerCamelCase						:       Optional[int]				   =				"""variation"""
     __lowerCamelCase						:       Tuple				   =				[]
     for id, variation in enumerate(tqdm(_lowercase,						desc="""Total completion: """,						leave=_lowercase     )     ):
          __lowerCamelCase						:       Any				   =				base_cmd + variation.split()
          results.append(
              process_run(
                  id + 1,						_lowercase,						_lowercase,						_lowercase,						_lowercase,						args.target_metric_key,						_lowercase,						args.repeat_times,						_lowercase,						args.verbose,						)     )

     process_results(_lowercase,						args.target_metric_key,						_lowercase,						args.base_variation,						_lowercase     )


if __name__ == "__main__":
   main()











'''simple docstring'''

import pickle
import shutil
import tempfile
import unittest

from transformers import SPIECE_UNDERLINE, XLMRobertaTokenizer, XLMRobertaTokenizerFast
from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow
from transformers.utils import cached_property

from ...test_tokenization_common import TokenizerTesterMixin


UpperCAmelCase__						:List[str]          =			get_tests_dir("""fixtures/test_sentencepiece.model""")







@require_sentencepiece
@require_tokenizers
class 	SCREAMING_SNAKE_CASE	(      lowerCAmelCase_    ,   unittest.TestCase  ):
       snake_case__    :     Optional[Any]   		=			XLMRobertaTokenizer
       snake_case__    :     str   		=			XLMRobertaTokenizerFast
       snake_case__    :     str   		=			True
       snake_case__    :     int   		=			True




       def 					a_					(					self      : Dict					):


            """simple docstring"""







            super().setUp()

            # We have a SentencePiece fixture for testing
            __lowerCamelCase						:       str				   =				XLMRobertaTokenizer(A__	,    keep_accents=A__					)
            tokenizer.save_pretrained(self.tmpdirname					)




       def 					a_					(					self      : int					):


            """simple docstring"""







            __lowerCamelCase						:       List[Any]				   =				"""<pad>"""
            __lowerCamelCase						:       List[Any]				   =				1

            self.assertEqual(self.get_tokenizer()._convert_token_to_id(A__					)	,    A__					)
            self.assertEqual(self.get_tokenizer()._convert_id_to_token(A__					)	,    A__					)




       def 					a_					(					self      : str					):


            """simple docstring"""







            __lowerCamelCase						:       List[str]				   =				list(self.get_tokenizer().get_vocab().keys()					)

            self.assertEqual(vocab_keys[0]	,    """<s>"""					)
            self.assertEqual(vocab_keys[1]	,    """<pad>"""					)
            self.assertEqual(vocab_keys[-1]	,    """<mask>"""					)
            self.assertEqual(len(A__					)	,    1002					)




       def 					a_					(					self      : List[Any]					):


            """simple docstring"""







            self.assertEqual(self.get_tokenizer().vocab_size	,    1002					)




       def 					a_					(					self      : Tuple					):


            """simple docstring"""







            __lowerCamelCase						:       Any				   =				XLMRobertaTokenizer(A__	,    keep_accents=A__					)

            __lowerCamelCase						:       List[str]				   =				tokenizer.tokenize("""This is a test"""					)
            self.assertListEqual(A__	,    ["""▁This""", """▁is""", """▁a""", """▁t""", """est"""]					)

            self.assertListEqual(
                tokenizer.convert_tokens_to_ids(A__					)	,    [value + tokenizer.fairseq_offset for value in [285, 46, 10, 170, 382]]	,    )

            __lowerCamelCase						:       Any				   =				tokenizer.tokenize("""I was born in 92000, and this is falsé."""					)
            self.assertListEqual(
                A__	,    [
                    SPIECE_UNDERLINE + """I""",
                    SPIECE_UNDERLINE + """was""",
                    SPIECE_UNDERLINE + """b""",
                    """or""",
                    """n""",
                    SPIECE_UNDERLINE + """in""",
                    SPIECE_UNDERLINE + """""",
                    """9""",
                    """2""",
                    """0""",
                    """0""",
                    """0""",
                    """,""",
                    SPIECE_UNDERLINE + """and""",
                    SPIECE_UNDERLINE + """this""",
                    SPIECE_UNDERLINE + """is""",
                    SPIECE_UNDERLINE + """f""",
                    """al""",
                    """s""",
                    """é""",
                    """.""",
                ]	,    )
            __lowerCamelCase						:       List[str]				   =				tokenizer.convert_tokens_to_ids(A__					)
            self.assertListEqual(
                A__	,    [
                    value + tokenizer.fairseq_offset
                    for value in [8, 21, 84, 55, 24, 19, 7, 2, 602, 347, 347, 347, 3, 12, 66, 46, 72, 80, 6, 2, 4]
                    #                                       ^ unk: 2 + 1 = 3                  unk: 2 + 1 = 3 ^
                ]	,    )

            __lowerCamelCase						:       Dict				   =				tokenizer.convert_ids_to_tokens(A__					)
            self.assertListEqual(
                A__	,    [
                    SPIECE_UNDERLINE + """I""",
                    SPIECE_UNDERLINE + """was""",
                    SPIECE_UNDERLINE + """b""",
                    """or""",
                    """n""",
                    SPIECE_UNDERLINE + """in""",
                    SPIECE_UNDERLINE + """""",
                    """<unk>""",
                    """2""",
                    """0""",
                    """0""",
                    """0""",
                    """,""",
                    SPIECE_UNDERLINE + """and""",
                    SPIECE_UNDERLINE + """this""",
                    SPIECE_UNDERLINE + """is""",
                    SPIECE_UNDERLINE + """f""",
                    """al""",
                    """s""",
                    """<unk>""",
                    """.""",
                ]	,    )




       def 					a_					(					self      : Any					):


            """simple docstring"""







            if not self.test_slow_tokenizer:
                 # as we don't have a slow version, we can't compare the outputs between slow and fast versions
                 return

            __lowerCamelCase						:       Tuple				   =				(self.rust_tokenizer_class, """hf-internal-testing/tiny-xlm-roberta""", {})
            for tokenizer, pretrained_name, kwargs in self.tokenizers_list:
                 with self.subTest(f"{tokenizer.__class__.__name__} ({pretrained_name})"					):
                      __lowerCamelCase						:       List[Any]				   =				self.rust_tokenizer_class.from_pretrained(A__	,    **A__					)
                      __lowerCamelCase						:       Dict				   =				self.tokenizer_class.from_pretrained(A__	,    **A__					)

                      __lowerCamelCase						:       str				   =				tempfile.mkdtemp()

                      __lowerCamelCase						:       Union[str, Any]				   =				tokenizer_r.save_pretrained(A__					)
                      __lowerCamelCase						:       Union[str, Any]				   =				tokenizer_p.save_pretrained(A__					)

                      # Checks it save with the same files + the tokenizer.json file for the fast one
                      self.assertTrue(any("""tokenizer.json""" in f for f in tokenizer_r_files					)					)
                      __lowerCamelCase						:       Any				   =				tuple(f for f in tokenizer_r_files if """tokenizer.json""" not in f					)
                      self.assertSequenceEqual(A__	,    A__					)

                      # Checks everything loads correctly in the same way
                      __lowerCamelCase						:       str				   =				tokenizer_r.from_pretrained(A__					)
                      __lowerCamelCase						:       str				   =				tokenizer_p.from_pretrained(A__					)

                      # Check special tokens are set accordingly on Rust and Python
                      for key in tokenizer_pp.special_tokens_map:
                           self.assertTrue(hasattr(A__	,    A__					)					)
                           # self.assertEqual(getattr(tokenizer_rp, key), getattr(tokenizer_pp, key))
                           # self.assertEqual(getattr(tokenizer_rp, key + "_id"), getattr(tokenizer_pp, key + "_id"))

                      shutil.rmtree(A__					)

                      # Save tokenizer rust, legacy_format=True
                      __lowerCamelCase						:       Optional[Any]				   =				tempfile.mkdtemp()

                      __lowerCamelCase						:       Dict				   =				tokenizer_r.save_pretrained(A__	,    legacy_format=A__					)
                      __lowerCamelCase						:       List[Any]				   =				tokenizer_p.save_pretrained(A__					)

                      # Checks it save with the same files
                      self.assertSequenceEqual(A__	,    A__					)

                      # Checks everything loads correctly in the same way
                      __lowerCamelCase						:       Any				   =				tokenizer_r.from_pretrained(A__					)
                      __lowerCamelCase						:       List[str]				   =				tokenizer_p.from_pretrained(A__					)

                      # Check special tokens are set accordingly on Rust and Python
                      for key in tokenizer_pp.special_tokens_map:
                           self.assertTrue(hasattr(A__	,    A__					)					)

                      shutil.rmtree(A__					)

                      # Save tokenizer rust, legacy_format=False
                      __lowerCamelCase						:       int				   =				tempfile.mkdtemp()

                      __lowerCamelCase						:       Any				   =				tokenizer_r.save_pretrained(A__	,    legacy_format=A__					)
                      __lowerCamelCase						:       List[str]				   =				tokenizer_p.save_pretrained(A__					)

                      # Checks it saved the tokenizer.json file
                      self.assertTrue(any("""tokenizer.json""" in f for f in tokenizer_r_files					)					)

                      # Checks everything loads correctly in the same way
                      __lowerCamelCase						:       List[Any]				   =				tokenizer_r.from_pretrained(A__					)
                      __lowerCamelCase						:       Optional[int]				   =				tokenizer_p.from_pretrained(A__					)

                      # Check special tokens are set accordingly on Rust and Python
                      for key in tokenizer_pp.special_tokens_map:
                           self.assertTrue(hasattr(A__	,    A__					)					)

                      shutil.rmtree(A__					)




       @cached_property
       def 					a_					(					self      : str					):


            """simple docstring"""







            return XLMRobertaTokenizer.from_pretrained("""xlm-roberta-base"""					)




       def 					a_					(					self      : int					):


            """simple docstring"""







            with tempfile.NamedTemporaryFile() as f:
                 shutil.copyfile(A__	,    f.name					)
                 __lowerCamelCase						:       int				   =				XLMRobertaTokenizer(f.name	,    keep_accents=A__					)
                 __lowerCamelCase						:       str				   =				pickle.dumps(A__					)
            pickle.loads(A__					)




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


            """simple docstring"""







            if not self.test_rust_tokenizer:
                 return

            __lowerCamelCase						:       Union[str, Any]				   =				self.get_tokenizer()
            __lowerCamelCase						:       Tuple				   =				self.get_rust_tokenizer()

            __lowerCamelCase						:       Optional[Any]				   =				"""I was born in 92000, and this is falsé."""

            __lowerCamelCase						:       int				   =				tokenizer.tokenize(A__					)
            __lowerCamelCase						:       Optional[Any]				   =				rust_tokenizer.tokenize(A__					)
            self.assertListEqual(A__	,    A__					)

            __lowerCamelCase						:       Any				   =				tokenizer.encode(A__	,    add_special_tokens=A__					)
            __lowerCamelCase						:       Dict				   =				rust_tokenizer.encode(A__	,    add_special_tokens=A__					)
            self.assertListEqual(A__	,    A__					)

            __lowerCamelCase						:       Optional[Any]				   =				self.get_rust_tokenizer()
            __lowerCamelCase						:       Optional[int]				   =				tokenizer.encode(A__					)
            __lowerCamelCase						:       str				   =				rust_tokenizer.encode(A__					)
            self.assertListEqual(A__	,    A__					)




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


            """simple docstring"""







            __lowerCamelCase						:       List[Any]				   =				"""Hello World!"""
            __lowerCamelCase						:       str				   =				[0, 35378, 6661, 38, 2]
            # xlmr = torch.hub.load('pytorch/fairseq', 'xlmr.base')  # xlmr.large has same tokenizer
            # xlmr.eval()
            # xlmr.encode(symbols)

            self.assertListEqual(A__	,    self.big_tokenizer.encode(A__					)					)




       @slow
       def 					a_					(					self      : Optional[Any]					):


            """simple docstring"""







            __lowerCamelCase						:       Any				   =				(
                """This is a very long text with a lot of weird characters, such as: . , ~ ? ( ) \" [ ] ! : - . Also we will"""
                """ add words that should not exsist and be tokenized to <unk>, such as saoneuhaoesuth"""
            )
            __lowerCamelCase						:       Optional[Any]				   =				[
                0,
                3293,
                83,
                10,
                4552,
                4989,
                7986,
                678,
                10,
                5915,
                111,
                179459,
                124850,
                4,
                6044,
                237,
                12,
                6,
                5,
                6,
                4,
                6780,
                705,
                15,
                1388,
                44,
                378,
                10114,
                711,
                152,
                20,
                6,
                5,
                22376,
                642,
                1221,
                15190,
                34153,
                450,
                5608,
                959,
                1119,
                57702,
                136,
                186,
                47,
                1098,
                29367,
                47,
                # 4426, # What fairseq tokenizes from "<unk>": "_<"
                # 3678, # What fairseq tokenizes from "<unk>": "unk"
                # 2740, # What fairseq tokenizes from "<unk>": ">"
                3,  # What we tokenize from "<unk>": "<unk>"
                6,  # Residue from the tokenization: an extra sentencepiece underline
                4,
                6044,
                237,
                6284,
                50901,
                528,
                31,
                90,
                34,
                927,
                2,
            ]
            # xlmr = torch.hub.load('pytorch/fairseq', 'xlmr.base')  # xlmr.large has same tokenizer
            # xlmr.eval()
            # xlmr.encode(symbols)

            self.assertListEqual(A__	,    self.big_tokenizer.encode(A__					)					)




       @slow
       def 					a_					(					self      : Any					):


            """simple docstring"""







            __lowerCamelCase						:       Tuple				   =				{"""input_ids""": [[0, 11062, 82772, 7, 15, 82772, 538, 51529, 237, 17198, 1290, 206, 9, 215175, 1314, 136, 17198, 1290, 206, 9, 56359, 42, 122009, 9, 16466, 16, 87344, 4537, 9, 4717, 78381, 6, 159958, 7, 15, 24480, 618, 4, 527, 22693, 5428, 4, 2777, 24480, 9874, 4, 43523, 594, 4, 803, 18392, 33189, 18, 4, 43523, 24447, 12399, 100, 24955, 83658, 9626, 144057, 15, 839, 22335, 16, 136, 24955, 83658, 83479, 15, 39102, 724, 16, 678, 645, 2789, 1328, 4589, 42, 122009, 115774, 23, 805, 1328, 46876, 7, 136, 53894, 1940, 42227, 41159, 17721, 823, 425, 4, 27512, 98722, 206, 136, 5531, 4970, 919, 17336, 5, 2], [0, 20080, 618, 83, 82775, 47, 479, 9, 1517, 73, 53894, 333, 80581, 110117, 18811, 5256, 1295, 51, 152526, 297, 7986, 390, 124416, 538, 35431, 214, 98, 15044, 25737, 136, 7108, 43701, 23, 756, 135355, 7, 5, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [0, 581, 63773, 119455, 6, 147797, 88203, 7, 645, 70, 21, 3285, 10269, 5, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]], """attention_mask""": [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]}  # noqa: E501
            # fmt: on

            self.tokenizer_integration_test_util(
                expected_encoding=A__	,    model_name="""xlm-roberta-base"""	,    revision="""d9d8a8ea5eb94b1c6654ae9249df7793cd2933d3"""	,    )



