





'''simple docstring'''



import collections
import importlib.util
import os
import re
from pathlib import Path


_SCREAMING_SNAKE_CASE					=    '''src/transformers'''


# Matches is_xxx_available()
_SCREAMING_SNAKE_CASE					=    re.compile(R'''is\_([a-z_]*)_available()''')
# Catches a one-line _import_struct = {xxx}
_SCREAMING_SNAKE_CASE					=    re.compile(R'''^_import_structure\s+=\s+\{([^\}]+)\}''')
# Catches a line with a key-values pattern: "bla": ["foo", "bar"]
_SCREAMING_SNAKE_CASE					=    re.compile(R'''\s+\"\S*\":\s+\[([^\]]*)\]''')
# Catches a line if not is_foo_available
_SCREAMING_SNAKE_CASE					=    re.compile(R'''^\s*if\s+not\s+is\_[a-z_]*\_available\(\)''')
# Catches a line _import_struct["bla"].append("foo")
_SCREAMING_SNAKE_CASE					=    re.compile(R'''^\s*_import_structure\[\"\S*\"\]\.append\(\"(\S*)\"\)''')
# Catches a line _import_struct["bla"].extend(["foo", "bar"]) or _import_struct["bla"] = ["foo", "bar"]
_SCREAMING_SNAKE_CASE					=    re.compile(R'''^\s*_import_structure\[\S*\](?:\.extend\(|\s*=\s+)\[([^\]]*)\]''')
# Catches a line with an object between quotes and a comma:     "MyModel",
_SCREAMING_SNAKE_CASE					=    re.compile('''^\s+\"([^\"]+)\",''')
# Catches a line with objects between brackets only:    ["foo", "bar"],
_SCREAMING_SNAKE_CASE					=    re.compile('''^\s+\[([^\]]+)\]''')
# Catches a line with from foo import bar, bla, boo
_SCREAMING_SNAKE_CASE					=    re.compile(R'''\s+from\s+\S*\s+import\s+([^\(\s].*)\n''')
# Catches a line with try:
_SCREAMING_SNAKE_CASE					=    re.compile(R'''^\s*try:''')
# Catches a line with else:
_SCREAMING_SNAKE_CASE					=    re.compile(R'''^\s*else:''')




def    _lowerCAmelCase						(				lowerCamelCase_			:  Optional[int]				):







			if _re_test_backend.search(__UpperCAmelCase				) is None:
						return None
			__lowercase										=							[b[0] for b in _re_backend.findall(__UpperCAmelCase				)]
			backends.sort()
			return "_and_".join(__UpperCAmelCase				)




