
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		     =    logging.getLogger(__name__)


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

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



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

 A__  : bool      					=			field(
     default=__SCREAMING_SNAKE_CASE							,		metadata={"""help""": """Train with masked-language modeling loss instead of language modeling."""} )
 A__  : bool      					=			field(default=__SCREAMING_SNAKE_CASE							,		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=__SCREAMING_SNAKE_CASE							,		metadata={"""help""": """Overwrite the cached training and evaluation sets"""} )




def  lowerCamelCase__ (  a__     :     DataTrainingArguments		,					a__     :     PreTrainedTokenizer		,					a__     :     bool = False		,					a__     :     Optional[str] = None		,					)						->		int:

       def _dataset(a__     :     Any		,					a__     :     Tuple=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=__a		,					file_path=__a		,					block_size=args.block_size		,					ref_path=__a		,					)

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

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




def  lowerCamelCase__ (  )						->		str:
       UpperCamelCase_											=				HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments)   )
       UpperCamelCase_				, UpperCamelCase_				, UpperCamelCase_											=				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"""		,					__a   )

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

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

       model.resize_token_embeddings(len(__a   )   )

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

       # Get datasets

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

    # Initialize our Trainer
       UpperCamelCase_											=				Trainer(
           model=__a		,					args=__a		,					data_collator=__a		,					train_dataset=__a		,					eval_dataset=__a		,					prediction_loss_only=__a		,					)

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

              UpperCamelCase_											=				trainer.evaluate()

              UpperCamelCase_											=				math.exp(eval_output["""eval_loss"""]   )
              UpperCamelCase_											=				{"""perplexity""": perplexity}

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

              results.update(__a   )

       return results




def  lowerCamelCase__ (  a__     :     Optional[Any]   )						->		Dict:
       main()


if __name__ == "__main__":
      main()










from sklearn.metrics import fa_score

import datasets


A    :					Any =      '''
The F1 score is the harmonic mean of the precision and recall. It can be computed with the equation:
F1 = 2 * (precision * recall) / (precision + recall)
'''


A    :					List[Any] =      '''
Args:
    predictions (`list` of `int`): Predicted labels.
    references (`list` of `int`): Ground truth labels.
    labels (`list` of `int`): The set of labels to include when `average` is not set to `\'binary\'`, and the order of the labels if `average` is `None`. Labels present in the data can be excluded, for example to calculate a multiclass average ignoring a majority negative class. Labels not present in the data will result in 0 components in a macro average. For multilabel targets, labels are column indices. By default, all labels in `predictions` and `references` are used in sorted order. Defaults to None.
    pos_label (`int`): The class to be considered the positive class, in the case where `average` is set to `binary`. Defaults to 1.
    average (`string`): This parameter is required for multiclass/multilabel targets. If set to `None`, the scores for each class are returned. Otherwise, this determines the type of averaging performed on the data. Defaults to `\'binary\'`.

        - \'binary\': Only report results for the class specified by `pos_label`. This is applicable only if the classes found in `predictions` and `references` are binary.
        - \'micro\': Calculate metrics globally by counting the total true positives, false negatives and false positives.
        - \'macro\': Calculate metrics for each label, and find their unweighted mean. This does not take label imbalance into account.
        - \'weighted\': Calculate metrics for each label, and find their average weighted by support (the number of true instances for each label). This alters `\'macro\'` to account for label imbalance. This option can result in an F-score that is not between precision and recall.
        - \'samples\': Calculate metrics for each instance, and find their average (only meaningful for multilabel classification).
    sample_weight (`list` of `float`): Sample weights Defaults to None.

Returns:
    f1 (`float` or `array` of `float`): F1 score or list of f1 scores, depending on the value passed to `average`. Minimum possible value is 0. Maximum possible value is 1. Higher f1 scores are better.

Examples:

    Example 1-A simple binary example
        >>> f1_metric = datasets.load_metric("f1")
        >>> results = f1_metric.compute(references=[0, 1, 0, 1, 0], predictions=[0, 0, 1, 1, 0])
        >>> print(results)
        {\'f1\': 0.5}

    Example 2-The same simple binary example as in Example 1, but with `pos_label` set to `0`.
        >>> f1_metric = datasets.load_metric("f1")
        >>> results = f1_metric.compute(references=[0, 1, 0, 1, 0], predictions=[0, 0, 1, 1, 0], pos_label=0)
        >>> print(round(results[\'f1\'], 2))
        0.67

    Example 3-The same simple binary example as in Example 1, but with `sample_weight` included.
        >>> f1_metric = datasets.load_metric("f1")
        >>> results = f1_metric.compute(references=[0, 1, 0, 1, 0], predictions=[0, 0, 1, 1, 0], sample_weight=[0.9, 0.5, 3.9, 1.2, 0.3])
        >>> print(round(results[\'f1\'], 2))
        0.35

    Example 4-A multiclass example, with different values for the `average` input.
        >>> predictions = [0, 2, 1, 0, 0, 1]
        >>> references = [0, 1, 2, 0, 1, 2]
        >>> results = f1_metric.compute(predictions=predictions, references=references, average="macro")
        >>> print(round(results[\'f1\'], 2))
        0.27
        >>> results = f1_metric.compute(predictions=predictions, references=references, average="micro")
        >>> print(round(results[\'f1\'], 2))
        0.33
        >>> results = f1_metric.compute(predictions=predictions, references=references, average="weighted")
        >>> print(round(results[\'f1\'], 2))
        0.27
        >>> results = f1_metric.compute(predictions=predictions, references=references, average=None)
        >>> print(results)
        {\'f1\': array([0.8, 0. , 0. ])}
'''


A    :					List[Any] =      '''
@article{scikit-learn,
    title={Scikit-learn: Machine Learning in {P}ython},
    author={Pedregosa, F. and Varoquaux, G. and Gramfort, A. and Michel, V.
           and Thirion, B. and Grisel, O. and Blondel, M. and Prettenhofer, P.
           and Weiss, R. and Dubourg, V. and Vanderplas, J. and Passos, A. and
           Cournapeau, D. and Brucher, M. and Perrot, M. and Duchesnay, E.},
    journal={Journal of Machine Learning Research},
    volume={12},
    pages={2825--2830},
    year={2011}
}
'''


@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION   ,     _KWARGS_DESCRIPTION    )
class   A			(datasets.Metric    ):
			'''simple docstring'''




			def    a_       (			self   :    Optional[int]   )	->	List[Any]:







					"""simple docstring"""






					return datasets.MetricInfo(
					    description=_DESCRIPTION							,	citation=_CITATION							,	inputs_description=_KWARGS_DESCRIPTION							,	features=datasets.Features(
					        {
					            """predictions""": datasets.Sequence(datasets.Value("""int32"""   )   ),
					            """references""": datasets.Sequence(datasets.Value("""int32"""   )   ),
					        }
					        if self.config_name == """multilabel"""
					        else {
					            """predictions""": datasets.Value("""int32"""   ),
					            """references""": datasets.Value("""int32"""   ),
					        }   )							,	reference_urls=["""https://scikit-learn.org/stable/modules/generated/sklearn.metrics.f1_score.html"""]							,	)







			def    a_       (			self   :    Any							,	__lowerCAmelCase   :    Tuple							,	__lowerCAmelCase   :    Union[str, Any]							,	__lowerCAmelCase   :    Dict=None							,	__lowerCAmelCase   :    List[str]=1							,	__lowerCAmelCase   :    Any="binary"							,	__lowerCAmelCase   :    Optional[int]=None   )	->	List[Any]:







					"""simple docstring"""






					A__        =   fa_score(
					    __lowerCAmelCase							,	__lowerCAmelCase							,	labels=__lowerCAmelCase							,	pos_label=__lowerCAmelCase							,	average=__lowerCAmelCase							,	sample_weight=__lowerCAmelCase   )
					return {"f1": float(__lowerCAmelCase   ) if score.size == 1 else score}



