
'''simple docstring'''



import argparse
import glob
import logging
import os
import sys
import time
from collections import defaultdict
from pathlib import Path
from typing import Dict, List, Tuple

import numpy as np
import pytorch_lightning as pl
import torch
from callbacks import SeqaSeqLoggingCallback, get_checkpoint_callback, get_early_stopping_callback
from torch import nn
from torch.utils.data import DataLoader

from transformers import MBartTokenizer, TaForConditionalGeneration
from transformers.models.bart.modeling_bart import shift_tokens_right
from utils import (
    ROUGE_KEYS,
    LegacySeqaSeqDataset,
    SeqaSeqDataset,
    assert_all_frozen,
    calculate_bleu,
    calculate_rouge,
    check_output_dir,
    flatten_list,
    freeze_embeds,
    freeze_params,
    get_git_info,
    label_smoothed_nll_loss,
    lmap,
    pickle_save,
    save_git_info,
    save_json,
    use_task_specific_params,
)


# need the parent dir module
sys.path.insert(2, str(Path(__file__).resolve().parents[1]))
from lightning_base import BaseTransformer, add_generic_args, generic_train  # noqa


UpperCamelCase__      :		Union[str, Any]       							=  logging.getLogger(__name__)

class    _a				(_lowerCamelCase):





       """simple docstring"""




       SCREAMING_SNAKE_CASE      =  'summarization'
       SCREAMING_SNAKE_CASE      =  ['loss']
       SCREAMING_SNAKE_CASE      =  ROUGE_KEYS
       SCREAMING_SNAKE_CASE      =  'rouge2'






       def __init__(							self       ,							A__       ,							**A__      )    ->			Dict:
          if hparams.sortish_sampler and hparams.gpus > 1:
             _SCREAMING_SNAKE_CASE      =				False
          elif hparams.max_tokens_per_batch is not None:
             if hparams.gpus > 1:
                raise NotImplementedError("""Dynamic Batch size does not work for multi-gpu training"""      )
             if hparams.sortish_sampler:
                raise ValueError("""--sortish_sampler and --max_tokens_per_batch may not be used simultaneously"""      )

          super().__init__(A__       ,							num_labels=A__       ,							mode=self.mode       ,							**A__      )
          use_task_specific_params(self.model       ,							"""summarization"""      )
          save_git_info(self.hparams.output_dir      )
          _SCREAMING_SNAKE_CASE      =				Path(self.output_dir      ) / """metrics.json"""
          _SCREAMING_SNAKE_CASE      =				Path(self.output_dir      ) / """hparams.pkl"""
          pickle_save(self.hparams       ,							self.hparams_save_path      )
          _SCREAMING_SNAKE_CASE      =				0
          _SCREAMING_SNAKE_CASE      =				defaultdict(A__      )
          _SCREAMING_SNAKE_CASE      =				self.config.model_type
          _SCREAMING_SNAKE_CASE      =				self.config.tgt_vocab_size if self.model_type == """fsmt""" else self.config.vocab_size

          _SCREAMING_SNAKE_CASE      =				{
              "data_dir": self.hparams.data_dir,
              "max_source_length": self.hparams.max_source_length,
              "prefix": self.model.config.prefix or "",
          }
          _SCREAMING_SNAKE_CASE      =				{
              """train""": self.hparams.n_train,
              """val""": self.hparams.n_val,
              """test""": self.hparams.n_test,
          }
          _SCREAMING_SNAKE_CASE      =				{k: v if v >= 0 else None for k, v in n_observations_per_split.items()}

          _SCREAMING_SNAKE_CASE      =				{
              """train""": self.hparams.max_target_length,
              """val""": self.hparams.val_max_target_length,
              """test""": self.hparams.test_max_target_length,
          }
          assert self.target_lens["train"] <= self.target_lens["val"], F"target_lens: {self.target_lens}"
          assert self.target_lens["train"] <= self.target_lens["test"], F"target_lens: {self.target_lens}"
          if self.hparams.freeze_embeds:
             freeze_embeds(self.model      )
          if self.hparams.freeze_encoder:
             freeze_params(self.model.get_encoder()      )
             assert_all_frozen(self.model.get_encoder()      )

          _SCREAMING_SNAKE_CASE      =				get_git_info()["""repo_sha"""]
          _SCREAMING_SNAKE_CASE      =				hparams.num_workers
          _SCREAMING_SNAKE_CASE      =				None  # default to config
          if self.model.config.decoder_start_token_id is None and isinstance(self.tokenizer       ,							A__      ):
             _SCREAMING_SNAKE_CASE      =				self.tokenizer.lang_code_to_id[hparams.tgt_lang]
             _SCREAMING_SNAKE_CASE      =				self.decoder_start_token_id
          _SCREAMING_SNAKE_CASE      =				(
              SeqaSeqDataset if hasattr(self.tokenizer       ,							"""prepare_seq2seq_batch"""      ) else LegacySeqaSeqDataset
          )
          _SCREAMING_SNAKE_CASE      =				False
          _SCREAMING_SNAKE_CASE      =				self.model.config.num_beams if self.hparams.eval_beams is None else self.hparams.eval_beams
          if self.hparams.eval_max_gen_length is not None:
             _SCREAMING_SNAKE_CASE      =				self.hparams.eval_max_gen_length
          else:
             _SCREAMING_SNAKE_CASE      =				self.model.config.max_length
          _SCREAMING_SNAKE_CASE      =				self.default_val_metric if self.hparams.val_metric is None else self.hparams.val_metric






       def        UpperCamelCase				(							self       ,							A__      )    ->			Dict[str, List[str]]:
          _SCREAMING_SNAKE_CASE      =				{
              k: self.tokenizer.batch_decode(v.tolist()      ) if """mask""" not in k else v.shape for k, v in batch.items()
          }
          save_json(A__       ,							Path(self.output_dir      ) / """text_batch.json"""      )
          save_json({k: v.tolist() for k, v in batch.items()}       ,							Path(self.output_dir      ) / """tok_batch.json"""      )

          _SCREAMING_SNAKE_CASE      =				True
          return readable_batch






       def        UpperCamelCase				(							self       ,							A__       ,							**A__      )    ->			List[Any]:
          return self.model(A__       ,							**A__      )






       def        UpperCamelCase				(							self       ,							A__      )    ->			Optional[Any]:
          _SCREAMING_SNAKE_CASE      =				self.tokenizer.batch_decode(
              A__       ,							skip_special_tokens=A__       ,							clean_up_tokenization_spaces=A__      )
          return lmap(str.strip       ,							A__      )






       def        UpperCamelCase				(							self       ,							A__      )    ->			Tuple:
          _SCREAMING_SNAKE_CASE      =				self.tokenizer.pad_token_id
          _SCREAMING_SNAKE_CASE ,							_SCREAMING_SNAKE_CASE      =				batch["""input_ids"""], batch["""attention_mask"""]
          _SCREAMING_SNAKE_CASE      =				batch["""labels"""]
          if isinstance(self.model       ,							A__      ):
             _SCREAMING_SNAKE_CASE      =				self.model._shift_right(A__      )
          else:
             _SCREAMING_SNAKE_CASE      =				shift_tokens_right(A__       ,							A__      )
          if not self.already_saved_batch:  # This would be slightly better if it only happened on rank zero
             _SCREAMING_SNAKE_CASE      =				decoder_input_ids
             self.save_readable_batch(A__      )

          _SCREAMING_SNAKE_CASE      =				self(A__       ,							attention_mask=A__       ,							decoder_input_ids=A__       ,							use_cache=A__      )
          _SCREAMING_SNAKE_CASE      =				outputs["""logits"""]
          if self.hparams.label_smoothing == 0:
             # Same behavior as modeling_bart.py, besides ignoring pad_token_id
             _SCREAMING_SNAKE_CASE      =				nn.CrossEntropyLoss(ignore_index=A__      )

             assert lm_logits.shape[-1] == self.vocab_size
             _SCREAMING_SNAKE_CASE      =				ce_loss_fct(lm_logits.view(-1       ,							lm_logits.shape[-1]      )       ,							tgt_ids.view(-1      )      )
          else:
             _SCREAMING_SNAKE_CASE      =				nn.functional.log_softmax(A__       ,							dim=-1      )
             _SCREAMING_SNAKE_CASE ,							_SCREAMING_SNAKE_CASE      =				label_smoothed_nll_loss(
                 A__       ,							A__       ,							self.hparams.label_smoothing       ,							ignore_index=A__      )
          return (loss,)






       @property
       def        UpperCamelCase				(							self      )    ->			int:
          return self.tokenizer.pad_token_id






       def        UpperCamelCase				(							self       ,							A__       ,							A__      )    ->			Dict:
          _SCREAMING_SNAKE_CASE      =				self._step(A__      )

          _SCREAMING_SNAKE_CASE      =				dict(zip(self.loss_names       ,							A__      )      )
          # tokens per batch
          _SCREAMING_SNAKE_CASE      =				batch["""input_ids"""].ne(self.pad      ).sum() + batch["""labels"""].ne(self.pad      ).sum()
          _SCREAMING_SNAKE_CASE      =				batch["""input_ids"""].shape[0]
          _SCREAMING_SNAKE_CASE      =				batch["""input_ids"""].eq(self.pad      ).sum()
          _SCREAMING_SNAKE_CASE      =				batch["""input_ids"""].eq(self.pad      ).float().mean()
          # TODO(SS): make a wandb summary metric for this
          return {"loss": loss_tensors[0], "log": logs}






       def        UpperCamelCase				(							self       ,							A__       ,							A__      )    ->			Dict:
          return self._generative_step(A__      )






       def        UpperCamelCase				(							self       ,							A__       ,							A__="val"      )    ->			Dict:
          self.step_count += 1
          _SCREAMING_SNAKE_CASE      =				{k: torch.stack([x[k] for x in outputs]      ).mean() for k in self.loss_names}
          _SCREAMING_SNAKE_CASE      =				losses["""loss"""]
          _SCREAMING_SNAKE_CASE      =				{
              k: np.array([x[k] for x in outputs]      ).mean() for k in self.metric_names + ["""gen_time""", """gen_len"""]
          }
          _SCREAMING_SNAKE_CASE      =				(
              generative_metrics[self.val_metric] if self.val_metric in generative_metrics else losses[self.val_metric]
          )
          _SCREAMING_SNAKE_CASE      =				torch.tensor(A__      ).type_as(A__      )
          generative_metrics.update({k: v.item() for k, v in losses.items()}      )
          losses.update(A__      )
          _SCREAMING_SNAKE_CASE      =				{F"{prefix}_avg_{k}": x for k, x in losses.items()}
          _SCREAMING_SNAKE_CASE      =				self.step_count
          self.metrics[prefix].append(A__      )  # callback writes this to self.metrics_save_path
          _SCREAMING_SNAKE_CASE      =				flatten_list([x["""preds"""] for x in outputs]      )
          return {
              "log": all_metrics,
              "preds": preds,
              F"{prefix}_loss": loss,
              F"{prefix}_{self.val_metric}": metric_tensor,
          }






       def        UpperCamelCase				(							self       ,							A__       ,							A__      )    ->			Dict:
          return calculate_rouge(A__       ,							A__      )






       def        UpperCamelCase				(							self       ,							A__      )    ->			dict:
          _SCREAMING_SNAKE_CASE      =				time.time()

          # parser.add_argument('--eval_max_gen_length', type=int, default=None, help='never generate more than n tokens')
          _SCREAMING_SNAKE_CASE      =				self.model.generate(
              batch["""input_ids"""]       ,							attention_mask=batch["""attention_mask"""]       ,							use_cache=A__       ,							decoder_start_token_id=self.decoder_start_token_id       ,							num_beams=self.eval_beams       ,							max_length=self.eval_max_length       ,							)
          _SCREAMING_SNAKE_CASE      =				(time.time() - ta) / batch["""input_ids"""].shape[0]
          _SCREAMING_SNAKE_CASE      =				self.ids_to_clean_text(A__      )
          _SCREAMING_SNAKE_CASE      =				self.ids_to_clean_text(batch["""labels"""]      )
          _SCREAMING_SNAKE_CASE      =				self._step(A__      )
          _SCREAMING_SNAKE_CASE      =				dict(zip(self.loss_names       ,							A__      )      )
          _SCREAMING_SNAKE_CASE      =				self.calc_generative_metrics(A__       ,							A__      )
          _SCREAMING_SNAKE_CASE      =				np.mean(lmap(A__       ,							A__      )      )
          base_metrics.update(gen_time=A__       ,							gen_len=A__       ,							preds=A__       ,							target=A__       ,							**A__      )
          return base_metrics






       def        UpperCamelCase				(							self       ,							A__       ,							A__      )    ->			Tuple:
          return self._generative_step(A__      )






       def        UpperCamelCase				(							self       ,							A__      )    ->			Optional[int]:
          return self.validation_epoch_end(A__       ,							prefix="""test"""      )






       def        UpperCamelCase				(							self       ,							A__      )    ->			SeqaSeqDataset:
          _SCREAMING_SNAKE_CASE      =				self.n_obs[type_path]
          _SCREAMING_SNAKE_CASE      =				self.target_lens[type_path]
          _SCREAMING_SNAKE_CASE      =				self.dataset_class(
              self.tokenizer       ,							type_path=A__       ,							n_obs=A__       ,							max_target_length=A__       ,							**self.dataset_kwargs       ,							)
          return dataset






       def        UpperCamelCase				(							self       ,							A__       ,							A__       ,							A__ = False      )    ->			DataLoader:
          _SCREAMING_SNAKE_CASE      =				self.get_dataset(A__      )

          if self.hparams.sortish_sampler and type_path != "test" and type_path != "val":
             _SCREAMING_SNAKE_CASE      =				dataset.make_sortish_sampler(A__       ,							distributed=self.hparams.gpus > 1      )
             return DataLoader(
                 A__       ,							batch_size=A__       ,							collate_fn=dataset.collate_fn       ,							shuffle=A__       ,							num_workers=self.num_workers       ,							sampler=A__       ,							)

          elif self.hparams.max_tokens_per_batch is not None and type_path != "test" and type_path != "val":
             _SCREAMING_SNAKE_CASE      =				dataset.make_dynamic_sampler(
                 self.hparams.max_tokens_per_batch       ,							distributed=self.hparams.gpus > 1      )
             return DataLoader(
                 A__       ,							batch_sampler=A__       ,							collate_fn=dataset.collate_fn       ,							num_workers=self.num_workers       ,							)
          else:
             return DataLoader(
                 A__       ,							batch_size=A__       ,							collate_fn=dataset.collate_fn       ,							shuffle=A__       ,							num_workers=self.num_workers       ,							sampler=A__       ,							)






       def        UpperCamelCase				(							self      )    ->			DataLoader:
          _SCREAMING_SNAKE_CASE      =				self.get_dataloader("""train"""       ,							batch_size=self.hparams.train_batch_size       ,							shuffle=A__      )
          return dataloader






       def        UpperCamelCase				(							self      )    ->			DataLoader:
          return self.get_dataloader("""val"""       ,							batch_size=self.hparams.eval_batch_size      )






       def        UpperCamelCase				(							self      )    ->			DataLoader:
          return self.get_dataloader("""test"""       ,							batch_size=self.hparams.eval_batch_size      )






       @staticmethod
       def        UpperCamelCase				(							A__       ,							A__      )    ->			Union[str, Any]:
          BaseTransformer.add_model_specific_args(A__       ,							A__      )
          add_generic_args(A__       ,							A__      )
          parser.add_argument(
              """--max_source_length"""       ,							default=10_24       ,							type=A__       ,							help=(
                  """The maximum total input sequence length after tokenization. Sequences longer """
                  """than this will be truncated, sequences shorter will be padded."""
              )       ,							)
          parser.add_argument(
              """--max_target_length"""       ,							default=56       ,							type=A__       ,							help=(
                  """The maximum total input sequence length after tokenization. Sequences longer """
                  """than this will be truncated, sequences shorter will be padded."""
              )       ,							)
          parser.add_argument(
              """--val_max_target_length"""       ,							default=1_42       ,							type=A__       ,							help=(
                  """The maximum total input sequence length after tokenization. Sequences longer """
                  """than this will be truncated, sequences shorter will be padded."""
              )       ,							)
          parser.add_argument(
              """--test_max_target_length"""       ,							default=1_42       ,							type=A__       ,							help=(
                  """The maximum total input sequence length after tokenization. Sequences longer """
                  """than this will be truncated, sequences shorter will be padded."""
              )       ,							)
          parser.add_argument("""--freeze_encoder"""       ,							action="""store_true"""      )
          parser.add_argument("""--freeze_embeds"""       ,							action="""store_true"""      )
          parser.add_argument("""--sortish_sampler"""       ,							action="""store_true"""       ,							default=A__      )
          parser.add_argument("""--overwrite_output_dir"""       ,							action="""store_true"""       ,							default=A__      )
          parser.add_argument("""--max_tokens_per_batch"""       ,							type=A__       ,							default=A__      )
          parser.add_argument("""--logger_name"""       ,							type=A__       ,							choices=["""default""", """wandb""", """wandb_shared"""]       ,							default="""default"""      )
          parser.add_argument("""--n_train"""       ,							type=A__       ,							default=-1       ,							required=A__       ,							help="""# examples. -1 means use all."""      )
          parser.add_argument("""--n_val"""       ,							type=A__       ,							default=5_00       ,							required=A__       ,							help="""# examples. -1 means use all."""      )
          parser.add_argument("""--n_test"""       ,							type=A__       ,							default=-1       ,							required=A__       ,							help="""# examples. -1 means use all."""      )
          parser.add_argument(
              """--task"""       ,							type=A__       ,							default="""summarization"""       ,							required=A__       ,							help="""# examples. -1 means use all."""      )
          parser.add_argument("""--label_smoothing"""       ,							type=A__       ,							default=0.0       ,							required=A__      )
          parser.add_argument("""--src_lang"""       ,							type=A__       ,							default=""""""       ,							required=A__      )
          parser.add_argument("""--tgt_lang"""       ,							type=A__       ,							default=""""""       ,							required=A__      )
          parser.add_argument("""--eval_beams"""       ,							type=A__       ,							default=A__       ,							required=A__      )
          parser.add_argument(
              """--val_metric"""       ,							type=A__       ,							default=A__       ,							required=A__       ,							choices=["""bleu""", """rouge2""", """loss""", None]      )
          parser.add_argument("""--eval_max_gen_length"""       ,							type=A__       ,							default=A__       ,							help="""never generate more than n tokens"""      )
          parser.add_argument("""--save_top_k"""       ,							type=A__       ,							default=1       ,							required=A__       ,							help="""How many checkpoints to save"""      )
          parser.add_argument(
              """--early_stopping_patience"""       ,							type=A__       ,							default=-1       ,							required=A__       ,							help=(
                  """-1 means never early stop. early_stopping_patience is measured in validation checks, not epochs. So"""
                  """ val_check_interval will effect it."""
              )       ,							)
          return parser






