


import logging
import os

import quant_trainer
import torch
from torch.utils.data import DataLoader

from transformers import Trainer, is_torch_tpu_available
from transformers.trainer_utils import PredictionOutput


A      :    int		=					logging.getLogger(__name__)

if is_torch_tpu_available(check_device=False):
    import torch_xla.core.xla_model as xm
    import torch_xla.debug.metrics as met







class 			_lowercase (							lowercase__):


       """simple docstring"""




       def __init__(   self							:			int					,      *__lowerCamelCase							:			Any					,      __lowerCamelCase							:			List[str]=None					,      __lowerCamelCase							:			Union[str, Any]=None					,      __lowerCamelCase							:			Dict=None					,      **__lowerCamelCase							:			List[Any]       ):


             '''simple docstring'''



             super().__init__(*__lowerCamelCase					,      **__lowerCamelCase       )
             lowerCamelCase__		:				Any    =  eval_examples
             lowerCamelCase__		:				Optional[int]    =  post_process_function
             lowerCamelCase__		:				List[Any]    =  quant_trainer_args
             lowerCamelCase__		:				Dict    =  128  # default number of calibration samples





       def 						lowerCAmelCase     (   self							:			Dict					,      __lowerCamelCase							:			Dict=None       ):


             '''simple docstring'''



             if calib_dataset is None and self.calib_dataset is None:
                   raise ValueError("Trainer: calibration requires an calib_dataset."       )
             lowerCamelCase__		:				Optional[int]    =  calib_dataset if calib_dataset is not None else self.calib_dataset

             lowerCamelCase__		:				Union[str, Any]    =  self._remove_unused_columns(__lowerCamelCase					,      description="Calibration"       )

             return DataLoader(
                 __lowerCamelCase					,      batch_size=self.args.eval_batch_size					,      collate_fn=self.data_collator					,      drop_last=self.args.dataloader_drop_last					,      num_workers=self.args.dataloader_num_workers					,      pin_memory=self.args.dataloader_pin_memory					,      shuffle=__lowerCamelCase					,      )





       def 						lowerCAmelCase     (   self							:			Dict					,      __lowerCamelCase							:			Optional[int]=None       ):


             '''simple docstring'''



             lowerCamelCase__		:				Union[str, Any]    =  self.train_dataset if calib_dataset is None else calib_dataset
             lowerCamelCase__		:				str    =  self.get_calib_dataloader(__lowerCamelCase       )

             lowerCamelCase__		:				List[str]    =  self.model
             quant_trainer.configure_model(__lowerCamelCase					,      self.quant_trainer_args					,      calib=__lowerCamelCase       )
             model.eval()
             quant_trainer.enable_calibration(__lowerCamelCase       )

             logger.info("***** Running calibration *****"       )
             logger.info(f"  Num examples = {self.calib_num}"       )
             logger.info(f"  Batch size = {calib_dataloader.batch_size}"       )

             for step, inputs in enumerate(__lowerCamelCase       ):
                   # Prediction step
                   lowerCamelCase__    ,   lowerCamelCase__    ,   lowerCamelCase__		:				Optional[int]    =  self.prediction_step(__lowerCamelCase					,      __lowerCamelCase					,      prediction_loss_only=__lowerCamelCase       )
                   if (step + 1) * calib_dataloader.batch_size >= self.calib_num:
                         break

             quant_trainer.finish_calibration(__lowerCamelCase					,      self.quant_trainer_args       )
             lowerCamelCase__		:				Optional[int]    =  model





       def 						lowerCAmelCase     (   self							:			List[str]					,      __lowerCamelCase							:			Union[str, Any]=None					,      __lowerCamelCase							:			Union[str, Any]=None					,      __lowerCamelCase							:			Any=None					,      __lowerCamelCase							:			str = "eval"       ):


             '''simple docstring'''



             lowerCamelCase__		:				Any    =  self.eval_dataset if eval_dataset is None else eval_dataset
             lowerCamelCase__		:				List[Any]    =  self.get_eval_dataloader(__lowerCamelCase       )
             lowerCamelCase__		:				Union[str, Any]    =  self.eval_examples if eval_examples is None else eval_examples

             # Temporarily disable metric computation, we will do it in the loop here.
             lowerCamelCase__		:				Union[str, Any]    =  self.compute_metrics
             lowerCamelCase__		:				List[str]    =  None
             lowerCamelCase__		:				Optional[int]    =  self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop
             try:
                   lowerCamelCase__		:				int    =  eval_loop(
                       __lowerCamelCase					,      description="Evaluation"					,      prediction_loss_only=True if compute_metrics is None else None					,      ignore_keys=__lowerCamelCase					,      )
             finally:
                   lowerCamelCase__		:				Union[str, Any]    =  compute_metrics

             if self.post_process_function is not None and self.compute_metrics is not None:
                   lowerCamelCase__		:				Union[str, Any]    =  self.post_process_function(__lowerCamelCase					,      __lowerCamelCase					,      output.predictions       )
                   lowerCamelCase__		:				str    =  self.compute_metrics(__lowerCamelCase       )

                   # Prefix all keys with metric_key_prefix + '_'
                   for key in list(metrics.keys()       ):
                         if not key.startswith(f"{metric_key_prefix}_"       ):
                               lowerCamelCase__		:				Optional[int]    =  metrics.pop(__lowerCamelCase       )

                   self.log(__lowerCamelCase       )
             else:
                   lowerCamelCase__		:				Tuple    =  {}

             if self.args.tpu_metrics_debug or self.args.debug:
                   # tpu-comment: Logging debug metrics for PyTorch/XLA (compile, execute times, ops, etc.)
                   xm.master_print(met.metrics_report()       )

             lowerCamelCase__		:				List[Any]    =  self.callback_handler.on_evaluate(self.args					,      self.state					,      self.control					,      __lowerCamelCase       )
             return metrics





       def 						lowerCAmelCase     (   self							:			Optional[int]					,      __lowerCamelCase							:			Optional[Any]					,      __lowerCamelCase							:			List[Any]					,      __lowerCamelCase							:			int=None					,      __lowerCamelCase							:			str = "test"       ):


             '''simple docstring'''



             lowerCamelCase__		:				Dict    =  self.get_test_dataloader(__lowerCamelCase       )

             # Temporarily disable metric computation, we will do it in the loop here.
             lowerCamelCase__		:				str    =  self.compute_metrics
             lowerCamelCase__		:				Optional[int]    =  None
             lowerCamelCase__		:				str    =  self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop
             try:
                   lowerCamelCase__		:				str    =  eval_loop(
                       __lowerCamelCase					,      description="Prediction"					,      prediction_loss_only=True if compute_metrics is None else None					,      ignore_keys=__lowerCamelCase					,      )
             finally:
                   lowerCamelCase__		:				List[Any]    =  compute_metrics

             if self.post_process_function is None or self.compute_metrics is None:
                   return output

             lowerCamelCase__		:				Union[str, Any]    =  self.post_process_function(__lowerCamelCase					,      __lowerCamelCase					,      output.predictions					,      "predict"       )
             lowerCamelCase__		:				Dict    =  self.compute_metrics(__lowerCamelCase       )

             # Prefix all keys with metric_key_prefix + '_'
             for key in list(metrics.keys()       ):
                   if not key.startswith(f"{metric_key_prefix}_"       ):
                         lowerCamelCase__		:				int    =  metrics.pop(__lowerCamelCase       )

             return PredictionOutput(predictions=predictions.predictions					,      label_ids=predictions.label_ids					,      metrics=__lowerCamelCase       )





       def 						lowerCAmelCase     (   self							:			Optional[int]					,      __lowerCamelCase							:			List[Any]="./"       ):


             '''simple docstring'''



             lowerCamelCase__		:				int    =  self.eval_dataset
             lowerCamelCase__		:				Optional[int]    =  self.get_eval_dataloader(__lowerCamelCase       )

             lowerCamelCase__		:				Union[str, Any]    =  next(iter(__lowerCamelCase       )       )

             # saving device - to make it consistent
             lowerCamelCase__		:				Optional[Any]    =  torch.device("cuda" if torch.cuda.is_available() else "cpu"       )

             # convert to tuple
             lowerCamelCase__		:				Any    =  tuple(v.to(__lowerCamelCase       ) for k, v in batch.items()       )

             logger.info("Converting model to be onnx compatible"       )
             from pytorch_quantization.nn import TensorQuantizer

             lowerCamelCase__		:				Tuple    =  True

             lowerCamelCase__		:				Union[str, Any]    =  self.model.to(__lowerCamelCase       )

             model.eval()
             model.float()

             lowerCamelCase__		:				int    =  model.module if hasattr(__lowerCamelCase					,      "module"       ) else model
             quant_trainer.configure_model(__lowerCamelCase					,      self.quant_trainer_args       )

             lowerCamelCase__		:				List[Any]    =  os.path.join(__lowerCamelCase					,      "model.onnx"       )
             logger.info(f"exporting model to {output_model_file}"       )

             lowerCamelCase__		:				Any    =  {0: "batch_size", 1: "seq_len"}

             torch.onnx.export(
                 __lowerCamelCase					,      __lowerCamelCase					,      __lowerCamelCase					,      export_params=__lowerCamelCase					,      opset_version=13					,      do_constant_folding=__lowerCamelCase					,      input_names=["input_ids", "attention_mask", "token_type_ids"]					,      output_names=["output_start_logits", "output_end_logits"]					,      dynamic_axes={
                     "input_ids": axes,
                     "attention_mask": axes,
                     "token_type_ids": axes,
                     "output_start_logits": axes,
                     "output_end_logits": axes,
                 }					,      verbose=__lowerCamelCase					,      )
             logger.info("onnx export finished"       )






