




'''simple docstring'''







from typing import Dict, List

from nltk.translate import gleu_score

import datasets
from datasets import MetricInfo


A     ='\\n@misc{wu2016googles,\n      title={Google\'s Neural Machine Translation System: Bridging the Gap between Human and Machine Translation},\n      author={Yonghui Wu and Mike Schuster and Zhifeng Chen and Quoc V. Le and Mohammad Norouzi and Wolfgang Macherey\n              and Maxim Krikun and Yuan Cao and Qin Gao and Klaus Macherey and Jeff Klingner and Apurva Shah and Melvin\n              Johnson and Xiaobing Liu and Łukasz Kaiser and Stephan Gouws and Yoshikiyo Kato and Taku Kudo and Hideto\n              Kazawa and Keith Stevens and George Kurian and Nishant Patil and Wei Wang and Cliff Young and\n              Jason Smith and Jason Riesa and Alex Rudnick and Oriol Vinyals and Greg Corrado and Macduff Hughes\n              and Jeffrey Dean},\n      year={2016},\n      eprint={1609.08144},\n      archivePrefix={arXiv},\n      primaryClass={cs.CL}\n}\n'

A     ='\\nThe BLEU score has some undesirable properties when used for single\nsentences, as it was designed to be a corpus measure. We therefore\nuse a slightly different score for our RL experiments which we call\nthe \'GLEU score\'. For the GLEU score, we record all sub-sequences of\n1, 2, 3 or 4 tokens in output and target sequence (n-grams). We then\ncompute a recall, which is the ratio of the number of matching n-grams\nto the number of total n-grams in the target (ground truth) sequence,\nand a precision, which is the ratio of the number of matching n-grams\nto the number of total n-grams in the generated output sequence. Then\nGLEU score is simply the minimum of recall and precision. This GLEU\nscore\'s range is always between 0 (no matches) and 1 (all match) and\nit is symmetrical when switching output and target. According to\nour experiments, GLEU score correlates quite well with the BLEU\nmetric on a corpus level but does not have its drawbacks for our per\nsentence reward objective.\n'