def    _lowerCAmelCase						(				lowerCamelCase_			:  Any				):







			with open(__UpperCAmelCase		,       '''r'''		,       encoding='''utf-8'''		,       newline='''\n'''				) as f:
						__lowercase										=							f.readlines()

			__lowercase										=							0
			while line_index < len(__UpperCAmelCase				) and not lines[line_index].startswith('''_import_structure = {'''				):
						line_index += 1

			# If this is a traditional init, just return.
			if line_index >= len(__UpperCAmelCase				):
						return None

			# First grab the objects without a specific backend in _import_structure
			__lowercase										=							[]
			while not lines[line_index].startswith('''if TYPE_CHECKING'''				) and find_backend(lines[line_index]				) is None:
						__lowercase										=							lines[line_index]
						# If we have everything on a single line, let's deal with it.
						if _re_one_line_import_struct.search(__UpperCAmelCase				):
									__lowercase										=							_re_one_line_import_struct.search(__UpperCAmelCase				).groups()[0]
									__lowercase										=							re.findall('''\[([^\]]+)\]'''		,       __UpperCAmelCase				)
									for imp in imports:
												objects.extend([obj[1:-1] for obj in imp.split(''', '''				)]				)
									line_index += 1
									continue
						__lowercase										=							_re_import_struct_key_value.search(__UpperCAmelCase				)
						if single_line_import_search is not None:
									__lowercase										=							[obj[1:-1] for obj in single_line_import_search.groups()[0].split(''', '''				) if len(__UpperCAmelCase				) > 0]
									objects.extend(__UpperCAmelCase				)
						elif line.startswith(''' ''' * 8 + '''\"'''				):
									objects.append(line[9:-3]				)
						line_index += 1

			__lowercase										=							{'''none''': objects}
			# Let's continue with backend-specific objects in _import_structure
			while not lines[line_index].startswith('''if TYPE_CHECKING'''				):
						# If the line is an if not is_backend_available, we grab all objects associated.
						__lowercase										=							find_backend(lines[line_index]				)
						# Check if the backend declaration is inside a try block:
						if _re_try.search(lines[line_index - 1]				) is None:
									__lowercase										=							None

						if backend is not None:
									line_index += 1

									# Scroll until we hit the else block of try-except-else
									while _re_else.search(lines[line_index]				) is None:
												line_index += 1

									line_index += 1

									__lowercase										=							[]
									# Until we unindent, add backend objects to the list
									while len(lines[line_index]				) <= 1 or lines[line_index].startswith(''' ''' * 4				):
												__lowercase										=							lines[line_index]
												if _re_import_struct_add_one.search(__UpperCAmelCase				) is not None:
															objects.append(_re_import_struct_add_one.search(__UpperCAmelCase				).groups()[0]				)
												elif _re_import_struct_add_many.search(__UpperCAmelCase				) is not None:
															__lowercase										=							_re_import_struct_add_many.search(__UpperCAmelCase				).groups()[0].split(''', '''				)
															__lowercase										=							[obj[1:-1] for obj in imports if len(__UpperCAmelCase				) > 0]
															objects.extend(__UpperCAmelCase				)
												elif _re_between_brackets.search(__UpperCAmelCase				) is not None:
															__lowercase										=							_re_between_brackets.search(__UpperCAmelCase				).groups()[0].split(''', '''				)
															__lowercase										=							[obj[1:-1] for obj in imports if len(__UpperCAmelCase				) > 0]
															objects.extend(__UpperCAmelCase				)
												elif _re_quote_object.search(__UpperCAmelCase				) is not None:
															objects.append(_re_quote_object.search(__UpperCAmelCase				).groups()[0]				)
												elif line.startswith(''' ''' * 8 + '''\"'''				):
															objects.append(line[9:-3]				)
												elif line.startswith(''' ''' * 1_2 + '''\"'''				):
															objects.append(line[1_3:-3]				)
												line_index += 1

									__lowercase										=							objects
						else:
									line_index += 1

    # At this stage we are in the TYPE_CHECKING part, first grab the objects without a specific backend
			__lowercase										=							[]
			while (
			    line_index < len(__UpperCAmelCase				)
			    and find_backend(lines[line_index]				) is None
			    and not lines[line_index].startswith('''else'''				)
			):
						__lowercase										=							lines[line_index]
						__lowercase										=							_re_import.search(__UpperCAmelCase				)
						if single_line_import_search is not None:
									objects.extend(single_line_import_search.groups()[0].split(''', '''				)				)
						elif line.startswith(''' ''' * 8				):
									objects.append(line[8:-2]				)
						line_index += 1

			__lowercase										=							{'''none''': objects}
			# Let's continue with backend-specific objects
			while line_index < len(__UpperCAmelCase				):
						# If the line is an if is_backend_available, we grab all objects associated.
						__lowercase										=							find_backend(lines[line_index]				)
						# Check if the backend declaration is inside a try block:
						if _re_try.search(lines[line_index - 1]				) is None:
									__lowercase										=							None

						if backend is not None:
									line_index += 1

									# Scroll until we hit the else block of try-except-else
									while _re_else.search(lines[line_index]				) is None:
												line_index += 1

									line_index += 1

									__lowercase										=							[]
									# Until we unindent, add backend objects to the list
									while len(lines[line_index]				) <= 1 or lines[line_index].startswith(''' ''' * 8				):
												__lowercase										=							lines[line_index]
												__lowercase										=							_re_import.search(__UpperCAmelCase				)
												if single_line_import_search is not None:
															objects.extend(single_line_import_search.groups()[0].split(''', '''				)				)
												elif line.startswith(''' ''' * 1_2				):
															objects.append(line[1_2:-2]				)
												line_index += 1

									__lowercase										=							objects
						else:
									line_index += 1

			return import_dict_objects, type_hint_objects




