'''simple docstring'''





import random
import timeit
from functools import wraps
from typing import Callable, Optional

from ..configuration_utils import PretrainedConfig
from ..models.auto.modeling_tf_auto import TF_MODEL_MAPPING, TF_MODEL_WITH_LM_HEAD_MAPPING
from ..utils import is_pyanvml_available, is_tf_available, logging
from .benchmark_utils import (
    Benchmark,
    Memory,
    MemorySummary,
    measure_peak_memory_cpu,
    start_memory_tracing,
    stop_memory_tracing,
)


if is_tf_available():
    import tensorflow as tf
    from tensorflow.python.framework.errors_impl import ResourceExhaustedError

    from .benchmark_args_tf import TensorFlowBenchmarkArguments

if is_pyanvml_available():
    import pyanvml.pyanvml as nvml

SCREAMING_SNAKE_CASE_:	Optional[int]    =logging.get_logger(__name__)





def       lowerCAmelCase_							(   snake_case_			:					bool   ,       snake_case_			:					bool     )       -> Union[str, Any]:


     '''simple docstring'''




     def run_func(snake_case_			:					Any     ):
          @wraps(snake_case_     )
          def run_in_eager_mode(*snake_case_			:					Tuple   ,       **snake_case_			:					Any     ):
               return func(*snake_case_   ,       **snake_case_     )

          @wraps(snake_case_     )
          @tf.function(experimental_compile=snake_case_     )
          def run_in_graph_mode(*snake_case_			:					Any   ,       **snake_case_			:					str     ):
               return func(*snake_case_   ,       **snake_case_     )

          if do_eager_mode is True:
               if use_xla is not False:
                    raise ValueError(
                        "Cannot run model in XLA, if `args.eager_mode` is set to `True`. Please set `args.eager_mode=False`."     )
               return run_in_eager_mode
          else:
               return run_in_graph_mode

     return run_func





def       lowerCAmelCase_							(   snake_case_			:					int   ,       snake_case_			:					int   ,       snake_case_			:					int     )       -> ["tf.Tensor"]:


     '''simple docstring'''




     UpperCAmelCase_			       =  random.Random()
     UpperCAmelCase_			       =  [rng.randint(0   ,       vocab_size - 1     ) for i in range(batch_size * sequence_length     )]
     return tf.constant(snake_case_   ,       shape=(batch_size, sequence_length)   ,       dtype=tf.intaa     )






