

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


lowerCAmelCase__       = logging.getLogger(__name__)


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






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






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

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

 UpperCAmelCase							    =						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							    =						field(
     default=UpperCamelCase_	,						metadata={"""help""": """Overwrite the cached training and evaluation sets"""}    )

def      _lowerCAmelCase(	__A   ,       __A   ,       __A = False   ,       __A = None   ,       ):
  def _dataset(__A   ,       __A=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=snake_case_   ,       file_path=snake_case_   ,       block_size=args.block_size   ,       ref_path=snake_case_   ,       )

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

  if evaluate:
    return _dataset(args.eval_data_file   ,       args.eval_ref_file			)
  elif args.train_data_files:
    return ConcatDataset([_dataset(snake_case_			) 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.

  UpperCAmelCase					      =  HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments)			)
  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"   ,       snake_case_			)

  # 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=snake_case_   ,       cache_dir=model_args.cache_dir   ,       )
  else:
    logger.info("Training new model from scratch"			)
    UpperCAmelCase					      =  AutoModelWithLMHead.from_config(snake_case_			)

  model.resize_token_embeddings(len(snake_case_			)			)

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

    # Initialize our Trainer
  UpperCAmelCase					      =  Trainer(
      model=snake_case_   ,       args=snake_case_   ,       data_collator=snake_case_   ,       train_dataset=snake_case_   ,       eval_dataset=snake_case_   ,       prediction_loss_only=snake_case_   ,       )

  # 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=snake_case_			)
    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(snake_case_   ,       "w"			) as writer:
        logger.info("***** Eval results *****"			)
        for key in sorted(result.keys()			):
          logger.info("  %s = %s"   ,       snake_case_   ,       str(result[key]			)			)
          writer.write("%s = %s\n" % (key, str(result[key]			))			)

    results.update(snake_case_			)

  return results
def      _lowerCAmelCase(	__A			):
  # For xla_spawn (TPUs)
  main()


if __name__ == "__main__":
      main()






import numpy as np
from nltk.translate import meteor_score

import datasets
from datasets.config import importlib_metadata, version


lowerCAmelCase__       = version.parse(importlib_metadata.version("nltk"))
if NLTK_VERSION >= version.Version("3.6.4"):
      from nltk import word_tokenize


lowerCAmelCase__       = "\\n@inproceedings{banarjee2005,\n  title     = {{METEOR}: An Automatic Metric for {MT} Evaluation with Improved Correlation with Human Judgments},\n  author    = {Banerjee, Satanjeev  and Lavie, Alon},\n  booktitle = {Proceedings of the {ACL} Workshop on Intrinsic and Extrinsic Evaluation Measures for Machine Translation and/or Summarization},\n  month     = jun,\n  year      = {2005},\n  address   = {Ann Arbor, Michigan},\n  publisher = {Association for Computational Linguistics},\n  url       = {https://www.aclweb.org/anthology/W05-0909},\n  pages     = {65--72},\n}\n"

lowerCAmelCase__       = "\\nMETEOR, an automatic metric for machine translation evaluation\nthat is based on a generalized concept of unigram matching between the\nmachine-produced translation and human-produced reference translations.\nUnigrams can be matched based on their surface forms, stemmed forms,\nand meanings; furthermore, METEOR can be easily extended to include more\nadvanced matching strategies. Once all generalized unigram matches\nbetween the two strings have been found, METEOR computes a score for\nthis matching using a combination of unigram-precision, unigram-recall, and\na measure of fragmentation that is designed to directly capture how\nwell-ordered the matched words in the machine translation are in relation\nto the reference.\n\nMETEOR gets an R correlation value of 0.347 with human evaluation on the Arabic\ndata and 0.331 on the Chinese data. This is shown to be an improvement on\nusing simply unigram-precision, unigram-recall and their harmonic F1\ncombination.\n"

lowerCAmelCase__       = "\nComputes METEOR score of translated segments against one or more references.\nArgs:\n    predictions: list of predictions to score. Each prediction\n        should be a string with tokens separated by spaces.\n    references: list of reference for each prediction. Each\n        reference should be a string with tokens separated by spaces.\n    alpha: Parameter for controlling relative weights of precision and recall. default: 0.9\n    beta: Parameter for controlling shape of penalty as a function of fragmentation. default: 3\n    gamma: Relative weight assigned to fragmentation penalty. default: 0.5\nReturns:\n    'meteor': meteor score.\nExamples:\n\n    >>> meteor = datasets.load_metric('meteor')\n    >>> predictions = [\"It is a guide to action which ensures that the military always obeys the commands of the party\"]\n    >>> references = [\"It is a guide to action that ensures that the military will forever heed Party commands\"]\n    >>> results = meteor.compute(predictions=predictions, references=references)\n    >>> print(round(results[\"meteor\"], 4))\n    0.6944\n"






@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION	,						_KWARGS_DESCRIPTION    )
class 						__magic_name__    (       datasets.Metric    ):


 def _UpperCamelCase	(						self		: int    )    ->      str:
   return datasets.MetricInfo(
       description=_DESCRIPTION			,						citation=_CITATION			,						inputs_description=_KWARGS_DESCRIPTION			,						features=datasets.Features(
           {
               "predictions": datasets.Value("string"			,						id="sequence"    ),
               "references": datasets.Value("string"			,						id="sequence"    ),
           }    )			,						codebase_urls=["https://github.com/nltk/nltk/blob/develop/nltk/translate/meteor_score.py"]			,						reference_urls=[
           "https://www.nltk.org/api/nltk.translate.html#module-nltk.translate.meteor_score",
           "https://en.wikipedia.org/wiki/METEOR",
       ]			,						)


 def _UpperCamelCase	(						self		: Dict			,						lowerCAmelCase__		: List[Any]    )    ->      Dict:
   import nltk

   nltk.download("wordnet"    )
   if NLTK_VERSION >= version.Version("3.6.5"    ):
     nltk.download("punkt"    )
   if NLTK_VERSION >= version.Version("3.6.6"    ):
     nltk.download("omw-1.4"    )


 def _UpperCamelCase	(						self		: Union[str, Any]			,						lowerCAmelCase__		: int			,						lowerCAmelCase__		: Dict			,						lowerCAmelCase__		: Any=0.9			,						lowerCAmelCase__		: Tuple=3			,						lowerCAmelCase__		: Optional[int]=0.5    )    ->      Any:
   if NLTK_VERSION >= version.Version("3.6.5"    ):
     UpperCAmelCase					      =  [
         meteor_score.single_meteor_score(
             word_tokenize(lowerCAmelCase__    )			,						word_tokenize(lowerCAmelCase__    )			,						alpha=lowerCAmelCase__			,						beta=lowerCAmelCase__			,						gamma=lowerCAmelCase__    )
         for ref, pred in zip(lowerCAmelCase__			,						lowerCAmelCase__    )
     ]
   else:
     UpperCAmelCase					      =  [
         meteor_score.single_meteor_score(lowerCAmelCase__			,						lowerCAmelCase__			,						alpha=lowerCAmelCase__			,						beta=lowerCAmelCase__			,						gamma=lowerCAmelCase__    )
         for ref, pred in zip(lowerCAmelCase__			,						lowerCAmelCase__    )
     ]

   return {"meteor": np.mean(lowerCAmelCase__    )}