def    _lowerCAmelCase						(				lowerCamelCase_			:  Optional[Any]		,       lowerCamelCase_			:  Optional[int]				):







			def find_duplicates(lowerCamelCase_			:  int				):
						return [k for k, v in collections.Counter(__UpperCAmelCase				).items() if v > 1]

			if list(import_dict_objects.keys()				) != list(type_hint_objects.keys()				):
						return ["Both sides of the init do not have the same backends!"]

			__lowercase										=							[]
			for key in import_dict_objects.keys():
						__lowercase										=							find_duplicates(import_dict_objects[key]				)
						if duplicate_imports:
									errors.append(f"Duplicate _import_structure definitions for: {duplicate_imports}"				)
						__lowercase										=							find_duplicates(type_hint_objects[key]				)
						if duplicate_type_hints:
									errors.append(f"Duplicate TYPE_CHECKING objects for: {duplicate_type_hints}"				)

						if sorted(set(import_dict_objects[key]				)				) != sorted(set(type_hint_objects[key]				)				):
									__lowercase										=							'''base imports''' if key == '''none''' else f"{key} backend"
									errors.append(f"Differences for {name}:"				)
									for a in type_hint_objects[key]:
												if a not in import_dict_objects[key]:
															errors.append(f"  {a} in TYPE_HINT but not in _import_structure."				)
									for a in import_dict_objects[key]:
												if a not in type_hint_objects[key]:
															errors.append(f"  {a} in _import_structure but not in TYPE_HINT."				)
			return errors




def    _lowerCAmelCase						(				):
			__lowercase										=							[]
			for root, _, files in os.walk(__UpperCAmelCase				):
						if "__init__.py" in files:
									__lowercase										=							os.path.join(__UpperCAmelCase		,       '''__init__.py'''				)
									__lowercase										=							parse_init(__UpperCAmelCase				)
									if objects is not None:
												__lowercase										=							analyze_results(*__UpperCAmelCase				)
												if len(__UpperCAmelCase				) > 0:
															__lowercase										=							f"Problem in {fname}, both halves do not define the same objects.\n{errors[0]}"
															failures.append('''\n'''.join(__UpperCAmelCase				)				)
			if len(__UpperCAmelCase				) > 0:
						raise ValueError('''\n\n'''.join(__UpperCAmelCase				)				)




def    _lowerCAmelCase						(				):
			__lowercase										=							[]
			for path, directories, files in os.walk(__UpperCAmelCase				):
						for folder in directories:
									# Ignore private modules
									if folder.startswith('''_'''				):
												directories.remove(__UpperCAmelCase				)
												continue
									# Ignore leftovers from branches (empty folders apart from pycache)
									if len(list((Path(__UpperCAmelCase				) / folder).glob('''*.py'''				)				)				) == 0:
												continue
									__lowercase										=							str((Path(__UpperCAmelCase				) / folder).relative_to(__UpperCAmelCase				)				)
									__lowercase										=							short_path.replace(os.path.sep		,       '''.'''				)
									submodules.append(__UpperCAmelCase				)
						for fname in files:
									if fname == "__init__.py":
												continue
									__lowercase										=							str((Path(__UpperCAmelCase				) / fname).relative_to(__UpperCAmelCase				)				)
									__lowercase										=							short_path.replace('''.py'''		,       ''''''				).replace(os.path.sep		,       '''.'''				)
									if len(submodule.split('''.'''				)				) == 1:
												submodules.append(__UpperCAmelCase				)
			return submodules


