



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


__snake_case						:Optional[int]      		=     logging.getLogger(__name__)


__snake_case						:Dict      		=     list(MODEL_WITH_LM_HEAD_MAPPING.keys())
__snake_case						:Tuple      		=     tuple(conf.model_type for conf in MODEL_CONFIG_CLASSES)

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


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

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

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





def      __snake_case	(			_UpperCAmelCase   , _UpperCAmelCase   , _UpperCAmelCase = False   , _UpperCAmelCase = None   , ):
    def _dataset(_UpperCAmelCase   , _UpperCAmelCase=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      __snake_case	(			):
    # 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      __snake_case	(			_UpperCAmelCase				):
    # For xla_spawn (TPUs)
    main()


if __name__ == "__main__":
 main()








import argparse
from collections import defaultdict

import yaml


A_       : List[str]         =			'docs/source/en/_toctree.yml'

def 						UpperCamelCase					(lowercase_: Optional[int]					)     ->      List[str]:
	A__							:    Dict        =		defaultdict(lowercase_					)
	A__							:    Optional[int]        =		[]
	A__							:    Union[str, Any]        =		[]
	for doc in doc_list:
		if "local" in doc:
			counts[doc["local"]] += 1

		if doc["title"].lower() == "overview":
			overview_doc.append({"""local""": doc["""local"""], """title""": doc["""title"""]}					)
		else:
			new_doc_list.append(lowercase_					)

	A__							:    Optional[int]        =		new_doc_list
	A__							:    Optional[int]        =		[key for key, value in counts.items() if value > 1]

	A__							:    Optional[Any]        =		[]
	for duplicate_key in duplicates:
		A__							:    List[Any]        =		list({doc["""title"""] for doc in doc_list if doc["""local"""] == duplicate_key}					)
		if len(lowercase_					) > 1:
			raise ValueError(
			    f"""{duplicate_key} is present several times in the documentation table of content at """
			    """`docs/source/en/_toctree.yml` with different *Title* values. Choose one of those and remove the """
			    """others."""					)
		# Only add this once
		new_doc.append({"""local""": duplicate_key, """title""": titles[0]}					)

	# Add none duplicate-keys
	new_doc.extend([doc for doc in doc_list if """local""" not in counts or counts[doc["""local"""]] == 1]					)
	A__							:    Dict        =		sorted(lowercase_    ,      key=lambda lowercase_					: s["title"].lower()					)

	# "overview" gets special treatment and is always first
	if len(lowercase_					) > 1:
		raise ValueError("""{doc_list} has two 'overview' docs which is not allowed."""					)

	overview_doc.extend(lowercase_					)

	# Sort
	return overview_doc

def 						UpperCamelCase					(lowercase_: Tuple=False					)     ->      List[Any]:
	with open(lowercase_    ,      encoding="""utf-8"""					) as f:
		A__							:    Dict        =		yaml.safe_load(f.read()					)

	# Get to the API doc
	A__							:    List[Any]        =		0
	while content[api_idx]["title"] != "API":
		api_idx += 1
	A__							:    Union[str, Any]        =		content[api_idx]["""sections"""]

	# Then to the model doc
	A__							:    Dict        =		0
	while api_doc[scheduler_idx]["title"] != "Schedulers":
		scheduler_idx += 1

	A__							:    List[Any]        =		api_doc[scheduler_idx]["""sections"""]
	A__							:    Union[str, Any]        =		clean_doc_toc(lowercase_					)

	A__							:    Optional[int]        =		False
	if new_scheduler_doc != scheduler_doc:
		A__							:    List[Any]        =		True
		if overwrite:
			A__							:    Optional[int]        =		new_scheduler_doc

	if diff:
		if overwrite:
			A__							:    Tuple        =		api_doc
			with open(lowercase_    ,      """w"""    ,      encoding="""utf-8"""					) as f:
				f.write(yaml.dump(lowercase_    ,      allow_unicode=lowercase_					)					)
		else:
			raise ValueError(
			    """The model doc part of the table of content is not properly sorted, run `make style` to fix this."""					)

def 						UpperCamelCase					(lowercase_: Dict=False					)     ->      Optional[Any]:
	with open(lowercase_    ,      encoding="""utf-8"""					) as f:
		A__							:    int        =		yaml.safe_load(f.read()					)

	# Get to the API doc
	A__							:    Optional[Any]        =		0
	while content[api_idx]["title"] != "API":
		api_idx += 1
	A__							:    List[str]        =		content[api_idx]["""sections"""]

	# Then to the model doc
	A__							:    List[Any]        =		0
	while api_doc[pipeline_idx]["title"] != "Pipelines":
		pipeline_idx += 1

	A__							:    Dict        =		False
	A__							:    Tuple        =		api_doc[pipeline_idx]["""sections"""]
	A__							:    Tuple        =		[]

	# sort sub pipeline docs
	for pipeline_doc in pipeline_docs:
		if "section" in pipeline_doc:
			A__							:    List[Any]        =		pipeline_doc["""section"""]
			A__							:    Dict        =		clean_doc_toc(lowercase_					)
			if overwrite:
				A__							:    Optional[Any]        =		new_sub_pipeline_doc
		new_pipeline_docs.append(lowercase_					)

	# sort overall pipeline doc
	A__							:    Optional[int]        =		clean_doc_toc(lowercase_					)

	if new_pipeline_docs != pipeline_docs:
		A__							:    int        =		True
		if overwrite:
			A__							:    List[Any]        =		new_pipeline_docs

	if diff:
		if overwrite:
			A__							:    Union[str, Any]        =		api_doc
			with open(lowercase_    ,      """w"""    ,      encoding="""utf-8"""					) as f:
				f.write(yaml.dump(lowercase_    ,      allow_unicode=lowercase_					)					)
		else:
			raise ValueError(
			    """The model doc part of the table of content is not properly sorted, run `make style` to fix this."""					)


if __name__ == "__main__":
	A_       : str         =			argparse.ArgumentParser()
	parser.add_argument('--fix_and_overwrite', action='store_true', help='Whether to fix inconsistencies.')
	A_       : str         =			parser.parse_args()

	check_scheduler_doc(args.fix_and_overwrite)
	check_pipeline_doc(args.fix_and_overwrite)