class 			__A (					UpperCamelCase__      ):
    a__			:		TensorFlowBenchmarkArguments
    a__			:		PretrainedConfig
    a__			:		str			  =    "TensorFlow"



    @property
    def    _lowercase		(self       :       List[str]					):
         return tf.__version__



    def    _lowercase		(self       :       Optional[Any]  ,     __a       :       str  ,     __a       :       int  ,     __a       :       int					):
         # initialize GPU on separate process
         UpperCAmelCase_			       =  self.args.strategy
         if strategy is None:
              raise ValueError("A device strategy has to be initialized before using TensorFlow."					)
         UpperCAmelCase_			       =  self._prepare_inference_func(__a  ,     __a  ,     __a					)
         return self._measure_speed(_inference					)



    def    _lowercase		(self       :       Optional[Any]  ,     __a       :       str  ,     __a       :       int  ,     __a       :       int					):
         UpperCAmelCase_			       =  self.args.strategy
         if strategy is None:
              raise ValueError("A device strategy has to be initialized before using TensorFlow."					)
         UpperCAmelCase_			       =  self._prepare_train_func(__a  ,     __a  ,     __a					)
         return self._measure_speed(_train					)



    def    _lowercase		(self       :       Optional[int]  ,     __a       :       str  ,     __a       :       int  ,     __a       :       int					):
         # initialize GPU on separate process
         if self.args.is_gpu:
              tf.config.experimental.set_memory_growth(self.args.gpu_list[self.args.device_idx]  ,     __a					)
         UpperCAmelCase_			       =  self.args.strategy
         if strategy is None:
              raise ValueError("A device strategy has to be initialized before using TensorFlow."					)
         UpperCAmelCase_			       =  self._prepare_inference_func(__a  ,     __a  ,     __a					)
         return self._measure_memory(_inference					)



    def    _lowercase		(self       :       Dict  ,     __a       :       str  ,     __a       :       int  ,     __a       :       int					):
         if self.args.is_gpu:
              tf.config.experimental.set_memory_growth(self.args.gpu_list[self.args.device_idx]  ,     __a					)
         UpperCAmelCase_			       =  self.args.strategy
         if strategy is None:
              raise ValueError("A device strategy has to be initialized before using TensorFlow."					)

         UpperCAmelCase_			       =  self._prepare_train_func(__a  ,     __a  ,     __a					)
         return self._measure_memory(_train					)



    def    _lowercase		(self       :       Optional[Any]  ,     __a       :       str  ,     __a       :       int  ,     __a       :       int					):
         UpperCAmelCase_			       =  self.config_dict[model_name]

         if self.args.fpaa:
              raise NotImplementedError("Mixed precision is currently not supported."					)

         UpperCAmelCase_			       =  (
             hasattr(__a  ,     "architectures"					)
             and isinstance(config.architectures  ,     __a					)
             and len(config.architectures					) > 0
         )
         if not self.args.only_pretrain_model and has_model_class_in_config:
              try:
                   UpperCAmelCase_			       =  "TF" + config.architectures[0]  # prepend 'TF' for tensorflow model
                   UpperCAmelCase_			       =  __import__("transformers"  ,     fromlist=[model_class]					)
                   UpperCAmelCase_			       =  getattr(__a  ,     __a					)
                   UpperCAmelCase_			       =  model_cls(__a					)
              except ImportError:
                   raise ImportError(
                       f"""{model_class} does not exist. If you just want to test the pretrained model, you might want to"""
                       " set `--only_pretrain_model` or `args.only_pretrain_model=True`."					)
         else:
              UpperCAmelCase_			       =  TF_MODEL_MAPPING[config.__class__](__a					)

         # encoder-decoder has vocab size saved differently
         UpperCAmelCase_			       =  config.vocab_size if hasattr(__a  ,     "vocab_size"					) else config.encoder.vocab_size
         UpperCAmelCase_			       =  random_input_ids(__a  ,     __a  ,     __a					)

         @run_with_tf_optimizations(self.args.eager_mode  ,     self.args.use_xla					)
         def encoder_decoder_forward():
              return model(__a  ,     decoder_input_ids=__a  ,     training=__a					)

         @run_with_tf_optimizations(self.args.eager_mode  ,     self.args.use_xla					)
         def encoder_forward():
              return model(__a  ,     training=__a					)

         UpperCAmelCase_			       =  encoder_decoder_forward if config.is_encoder_decoder else encoder_forward

         return _inference



    def    _lowercase		(self       :       Dict  ,     __a       :       str  ,     __a       :       int  ,     __a       :       int					):
         UpperCAmelCase_			       =  self.config_dict[model_name]

         if self.args.eager_mode is not False:
              raise ValueError("Training cannot be done in eager mode. Please make sure that `args.eager_mode = False`."					)

         if self.args.fpaa:
              raise NotImplementedError("Mixed precision is currently not supported."					)

         UpperCAmelCase_			       =  (
             hasattr(__a  ,     "architectures"					)
             and isinstance(config.architectures  ,     __a					)
             and len(config.architectures					) > 0
         )
         if not self.args.only_pretrain_model and has_model_class_in_config:
              try:
                   UpperCAmelCase_			       =  "TF" + config.architectures[0]  # prepend 'TF' for tensorflow model
                   UpperCAmelCase_			       =  __import__("transformers"  ,     fromlist=[model_class]					)
                   UpperCAmelCase_			       =  getattr(__a  ,     __a					)
                   UpperCAmelCase_			       =  model_cls(__a					)
              except ImportError:
                   raise ImportError(
                       f"""{model_class} does not exist. If you just want to test the pretrained model, you might want to"""
                       " set `--only_pretrain_model` or `args.only_pretrain_model=True`."					)
         else:
              UpperCAmelCase_			       =  TF_MODEL_WITH_LM_HEAD_MAPPING[config.__class__](__a					)

         # encoder-decoder has vocab size saved differently
         UpperCAmelCase_			       =  config.vocab_size if hasattr(__a  ,     "vocab_size"					) else config.encoder.vocab_size
         UpperCAmelCase_			       =  random_input_ids(__a  ,     __a  ,     __a					)

         @run_with_tf_optimizations(self.args.eager_mode  ,     self.args.use_xla					)
         def encoder_decoder_train():
              UpperCAmelCase_			       =  model(__a  ,     decoder_input_ids=__a  ,     labels=__a  ,     training=__a					)[0]
              UpperCAmelCase_			       =  tf.gradients(__a  ,     model.trainable_variables					)
              return gradients

         @run_with_tf_optimizations(self.args.eager_mode  ,     self.args.use_xla					)
         def encoder_train():
              UpperCAmelCase_			       =  model(__a  ,     labels=__a  ,     training=__a					)[0]
              UpperCAmelCase_			       =  tf.gradients(__a  ,     model.trainable_variables					)
              return gradients

         UpperCAmelCase_			       =  encoder_decoder_train if config.is_encoder_decoder else encoder_train

         return _train



    def    _lowercase		(self       :       Dict  ,     __a       :       str					):
         with self.args.strategy.scope():
              try:
                   if self.args.is_tpu or self.args.use_xla:
                        # run additional 10 times to stabilize compilation for tpu
                        logger.info("Do inference on TPU. Running model 5 times to stabilize compilation"					)
                        timeit.repeat(__a  ,     repeat=1  ,     number=5					)

                   # as written in https://docs.python.org/2/library/timeit.html#timeit.Timer.repeat, min should be taken rather than the average
                   UpperCAmelCase_			       =  timeit.repeat(
                       __a  ,     repeat=self.args.repeat  ,     number=10  ,     )

                   return min(__a					) / 10.0
              except ResourceExhaustedError as e:
                   self.print_fn(f"""Doesn't fit on GPU. {e}"""					)






    def    _lowercase		(self       :       Dict  ,     __a       :       Callable[[], None]					):
         logger.info(
             "Note that TensorFlow allocates more memory than "
             "it might need to speed up computation. "
             "The memory reported here corresponds to the memory "
             "reported by `nvidia-smi`, which can vary depending "
             "on total available memory on the GPU that is used."					)
         with self.args.strategy.scope():
              try:
                   if self.args.trace_memory_line_by_line:
                        if not self.args.eager_mode:
                             raise ValueError(
                                 "`args.eager_mode` is set to `False`. Make sure to run model in eager mode to measure memory"
                                 " consumption line by line."					)
                        UpperCAmelCase_			       =  start_memory_tracing("transformers"					)

                   if self.args.is_tpu:
                        # tpu
                        raise NotImplementedError(
                            "Memory Benchmarking is currently not implemented for TPU. Please disable memory benchmarking"
                            " with `args.memory=False`"					)
                   elif self.args.is_gpu:
                        # gpu
                        if not is_pyanvml_available():
                             logger.warning(
                                 "py3nvml not installed, we won't log GPU memory usage. "
                                 "Install py3nvml (pip install py3nvml) to log information about GPU."					)
                             UpperCAmelCase_			       =  "N/A"
                        else:
                             logger.info(
                                 "Measuring total GPU usage on GPU device. Make sure to not have additional processes"
                                 " running on the same GPU."					)
                             # init nvml
                             nvml.nvmlInit()
                             func()
                             UpperCAmelCase_			       =  nvml.nvmlDeviceGetHandleByIndex(self.args.device_idx					)
                             UpperCAmelCase_			       =  nvml.nvmlDeviceGetMemoryInfo(__a					)
                             UpperCAmelCase_			       =  meminfo.used
                             UpperCAmelCase_			       =  Memory(__a					)
                             # shutdown nvml
                             nvml.nvmlShutdown()
                   else:
                        # cpu
                        if self.args.trace_memory_line_by_line:
                             logger.info(
                                 "When enabling line by line tracing, the max peak memory for CPU is inaccurate in"
                                 " TensorFlow."					)
                             UpperCAmelCase_			       =  None
                        else:
                             UpperCAmelCase_			       =  measure_peak_memory_cpu(__a					)
                             UpperCAmelCase_			       =  Memory(__a					) if isinstance(__a  ,     __a					) else memory_bytes
                   if self.args.trace_memory_line_by_line:
                        UpperCAmelCase_			       =  stop_memory_tracing(__a					)
                        if memory is None:
                             UpperCAmelCase_			       =  summary.total
                   else:
                        UpperCAmelCase_			       =  None

                   return memory, summary
              except ResourceExhaustedError as e:
                   self.print_fn(f"""Doesn't fit on GPU. {e}"""					)
                   return "N/A", None