from collections import defaultdict
from pathlib import Path

import pandas as pd
from rouge_cli import calculate_rouge_path

from utils import calculate_rouge


A      :    Optional[int]		=					[
    "Prosecutor: \"No videos were used in the crash investigation\" German papers say they saw a cell phone video of the"
    " final seconds on board Flight 9525. The Germanwings co-pilot says he had a \"previous episode of severe"
    " depression\" German airline confirms it knew of Andreas Lubitz's depression years before he took control.",
    "The Palestinian Authority officially becomes the 123rd member of the International Criminal Court. The formal"
    " accession was marked with a ceremony at The Hague, in the Netherlands. The Palestinians signed the ICC's"
    " founding Rome Statute in January. Israel and the United States opposed the Palestinians' efforts to join the"
    " body.",
    "Amnesty International releases its annual report on the death penalty. The report catalogs the use of"
    " state-sanctioned killing as a punitive measure across the globe. At least 607 people were executed around the"
    " world in 2014, compared to 778 in 2013. The U.S. remains one of the worst offenders for imposing capital"
    " punishment.",
]

A      :    List[Any]		=					[
    "Marseille prosecutor says \"so far no videos were used in the crash investigation\" despite media reports ."
    " Journalists at Bild and Paris Match are \"very confident\" the video clip is real, an editor says . Andreas Lubitz"
    " had informed his Lufthansa training school of an episode of severe depression, airline says .",
    "Membership gives the ICC jurisdiction over alleged crimes committed in Palestinian territories since last June ."
    " Israel and the United States opposed the move, which could open the door to war crimes investigations against"
    " Israelis .",
    "Amnesty's annual death penalty report catalogs encouraging signs, but setbacks in numbers of those sentenced to"
    " death . Organization claims that governments around the world are using the threat of terrorism to advance"
    " executions . The number of executions worldwide has gone down by almost 22% compared with 2013, but death"
    " sentences up by 28% .",
]