class    _a				(_lowerCamelCase):





       """simple docstring"""




       SCREAMING_SNAKE_CASE      =  'translation'
       SCREAMING_SNAKE_CASE      =  ['loss']
       SCREAMING_SNAKE_CASE      =  ['bleu']
       SCREAMING_SNAKE_CASE      =  'bleu'






       def __init__(							self       ,							A__       ,							**A__      )    ->			Any:
          super().__init__(A__       ,							**A__      )
          _SCREAMING_SNAKE_CASE      =				hparams.src_lang
          _SCREAMING_SNAKE_CASE      =				hparams.tgt_lang






       def        UpperCamelCase				(							self       ,							A__       ,							A__      )    ->			dict:
          return calculate_bleu(A__       ,							A__      )






def    lowerCAmelCase_	(				SCREAMING_SNAKE_CASE_    ,      SCREAMING_SNAKE_CASE_=None						)     ->     SummarizationModule:




   """simple docstring"""
   Path(args.output_dir						).mkdir(exist_ok=SCREAMING_SNAKE_CASE_						)
   check_output_dir(SCREAMING_SNAKE_CASE_    ,      expected_items=3						)

   if model is None:
      if "summarization" in args.task:
         _SCREAMING_SNAKE_CASE      =				SummarizationModule(SCREAMING_SNAKE_CASE_						)
      else:
         _SCREAMING_SNAKE_CASE      =				TranslationModule(SCREAMING_SNAKE_CASE_						)
   _SCREAMING_SNAKE_CASE      =				Path(args.data_dir						).name
   if (
       args.logger_name == "default"
       or args.fast_dev_run
       or str(args.output_dir						).startswith("""/tmp"""						)
       or str(args.output_dir						).startswith("""/var"""						)
   ):
      _SCREAMING_SNAKE_CASE      =				True  # don't pollute wandb logs unnecessarily
   elif args.logger_name == "wandb":
      from pytorch_lightning.loggers import WandbLogger

      _SCREAMING_SNAKE_CASE      =				os.environ.get("""WANDB_PROJECT"""    ,      SCREAMING_SNAKE_CASE_						)
      _SCREAMING_SNAKE_CASE      =				WandbLogger(name=model.output_dir.name    ,      project=SCREAMING_SNAKE_CASE_						)

   elif args.logger_name == "wandb_shared":
      from pytorch_lightning.loggers import WandbLogger

      _SCREAMING_SNAKE_CASE      =				WandbLogger(name=model.output_dir.name    ,      project=F"hf_{dataset}"						)

   if args.early_stopping_patience >= 0:
      _SCREAMING_SNAKE_CASE      =				get_early_stopping_callback(model.val_metric    ,      args.early_stopping_patience						)
   else:
      _SCREAMING_SNAKE_CASE      =				False

   _SCREAMING_SNAKE_CASE      =				args.val_metric == """loss"""
   _SCREAMING_SNAKE_CASE      =				generic_train(
       SCREAMING_SNAKE_CASE_    ,      SCREAMING_SNAKE_CASE_    ,      logging_callback=SeqaSeqLoggingCallback()    ,      checkpoint_callback=get_checkpoint_callback(
           args.output_dir    ,      model.val_metric    ,      args.save_top_k    ,      SCREAMING_SNAKE_CASE_						)    ,      early_stopping_callback=SCREAMING_SNAKE_CASE_    ,      logger=SCREAMING_SNAKE_CASE_    ,      )
   pickle_save(model.hparams    ,      model.output_dir / """hparams.pkl"""						)
   if not args.do_predict:
      return model

   _SCREAMING_SNAKE_CASE      =				""""""
   _SCREAMING_SNAKE_CASE      =				sorted(glob.glob(os.path.join(args.output_dir    ,      """*.ckpt"""						)    ,      recursive=SCREAMING_SNAKE_CASE_						)						)
   if checkpoints:
      _SCREAMING_SNAKE_CASE      =				checkpoints[-1]
      _SCREAMING_SNAKE_CASE      =				checkpoints[-1]
   trainer.logger.log_hyperparams(model.hparams						)

   # test() without a model tests using the best checkpoint automatically
   trainer.test()
   return model