import logging
import math
import os
from dataclasses import dataclass, field
from glob import glob
from typing import Optional

from torch.utils.data import ConcatDataset

import transformers
from transformers import (
    CONFIG_MAPPING,
    MODEL_WITH_LM_HEAD_MAPPING,
    AutoConfig,
    AutoModelWithLMHead,
    AutoTokenizer,
    DataCollatorForLanguageModeling,
    DataCollatorForPermutationLanguageModeling,
    DataCollatorForWholeWordMask,
    HfArgumentParser,
    LineByLineTextDataset,
    LineByLineWithRefDataset,
    PreTrainedTokenizer,
    TextDataset,
    Trainer,
    TrainingArguments,
    set_seed,
)
from transformers.trainer_utils import is_main_process


a__: List[Any]							   =						logging.getLogger(__name__)


a__: str							   =						list(MODEL_WITH_LM_HEAD_MAPPING.keys())
a__: Tuple							   =						tuple(conf.model_type for conf in MODEL_CONFIG_CLASSES)




@dataclass
class        SCREAMING_SNAKE_CASE__					:
 __SCREAMING_SNAKE_CASE							=      field(
     default=UpperCamelCase__							,   metadata={
         '''help''': (
             '''The model checkpoint for weights initialization. Leave None if you want to train a model from'''
             ''' scratch.'''
         )
     }							,   )
 __SCREAMING_SNAKE_CASE							=      field(
     default=UpperCamelCase__							,   metadata={'''help''': '''If training from scratch, pass a model type from the list: ''' + ''', '''.join(UpperCamelCase__ )}							,   )
 __SCREAMING_SNAKE_CASE							=      field(
     default=UpperCamelCase__							,   metadata={'''help''': '''Pretrained config name or path if not the same as model_name'''} )
 __SCREAMING_SNAKE_CASE							=      field(
     default=UpperCamelCase__							,   metadata={'''help''': '''Pretrained tokenizer name or path if not the same as model_name'''} )
 __SCREAMING_SNAKE_CASE							=      field(
     default=UpperCamelCase__							,   metadata={'''help''': '''Where do you want to store the pretrained models downloaded from huggingface.co'''}							,   )