_SCREAMING_SNAKE_CASE					=    [
    '''convert_pytorch_checkpoint_to_tf2''',
    '''modeling_flax_pytorch_utils''',
]




def    _lowerCAmelCase						(				):
			__lowercase										=							importlib.util.spec_from_file_location(
			    '''transformers'''		,       os.path.join(__UpperCAmelCase		,       '''__init__.py'''				)		,       submodule_search_locations=[PATH_TO_TRANSFORMERS]		,       )
			__lowercase										=							spec.loader.load_module()

			__lowercase										=							[
			    module
			    for module in get_transformers_submodules()
			    if module not in IGNORE_SUBMODULES and module not in transformers._import_structure.keys()
			]
			if len(__UpperCAmelCase				) > 0:
						__lowercase										=							'''\n'''.join(f"- {module}" for module in module_not_registered				)
						raise ValueError(
						    '''The following submodules are not properly registered in the main init of Transformers:\n'''
						    f"{list_of_modules}\n"
						    '''Make sure they appear somewhere in the keys of `_import_structure` with an empty list as value.'''				)


if __name__ == "__main__":
							check_all_inits()
							check_submodules()












'''simple docstring'''



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


_SCREAMING_SNAKE_CASE					=    logging.getLogger(__name__)


_SCREAMING_SNAKE_CASE					=    list(MODEL_WITH_LM_HEAD_MAPPING.keys())
_SCREAMING_SNAKE_CASE					=    tuple(conf.model_type for conf in MODEL_CONFIG_CLASSES)






@dataclass
class 							__lowercase       :







	'''simple docstring'''

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






@dataclass
class 							__lowercase       :







	'''simple docstring'''

	a    :				Optional[str]											=       field(
	    default=lowerCAmelCase__ ,      metadata={"help": "The input training data file (a text file)."}						)
	a    :				Optional[str]											=       field(
	    default=lowerCAmelCase__ ,      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"
	        )
	    } ,      )
	a    :				Optional[str]											=       field(
	    default=lowerCAmelCase__ ,      metadata={"help": "An optional input evaluation data file to evaluate the perplexity on (a text file)."} ,      )
	a    :				Optional[str]											=       field(
	    default=lowerCAmelCase__ ,      metadata={"help": "An optional input train ref data file for whole word mask in Chinese."} ,      )
	a    :				Optional[str]											=       field(
	    default=lowerCAmelCase__ ,      metadata={"help": "An optional input eval ref data file for whole word mask in Chinese."} ,      )
	a    :				bool											=       field(
	    default=lowerCAmelCase__ ,      metadata={"help": "Whether distinct lines of text in the dataset are to be handled as distinct sequences."} ,      )

	a    :				bool											=       field(
	    default=lowerCAmelCase__ ,      metadata={"help": "Train with masked-language modeling loss instead of language modeling."}						)
	a    :				bool											=       field(default=lowerCAmelCase__ ,      metadata={"help": "Whether ot not to use whole word mask."}						)
	a    :				float											=       field(
	    default=0.15 ,      metadata={"help": "Ratio of tokens to mask for masked language modeling loss"}						)
	a    :				float											=       field(
	    default=1 / 6 ,      metadata={
	        "help": (
	            "Ratio of length of a span of masked tokens to surrounding context length for permutation language"
	            " modeling."
	        )
	    } ,      )
	a    :				int											=       field(
	    default=5 ,      metadata={"help": "Maximum length of a span of masked tokens for permutation language modeling."}						)

	a    :				int											=       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)."
	        )
	    } ,      )
	a    :				bool											=       field(
	    default=lowerCAmelCase__ ,      metadata={"help": "Overwrite the cached training and evaluation sets"}						)