def       lowercase_		(		):

      """simple docstring"""




      lowerCamelCase__		:				Dict    =  calculate_rouge(_A    ,					_A    ,					bootstrap_aggregation=_A    ,					rouge_keys=["rouge2", "rougeL"]						)
      assert isinstance(_A    ,					_A						)
      lowerCamelCase__		:				List[Any]    =  calculate_rouge(_A    ,					_A    ,					bootstrap_aggregation=_A    ,					rouge_keys=["rouge2"]						)
      assert (
          pd.DataFrame(no_aggregation["rouge2"]						).fmeasure.mean()
          == pd.DataFrame(no_aggregation_just_ra["rouge2"]						).fmeasure.mean()
      )

def       lowercase_		(		):

      """simple docstring"""




      lowerCamelCase__		:				Any    =  "rougeLsum"
      lowerCamelCase__		:				List[str]    =  calculate_rouge(_A    ,					_A    ,					newline_sep=_A    ,					rouge_keys=[k]						)[k]
      lowerCamelCase__		:				str    =  calculate_rouge(_A    ,					_A    ,					newline_sep=_A    ,					rouge_keys=[k]						)[k]
      assert score > score_no_sep

def       lowercase_		(		):

      """simple docstring"""




      lowerCamelCase__		:				int    =  ["rouge1", "rouge2", "rougeL"]
      lowerCamelCase__		:				Union[str, Any]    =  calculate_rouge(_A    ,					_A    ,					newline_sep=_A    ,					rouge_keys=_A						)
      lowerCamelCase__		:				Any    =  calculate_rouge(_A    ,					_A    ,					newline_sep=_A    ,					rouge_keys=_A						)
      assert score_sep == score_no_sep