@dataclass
class        SCREAMING_SNAKE_CASE__					:
 __SCREAMING_SNAKE_CASE							=      field(
     default=UpperCamelCase__							,   metadata={'''help''': '''The input training data file (a text file).'''} )
 __SCREAMING_SNAKE_CASE							=      field(
     default=UpperCamelCase__							,   metadata={
         '''help''': (
             '''The input training data files (multiple files in glob format). '''
             '''Very often splitting large files to smaller files can prevent tokenizer going out of memory'''
         )
     }							,   )
 __SCREAMING_SNAKE_CASE							=      field(
     default=UpperCamelCase__							,   metadata={'''help''': '''An optional input evaluation data file to evaluate the perplexity on (a text file).'''}							,   )
 __SCREAMING_SNAKE_CASE							=      field(
     default=UpperCamelCase__							,   metadata={'''help''': '''An optional input train ref data file for whole word mask in Chinese.'''}							,   )
 __SCREAMING_SNAKE_CASE							=      field(
     default=UpperCamelCase__							,   metadata={'''help''': '''An optional input eval ref data file for whole word mask in Chinese.'''}							,   )
 __SCREAMING_SNAKE_CASE							=      field(
     default=UpperCamelCase__							,   metadata={'''help''': '''Whether distinct lines of text in the dataset are to be handled as distinct sequences.'''}							,   )

 __SCREAMING_SNAKE_CASE							=      field(
     default=UpperCamelCase__							,   metadata={'''help''': '''Train with masked-language modeling loss instead of language modeling.'''} )
 __SCREAMING_SNAKE_CASE							=      field(default=UpperCamelCase__							,   metadata={'''help''': '''Whether ot not to use whole word mask.'''} )
 __SCREAMING_SNAKE_CASE							=      field(
     default=0.1_5							,   metadata={'''help''': '''Ratio of tokens to mask for masked language modeling loss'''} )
 __SCREAMING_SNAKE_CASE							=      field(
     default=1 / 6							,   metadata={
         '''help''': (
             '''Ratio of length of a span of masked tokens to surrounding context length for permutation language'''
             ''' modeling.'''
         )
     }							,   )
 __SCREAMING_SNAKE_CASE							=      field(
     default=5							,   metadata={'''help''': '''Maximum length of a span of masked tokens for permutation language modeling.'''} )

 __SCREAMING_SNAKE_CASE							=      field(
     default=-1							,   metadata={
         '''help''': (
             '''Optional input sequence length after tokenization.'''
             '''The training dataset will be truncated in block of this size for training.'''
             '''Default to the model max input length for single sentence inputs (take into account special tokens).'''
         )
     }							,   )
 __SCREAMING_SNAKE_CASE							=      field(
     default=UpperCamelCase__							,   metadata={'''help''': '''Overwrite the cached training and evaluation sets'''} )