A     ='\\nComputes corpus-level Google BLEU (GLEU) score of translated segments against one or more references.\nInstead of averaging the sentence level GLEU scores (i.e. macro-average precision), Wu et al. (2016) sum up the matching\ntokens and the max of hypothesis and reference tokens for each sentence, then compute using the aggregate values.\n\nArgs:\n    predictions (list of str): list of translations to score.\n        Each translation should be tokenized into a list of tokens.\n    references (list of list of str): list of lists of references for each translation.\n        Each reference should be tokenized into a list of tokens.\n    min_len (int): The minimum order of n-gram this function should extract. Defaults to 1.\n    max_len (int): The maximum order of n-gram this function should extract. Defaults to 4.\n\nReturns:\n    \'google_bleu\': google_bleu score\n\nExamples:\n    Example 1:\n        >>> hyp1 = [\'It\', \'is\', \'a\', \'guide\', \'to\', \'action\', \'which\',\n        ...         \'ensures\', \'that\', \'the\', \'rubber\', \'duck\', \'always\',\n        ...         \'disobeys\', \'the\', \'commands\', \'of\', \'the\', \'cat\']\n        >>> ref1a = [\'It\', \'is\', \'the\', \'guiding\', \'principle\', \'which\',\n        ...          \'guarantees\', \'the\', \'rubber\', \'duck\', \'forces\', \'never\',\n        ...          \'being\', \'under\', \'the\', \'command\', \'of\', \'the\', \'cat\']\n\n        >>> hyp2 = [\'he\', \'read\', \'the\', \'book\', \'because\', \'he\', \'was\',\n        ...         \'interested\', \'in\', \'world\', \'history\']\n        >>> ref2a = [\'he\', \'was\', \'interested\', \'in\', \'world\', \'history\',\n        ...          \'because\', \'he\', \'read\', \'the\', \'book\']\n\n        >>> list_of_references = [[ref1a], [ref2a]]\n        >>> hypotheses = [hyp1, hyp2]\n        >>> google_bleu = datasets.load_metric("google_bleu")\n        >>> results = google_bleu.compute(predictions=hypotheses, references=list_of_references)\n        >>> print(round(results["google_bleu"], 2))\n        0.44\n\n    Example 2:\n        >>> hyp1 = [\'It\', \'is\', \'a\', \'guide\', \'to\', \'action\', \'which\',\n        ...         \'ensures\', \'that\', \'the\', \'rubber\', \'duck\', \'always\',\n        ...         \'disobeys\', \'the\', \'commands\', \'of\', \'the\', \'cat\']\n        >>> ref1a = [\'It\', \'is\', \'the\', \'guiding\', \'principle\', \'which\',\n        ...          \'guarantees\', \'the\', \'rubber\', \'duck\', \'forces\', \'never\',\n        ...          \'being\', \'under\', \'the\', \'command\', \'of\', \'the\', \'cat\']\n        >>> ref1b = [\'It\', \'is\', \'a\', \'guide\', \'to\', \'action\', \'that\',\n        ...          \'ensures\', \'that\', \'the\', \'rubber\', \'duck\', \'will\', \'never\',\n        ...          \'heed\', \'the\', \'cat\', \'commands\']\n        >>> ref1c = [\'It\', \'is\', \'the\', \'practical\', \'guide\', \'for\', \'the\',\n        ...          \'rubber\', \'duck\', \'army\', \'never\', \'to\', \'heed\', \'the\', \'directions\',\n        ...          \'of\', \'the\', \'cat\']\n\n        >>> hyp2 = [\'he\', \'read\', \'the\', \'book\', \'because\', \'he\', \'was\',\n        ...         \'interested\', \'in\', \'world\', \'history\']\n        >>> ref2a = [\'he\', \'was\', \'interested\', \'in\', \'world\', \'history\',\n        ...          \'because\', \'he\', \'read\', \'the\', \'book\']\n\n        >>> list_of_references = [[ref1a, ref1b, ref1c], [ref2a]]\n        >>> hypotheses = [hyp1, hyp2]\n        >>> google_bleu = datasets.load_metric("google_bleu")\n        >>> results = google_bleu.compute(predictions=hypotheses, references=list_of_references)\n        >>> print(round(results["google_bleu"], 2))\n        0.61\n\n    Example 3:\n        >>> hyp1 = [\'It\', \'is\', \'a\', \'guide\', \'to\', \'action\', \'which\',\n        ...         \'ensures\', \'that\', \'the\', \'rubber\', \'duck\', \'always\',\n        ...         \'disobeys\', \'the\', \'commands\', \'of\', \'the\', \'cat\']\n        >>> ref1a = [\'It\', \'is\', \'the\', \'guiding\', \'principle\', \'which\',\n        ...          \'guarantees\', \'the\', \'rubber\', \'duck\', \'forces\', \'never\',\n        ...          \'being\', \'under\', \'the\', \'command\', \'of\', \'the\', \'cat\']\n        >>> ref1b = [\'It\', \'is\', \'a\', \'guide\', \'to\', \'action\', \'that\',\n        ...          \'ensures\', \'that\', \'the\', \'rubber\', \'duck\', \'will\', \'never\',\n        ...          \'heed\', \'the\', \'cat\', \'commands\']\n        >>> ref1c = [\'It\', \'is\', \'the\', \'practical\', \'guide\', \'for\', \'the\',\n        ...          \'rubber\', \'duck\', \'army\', \'never\', \'to\', \'heed\', \'the\', \'directions\',\n        ...          \'of\', \'the\', \'cat\']\n\n        >>> hyp2 = [\'he\', \'read\', \'the\', \'book\', \'because\', \'he\', \'was\',\n        ...         \'interested\', \'in\', \'world\', \'history\']\n        >>> ref2a = [\'he\', \'was\', \'interested\', \'in\', \'world\', \'history\',\n        ...          \'because\', \'he\', \'read\', \'the\', \'book\']\n\n        >>> list_of_references = [[ref1a, ref1b, ref1c], [ref2a]]\n        >>> hypotheses = [hyp1, hyp2]\n        >>> google_bleu = datasets.load_metric("google_bleu")\n        >>> results = google_bleu.compute(predictions=hypotheses, references=list_of_references, min_len=2)\n        >>> print(round(results["google_bleu"], 2))\n        0.53\n\n    Example 4:\n        >>> hyp1 = [\'It\', \'is\', \'a\', \'guide\', \'to\', \'action\', \'which\',\n        ...         \'ensures\', \'that\', \'the\', \'rubber\', \'duck\', \'always\',\n        ...         \'disobeys\', \'the\', \'commands\', \'of\', \'the\', \'cat\']\n        >>> ref1a = [\'It\', \'is\', \'the\', \'guiding\', \'principle\', \'which\',\n        ...          \'guarantees\', \'the\', \'rubber\', \'duck\', \'forces\', \'never\',\n        ...          \'being\', \'under\', \'the\', \'command\', \'of\', \'the\', \'cat\']\n        >>> ref1b = [\'It\', \'is\', \'a\', \'guide\', \'to\', \'action\', \'that\',\n        ...          \'ensures\', \'that\', \'the\', \'rubber\', \'duck\', \'will\', \'never\',\n        ...          \'heed\', \'the\', \'cat\', \'commands\']\n        >>> ref1c = [\'It\', \'is\', \'the\', \'practical\', \'guide\', \'for\', \'the\',\n        ...          \'rubber\', \'duck\', \'army\', \'never\', \'to\', \'heed\', \'the\', \'directions\',\n        ...          \'of\', \'the\', \'cat\']\n\n        >>> hyp2 = [\'he\', \'read\', \'the\', \'book\', \'because\', \'he\', \'was\',\n        ...         \'interested\', \'in\', \'world\', \'history\']\n        >>> ref2a = [\'he\', \'was\', \'interested\', \'in\', \'world\', \'history\',\n        ...          \'because\', \'he\', \'read\', \'the\', \'book\']\n\n        >>> list_of_references = [[ref1a, ref1b, ref1c], [ref2a]]\n        >>> hypotheses = [hyp1, hyp2]\n        >>> google_bleu = datasets.load_metric("google_bleu")\n        >>> results = google_bleu.compute(predictions=hypotheses,references=list_of_references, min_len=2, max_len=6)\n        >>> print(round(results["google_bleu"], 2))\n        0.4\n'