def    _lowerCAmelCase						(				lowerCamelCase_			:  DataTrainingArguments		,       lowerCamelCase_			:  PreTrainedTokenizer		,       lowerCamelCase_			:  bool = False		,       lowerCamelCase_			:  Optional[str] = None		,       ):
			def _dataset(lowerCamelCase_			:  str		,       lowerCamelCase_			:  Union[str, Any]=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=lowerCamelCase_		,       file_path=lowerCamelCase_		,       block_size=args.block_size		,       ref_path=lowerCamelCase_		,       )

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

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




def    _lowerCAmelCase						(				):
			# 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.

			__lowercase										=							HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments)				)
			__lowercase						,		__lowercase						,		__lowercase										=							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'''		,       lowerCamelCase_				)

			# 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:
						__lowercase										=							AutoConfig.from_pretrained(model_args.config_name		,       cache_dir=model_args.cache_dir				)
			elif model_args.model_name_or_path:
						__lowercase										=							AutoConfig.from_pretrained(model_args.model_name_or_path		,       cache_dir=model_args.cache_dir				)
			else:
						__lowercase										=							CONFIG_MAPPING[model_args.model_type]()
						logger.warning('''You are instantiating a new config instance from scratch.'''				)

			if model_args.tokenizer_name:
						__lowercase										=							AutoTokenizer.from_pretrained(model_args.tokenizer_name		,       cache_dir=model_args.cache_dir				)
			elif model_args.model_name_or_path:
						__lowercase										=							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:
						__lowercase										=							AutoModelWithLMHead.from_pretrained(
						    model_args.model_name_or_path		,       from_tf=bool('''.ckpt''' in model_args.model_name_or_path				)		,       config=lowerCamelCase_		,       cache_dir=model_args.cache_dir		,       )
			else:
						logger.info('''Training new model from scratch'''				)
						__lowercase										=							AutoModelWithLMHead.from_config(lowerCamelCase_				)

			model.resize_token_embeddings(len(lowerCamelCase_				)				)

			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:
						__lowercase										=							tokenizer.max_len
						# Our input block size will be the max possible for the model
			else:
						__lowercase										=							min(data_args.block_size		,       tokenizer.max_len				)

			# Get datasets

			__lowercase										=							(
			    get_dataset(lowerCamelCase_		,       tokenizer=lowerCamelCase_		,       cache_dir=model_args.cache_dir				) if training_args.do_train else None
			)
			__lowercase										=							(
			    get_dataset(lowerCamelCase_		,       tokenizer=lowerCamelCase_		,       evaluate=lowerCamelCase_		,       cache_dir=model_args.cache_dir				)
			    if training_args.do_eval
			    else None
			)
			if config.model_type == "xlnet":
						__lowercase										=							DataCollatorForPermutationLanguageModeling(
						    tokenizer=lowerCamelCase_		,       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:
									__lowercase										=							DataCollatorForWholeWordMask(
									    tokenizer=lowerCamelCase_		,       mlm_probability=data_args.mlm_probability				)
						else:
									__lowercase										=							DataCollatorForLanguageModeling(
									    tokenizer=lowerCamelCase_		,       mlm=data_args.mlm		,       mlm_probability=data_args.mlm_probability				)

    # Initialize our Trainer
			__lowercase										=							Trainer(
			    model=lowerCamelCase_		,       args=lowerCamelCase_		,       data_collator=lowerCamelCase_		,       train_dataset=lowerCamelCase_		,       eval_dataset=lowerCamelCase_		,       prediction_loss_only=lowerCamelCase_		,       )

			# Training
			if training_args.do_train:
						__lowercase										=							(
						    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=lowerCamelCase_				)
						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
			__lowercase										=							{}
			if training_args.do_eval:
						logger.info('''*** Evaluate ***'''				)

						__lowercase										=							trainer.evaluate()

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

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

						results.update(lowerCamelCase_				)

			return results




def    _lowerCAmelCase						(				lowerCamelCase_			:  str				):
			# For xla_spawn (TPUs)
			main()


if __name__ == "__main__":
	main()