def       UpperCamelCase__(			UpperCamelCase__     :			DataTrainingArguments					,	UpperCamelCase__     :			PreTrainedTokenizer					,	UpperCamelCase__     :			bool = False					,	UpperCamelCase__     :			Optional[str] = None					,	)->str:
       def _dataset(UpperCamelCase__     :			List[str]					,	UpperCamelCase__     :			Optional[int]=None    ):
              if args.line_by_line:
                     if ref_path is not None:
                            if not args.whole_word_mask or not args.mlm:
                                   raise ValueError('''You need to set world whole masking and mlm to True for Chinese Whole Word Mask'''    )
                            return LineByLineWithRefDataset(
                                tokenizer=UpperCamelCase__					,	file_path=UpperCamelCase__					,	block_size=args.block_size					,	ref_path=UpperCamelCase__					,	)

                     return LineByLineTextDataset(tokenizer=UpperCamelCase__					,	file_path=UpperCamelCase__					,	block_size=args.block_size    )
              else:
                     return TextDataset(
                         tokenizer=UpperCamelCase__					,	file_path=UpperCamelCase__					,	block_size=args.block_size					,	overwrite_cache=args.overwrite_cache					,	cache_dir=UpperCamelCase__					,	)

       if evaluate:
              return _dataset(args.eval_data_file					,	args.eval_ref_file    )
       elif args.train_data_files:
              return ConcatDataset([_dataset(UpperCamelCase__    ) for f in glob(args.train_data_files    )]    )
       else:
              return _dataset(args.train_data_file					,	args.train_ref_file    )