@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION							,							_KWARGS_DESCRIPTION )
class 			_a  (	datasets.Metric ):
       def     A      (	self						:	Optional[Any]				):



           '''simple docstring'''

           return datasets.MetricInfo(
               description=_DESCRIPTION   ,				citation=_CITATION   ,				inputs_description=_KWARGS_DESCRIPTION   ,				features=datasets.Features(
                   {
                       '''predictions''': datasets.Sequence(datasets.Value('''string'''   ,				id='''token'''				)   ,				id='''sequence'''				),
                       '''references''': datasets.Sequence(
                           datasets.Sequence(datasets.Value('''string'''   ,				id='''token'''				)   ,				id='''sequence'''				)   ,				id='''references'''				),
                   }				)   ,				)







       def     A      (	self						:	List[Any]   ,				lowercase						:	List[List[List[str]]]   ,				lowercase						:	List[List[str]]   ,				lowercase						:	int = 1   ,				lowercase						:	int = 4   ,				):



           '''simple docstring'''

           return {
               "google_bleu": gleu_score.corpus_gleu(
                   list_of_references=lowercase   ,				hypotheses=lowercase   ,				min_len=lowercase   ,				max_len=lowercase				)
           }










'''simple docstring'''







import logging
import os
from dataclasses import dataclass, field
from typing import Dict, Optional

import numpy as np
from utils_multiple_choice import MultipleChoiceDataset, Split, processors

import transformers
from transformers import (
    AutoConfig,
    AutoModelForMultipleChoice,
    AutoTokenizer,
    DataCollatorWithPadding,
    EvalPrediction,
    HfArgumentParser,
    Trainer,
    TrainingArguments,
    set_seed,
)
from transformers.trainer_utils import is_main_process


A     =logging.getLogger(__name__)





def 						snake_case_							(_a	:							Dict    ,   _a	:							Union[str, Any]     ):
    return (preds == labels).mean()