def       lowercase_		(		):

      """simple docstring"""




      lowerCamelCase__		:				Optional[Any]    =  [
          "Her older sister, Margot Frank, died in 1945, a month earlier than previously thought.",
          "Marseille prosecutor says \"so far no videos were used in the crash investigation\" despite media reports .",
      ]
      lowerCamelCase__		:				Tuple    =  [
          "Margot Frank, died in 1945, a month earlier than previously thought.",
          "Prosecutor: \"No videos were used in the crash investigation\" German papers say they saw a cell phone video of"
          " the final seconds on board Flight 9525.",
      ]
      assert calculate_rouge(_A    ,					_A    ,					newline_sep=_A						) == calculate_rouge(_A    ,					_A    ,					newline_sep=_A						)

def       lowercase_		(		):

      """simple docstring"""




      lowerCamelCase__		:				List[str]    =  [
          "\" \"a person who has such a video needs to immediately give it to the investigators,\" prosecutor says .<n> \"it is a very disturbing scene,\" editor-in-chief of bild online tells \"erin burnett: outfront\" "
      ]
      lowerCamelCase__		:				str    =  [
          " Marseille prosecutor says \"so far no videos were used in the crash investigation\" despite media reports . Journalists at Bild and Paris Match are \"very confident\" the video clip is real, an editor says . Andreas Lubitz had informed his Lufthansa training school of an episode of severe depression, airline says ."
      ]

      lowerCamelCase__		:				Union[str, Any]    =  calculate_rouge(_A    ,					_A    ,					rouge_keys=["rougeLsum"]    ,					newline_sep=_A						)["rougeLsum"]
      lowerCamelCase__		:				List[str]    =  calculate_rouge(_A    ,					_A    ,					rouge_keys=["rougeLsum"]						)["rougeLsum"]
      assert new_score > prev_score


def       lowercase_		(		):

      """simple docstring"""




      lowerCamelCase__		:				Tuple    =  Path("examples/seq2seq/test_data/wmt_en_ro"						)
      lowerCamelCase__		:				Any    =  calculate_rouge_path(data_dir.joinpath("test.source"						)    ,					data_dir.joinpath("test.target"						)						)
      assert isinstance(_A    ,					_A						)
      lowerCamelCase__		:				str    =  calculate_rouge_path(
          data_dir.joinpath("test.source"						)    ,					data_dir.joinpath("test.target"						)    ,					bootstrap_aggregation=_A						)
      assert isinstance(_A    ,					_A						)