def       UpperCamelCase__(			)->List[Any]:
       # See all possible arguments in src/transformers/training_args.py
       # or by passing the --help flag to this script.
       # We now keep distinct sets of args, for a cleaner separation of concerns.

       A__		   =		HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments)    )
       A__   ,      A__   ,      A__		   =		parser.parse_args_into_dataclasses()

       if data_args.eval_data_file is None and training_args.do_eval:
              raise ValueError(
                  '''Cannot do evaluation without an evaluation data file. Either supply a file to --eval_data_file '''
                  '''or remove the --do_eval argument.'''    )
       if (
           os.path.exists(training_args.output_dir    )
           and os.listdir(training_args.output_dir    )
           and training_args.do_train
           and not training_args.overwrite_output_dir
       ):
              raise ValueError(
                  f"Output directory ({training_args.output_dir}) already exists and is not empty. Use"
                  ''' --overwrite_output_dir to overcome.'''    )

       # Setup logging
       logging.basicConfig(
           format='''%(asctime)s - %(levelname)s - %(name)s - %(message)s'''					,	datefmt='''%m/%d/%Y %H:%M:%S'''					,	level=logging.INFO if training_args.local_rank in [-1, 0] else logging.WARN					,	)
       logger.warning(
           '''Process rank: %s, device: %s, n_gpu: %s, distributed training: %s, 16-bits training: %s'''					,	training_args.local_rank					,	training_args.device					,	training_args.n_gpu					,	bool(training_args.local_rank != -1    )					,	training_args.fpaa					,	)
       # Set the verbosity to info of the Transformers logger (on main process only):
       if is_main_process(training_args.local_rank    ):
              transformers.utils.logging.set_verbosity_info()
              transformers.utils.logging.enable_default_handler()
              transformers.utils.logging.enable_explicit_format()
       logger.info('''Training/evaluation parameters %s'''					,	UpperCamelCase__    )

       # Set seed
       set_seed(training_args.seed    )

       # Load pretrained model and tokenizer
       #
       # Distributed training:
       # The .from_pretrained methods guarantee that only one local process can concurrently
       # download model & vocab.

       if model_args.config_name:
              A__		   =		AutoConfig.from_pretrained(model_args.config_name					,	cache_dir=model_args.cache_dir    )
       elif model_args.model_name_or_path:
              A__		   =		AutoConfig.from_pretrained(model_args.model_name_or_path					,	cache_dir=model_args.cache_dir    )
       else:
              A__		   =		CONFIG_MAPPING[model_args.model_type]()
              logger.warning('''You are instantiating a new config instance from scratch.'''    )

       if model_args.tokenizer_name:
              A__		   =		AutoTokenizer.from_pretrained(model_args.tokenizer_name					,	cache_dir=model_args.cache_dir    )
       elif model_args.model_name_or_path:
              A__		   =		AutoTokenizer.from_pretrained(model_args.model_name_or_path					,	cache_dir=model_args.cache_dir    )
       else:
              raise ValueError(
                  '''You are instantiating a new tokenizer from scratch. This is not supported, but you can do it from another'''
                  ''' script, save it,and load it from here, using --tokenizer_name'''    )

       if model_args.model_name_or_path:
              A__		   =		AutoModelWithLMHead.from_pretrained(
                  model_args.model_name_or_path					,	from_tf=bool('''.ckpt''' in model_args.model_name_or_path    )					,	config=UpperCamelCase__					,	cache_dir=model_args.cache_dir					,	)
       else:
              logger.info('''Training new model from scratch'''    )
              A__		   =		AutoModelWithLMHead.from_config(UpperCamelCase__    )

       model.resize_token_embeddings(len(UpperCamelCase__    )    )

       if config.model_type in ["bert", "roberta", "distilbert", "camembert"] and not data_args.mlm:
              raise ValueError(
                  '''BERT and RoBERTa-like models do not have LM heads but masked LM heads. They must be run using the'''
                  '''--mlm flag (masked language modeling).'''    )

       if data_args.block_size <= 0:
              A__		   =		tokenizer.max_len
              # Our input block size will be the max possible for the model
       else:
              A__		   =		min(data_args.block_size					,	tokenizer.max_len    )

       # Get datasets

       A__		   =		(
           get_dataset(UpperCamelCase__					,	tokenizer=UpperCamelCase__					,	cache_dir=model_args.cache_dir    ) if training_args.do_train else None
       )
       A__		   =		(
           get_dataset(UpperCamelCase__					,	tokenizer=UpperCamelCase__					,	evaluate=UpperCamelCase__					,	cache_dir=model_args.cache_dir    )
           if training_args.do_eval
           else None
       )
       if config.model_type == "xlnet":
              A__		   =		DataCollatorForPermutationLanguageModeling(
                  tokenizer=UpperCamelCase__					,	plm_probability=data_args.plm_probability					,	max_span_length=data_args.max_span_length					,	)
       else:
              if data_args.mlm and data_args.whole_word_mask:
                     A__		   =		DataCollatorForWholeWordMask(
                         tokenizer=UpperCamelCase__					,	mlm_probability=data_args.mlm_probability    )
              else:
                     A__		   =		DataCollatorForLanguageModeling(
                         tokenizer=UpperCamelCase__					,	mlm=data_args.mlm					,	mlm_probability=data_args.mlm_probability    )

    # Initialize our Trainer
       A__		   =		Trainer(
           model=UpperCamelCase__					,	args=UpperCamelCase__					,	data_collator=UpperCamelCase__					,	train_dataset=UpperCamelCase__					,	eval_dataset=UpperCamelCase__					,	prediction_loss_only=UpperCamelCase__					,	)

       # Training
       if training_args.do_train:
              A__		   =		(
                  model_args.model_name_or_path
                  if model_args.model_name_or_path is not None and os.path.isdir(model_args.model_name_or_path    )
                  else None
              )
              trainer.train(model_path=UpperCamelCase__    )
              trainer.save_model()
              # For convenience, we also re-save the tokenizer to the same directory,
              # so that you can share your model easily on huggingface.co/models =)
              if trainer.is_world_master():
                     tokenizer.save_pretrained(training_args.output_dir    )

    # Evaluation
       A__		   =		{}
       if training_args.do_eval:
              logger.info('''*** Evaluate ***'''    )

              A__		   =		trainer.evaluate()

              A__		   =		math.exp(eval_output['''eval_loss''']    )
              A__		   =		{'''perplexity''': perplexity}

              A__		   =		os.path.join(training_args.output_dir					,	'''eval_results_lm.txt'''    )
              if trainer.is_world_master():
                     with open(UpperCamelCase__					,	'''w'''    ) as writer:
                            logger.info('''***** Eval results *****'''    )
                            for key in sorted(result.keys()    ):
                                   logger.info('''  %s = %s'''					,	UpperCamelCase__					,	str(result[key]    )    )
                                   writer.write('''%s = %s\n''' % (key, str(result[key]    ))    )

              results.update(UpperCamelCase__    )

       return results


def       UpperCamelCase__(			UpperCamelCase__     :			List[str]    )->List[str]:
       # For xla_spawn (TPUs)
       main()


if __name__ == "__main__":
       main()