@dataclass
class 			_a  :
       __a				:     str   				=					field(
           metadata={"""help""": """Path to pretrained model or model identifier from huggingface.co/models"""} )
       __a				:     Optional[str]   				=					field(
           default=__a							,							metadata={"""help""": """Pretrained config name or path if not the same as model_name"""} )
       __a				:     Optional[str]   				=					field(
           default=__a							,							metadata={"""help""": """Pretrained tokenizer name or path if not the same as model_name"""} )
       __a				:     Optional[str]   				=					field(
           default=__a							,							metadata={"""help""": """Where do you want to store the pretrained models downloaded from huggingface.co"""}							,							)






@dataclass
class 			_a  :
       __a				:     str   				=					field(metadata={"""help""": """The name of the task to train on: """ + """, """.join(processors.keys() )} )
       __a				:     str   				=					field(metadata={"""help""": """Should contain the data files for the task."""} )
       __a				:     int   				=					field(
           default=128							,							metadata={
               """help""": (
                   """The maximum total input sequence length after tokenization. Sequences longer """
                   """than this will be truncated, sequences shorter will be padded."""
               )
           }							,							)
       __a				:     bool   				=					field(
           default=__a							,							metadata={"""help""": """Overwrite the cached training and evaluation sets"""} )






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.

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

    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     )

    try:
        UpperCAmelCase			       =		processors[data_args.task_name]()
        UpperCAmelCase			       =		processor.get_labels()
        UpperCAmelCase			       =		len(_a     )
    except KeyError:
        raise ValueError('''Task not found: %s''' % (data_args.task_name)     )

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

    UpperCAmelCase			       =		AutoConfig.from_pretrained(
        model_args.config_name if model_args.config_name else model_args.model_name_or_path    ,   num_labels=_a    ,   finetuning_task=data_args.task_name    ,   cache_dir=model_args.cache_dir    ,   )
    UpperCAmelCase			       =		AutoTokenizer.from_pretrained(
        model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path    ,   cache_dir=model_args.cache_dir    ,   )
    UpperCAmelCase			       =		AutoModelForMultipleChoice.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    ,   )

    # Get datasets
    UpperCAmelCase			       =		(
        MultipleChoiceDataset(
            data_dir=data_args.data_dir    ,   tokenizer=_a    ,   task=data_args.task_name    ,   max_seq_length=data_args.max_seq_length    ,   overwrite_cache=data_args.overwrite_cache    ,   mode=Split.train    ,   )
        if training_args.do_train
        else None
    )
    UpperCAmelCase			       =		(
        MultipleChoiceDataset(
            data_dir=data_args.data_dir    ,   tokenizer=_a    ,   task=data_args.task_name    ,   max_seq_length=data_args.max_seq_length    ,   overwrite_cache=data_args.overwrite_cache    ,   mode=Split.dev    ,   )
        if training_args.do_eval
        else None
    )

    def compute_metrics(_a	:							EvalPrediction     ) -> Dict:
        UpperCAmelCase			       =		np.argmax(p.predictions    ,   axis=1     )
        return {"acc": simple_accuracy(_a    ,   p.label_ids     )}

    # Data collator
    UpperCAmelCase			       =		DataCollatorWithPadding(_a    ,   pad_to_multiple_of=8     ) if training_args.fpaa else None

    # Initialize our Trainer
    UpperCAmelCase			       =		Trainer(
        model=_a    ,   args=_a    ,   train_dataset=_a    ,   eval_dataset=_a    ,   compute_metrics=_a    ,   data_collator=_a    ,   )

    # Training
    if training_args.do_train:
        trainer.train(
            model_path=model_args.model_name_or_path if os.path.isdir(model_args.model_name_or_path     ) else None     )
        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			       =		os.path.join(training_args.output_dir    ,   '''eval_results.txt'''     )
        if trainer.is_world_master():
            with open(_a    ,   '''w'''     ) as writer:
                logger.info('''***** Eval results *****'''     )
                for key, value in result.items():
                    logger.info('''  %s = %s'''    ,   _a    ,   _a     )
                    writer.write('''%s = %s\n''' % (key, value)     )

                results.update(_a     )

    return results





def 						snake_case_							(_a	:							Optional[int]     ):
    # For xla_spawn (TPUs)
    main()


if __name__ == "__main__":
   main()