if __name__ == "__main__":
     UpperCamelCase__      :		int       							=  argparse.ArgumentParser()
     UpperCamelCase__      :		Tuple       							=  pl.Trainer.add_argparse_args(parser)
     UpperCamelCase__      :		Tuple       							=  SummarizationModule.add_model_specific_args(parser, os.getcwd())

     UpperCamelCase__      :		Optional[int]       							=  parser.parse_args()

     main(args)








'''simple docstring'''



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


UpperCamelCase__      :		Tuple       							=  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    _a				(_lowerCamelCase):





       """simple docstring"""




       def __init__(							self       ,							*A__       ,							A__=None       ,							A__=None       ,							A__=None       ,							**A__      )    ->			Optional[int]:
          super().__init__(*A__       ,							**A__      )
          _SCREAMING_SNAKE_CASE      =				eval_examples
          _SCREAMING_SNAKE_CASE      =				post_process_function
          _SCREAMING_SNAKE_CASE      =				quant_trainer_args
          _SCREAMING_SNAKE_CASE      =				1_28  # default number of calibration samples






       def        UpperCamelCase				(							self       ,							A__=None      )    ->			Union[str, Any]:
          if calib_dataset is None and self.calib_dataset is None:
             raise ValueError("""Trainer: calibration requires an calib_dataset."""      )
          _SCREAMING_SNAKE_CASE      =				calib_dataset if calib_dataset is not None else self.calib_dataset

          _SCREAMING_SNAKE_CASE      =				self._remove_unused_columns(A__       ,							description="""Calibration"""      )

          return DataLoader(
              A__       ,							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=A__       ,							)






       def        UpperCamelCase				(							self       ,							A__=None      )    ->			str:
          _SCREAMING_SNAKE_CASE      =				self.train_dataset if calib_dataset is None else calib_dataset
          _SCREAMING_SNAKE_CASE      =				self.get_calib_dataloader(A__      )

          _SCREAMING_SNAKE_CASE      =				self.model
          quant_trainer.configure_model(A__       ,							self.quant_trainer_args       ,							calib=A__      )
          model.eval()
          quant_trainer.enable_calibration(A__      )

          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(A__      ):
             # Prediction step
             _SCREAMING_SNAKE_CASE ,							_SCREAMING_SNAKE_CASE ,							_SCREAMING_SNAKE_CASE      =				self.prediction_step(A__       ,							A__       ,							prediction_loss_only=A__      )
             if (step + 1) * calib_dataloader.batch_size >= self.calib_num:
                break

          quant_trainer.finish_calibration(A__       ,							self.quant_trainer_args      )
          _SCREAMING_SNAKE_CASE      =				model






       def        UpperCamelCase				(							self       ,							A__=None       ,							A__=None       ,							A__=None       ,							A__ = "eval"      )    ->			List[Any]:
          _SCREAMING_SNAKE_CASE      =				self.eval_dataset if eval_dataset is None else eval_dataset
          _SCREAMING_SNAKE_CASE      =				self.get_eval_dataloader(A__      )
          _SCREAMING_SNAKE_CASE      =				self.eval_examples if eval_examples is None else eval_examples

          # Temporarily disable metric computation, we will do it in the loop here.
          _SCREAMING_SNAKE_CASE      =				self.compute_metrics
          _SCREAMING_SNAKE_CASE      =				None
          _SCREAMING_SNAKE_CASE      =				self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop
          try:
             _SCREAMING_SNAKE_CASE      =				eval_loop(
                 A__       ,							description="""Evaluation"""       ,							prediction_loss_only=True if compute_metrics is None else None       ,							ignore_keys=A__       ,							)
          finally:
             _SCREAMING_SNAKE_CASE      =				compute_metrics

          if self.post_process_function is not None and self.compute_metrics is not None:
             _SCREAMING_SNAKE_CASE      =				self.post_process_function(A__       ,							A__       ,							output.predictions      )
             _SCREAMING_SNAKE_CASE      =				self.compute_metrics(A__      )

             # Prefix all keys with metric_key_prefix + '_'
             for key in list(metrics.keys()      ):
                if not key.startswith(F"{metric_key_prefix}_"      ):
                   _SCREAMING_SNAKE_CASE      =				metrics.pop(A__      )

             self.log(A__      )
          else:
             _SCREAMING_SNAKE_CASE      =				{}

          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()      )

          _SCREAMING_SNAKE_CASE      =				self.callback_handler.on_evaluate(self.args       ,							self.state       ,							self.control       ,							A__      )
          return metrics






       def        UpperCamelCase				(							self       ,							A__       ,							A__       ,							A__=None       ,							A__ = "test"      )    ->			List[str]:
          _SCREAMING_SNAKE_CASE      =				self.get_test_dataloader(A__      )

          # Temporarily disable metric computation, we will do it in the loop here.
          _SCREAMING_SNAKE_CASE      =				self.compute_metrics
          _SCREAMING_SNAKE_CASE      =				None
          _SCREAMING_SNAKE_CASE      =				self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop
          try:
             _SCREAMING_SNAKE_CASE      =				eval_loop(
                 A__       ,							description="""Prediction"""       ,							prediction_loss_only=True if compute_metrics is None else None       ,							ignore_keys=A__       ,							)
          finally:
             _SCREAMING_SNAKE_CASE      =				compute_metrics

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

          _SCREAMING_SNAKE_CASE      =				self.post_process_function(A__       ,							A__       ,							output.predictions       ,							"""predict"""      )
          _SCREAMING_SNAKE_CASE      =				self.compute_metrics(A__      )

          # Prefix all keys with metric_key_prefix + '_'
          for key in list(metrics.keys()      ):
             if not key.startswith(F"{metric_key_prefix}_"      ):
                _SCREAMING_SNAKE_CASE      =				metrics.pop(A__      )

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






       def        UpperCamelCase				(							self       ,							A__="./"      )    ->			Tuple:
          _SCREAMING_SNAKE_CASE      =				self.eval_dataset
          _SCREAMING_SNAKE_CASE      =				self.get_eval_dataloader(A__      )

          _SCREAMING_SNAKE_CASE      =				next(iter(A__      )      )

          # saving device - to make it consistent
          _SCREAMING_SNAKE_CASE      =				torch.device("""cuda""" if torch.cuda.is_available() else """cpu"""      )

          # convert to tuple
          _SCREAMING_SNAKE_CASE      =				tuple(v.to(A__      ) for k, v in batch.items()      )

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

          _SCREAMING_SNAKE_CASE      =				True

          _SCREAMING_SNAKE_CASE      =				self.model.to(A__      )

          model.eval()
          model.float()

          _SCREAMING_SNAKE_CASE      =				model.module if hasattr(A__       ,							"""module"""      ) else model
          quant_trainer.configure_model(A__       ,							self.quant_trainer_args      )

          _SCREAMING_SNAKE_CASE      =				os.path.join(A__       ,							"""model.onnx"""      )
          logger.info(F"exporting model to {output_model_file}"      )

          _SCREAMING_SNAKE_CASE      =				{0: """batch_size""", 1: """seq_len"""}

          torch.onnx.export(
              A__       ,							A__       ,							A__       ,							export_params=A__       ,							opset_version=13       ,							do_constant_folding=A__       ,							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=A__       ,							)
          logger.info("""onnx export finished"""      )






