





"""simple docstring"""


import logging
from pathlib import Path

import numpy as np
import pytorch_lightning as pl
import torch
from pytorch_lightning.callbacks import EarlyStopping, ModelCheckpoint
from pytorch_lightning.utilities import rank_zero_only
from utils_rag import save_json

def      UpperCamelCase							(SCREAMING_SNAKE_CASE     ):
						UpperCamelCase				:		Tuple				   =			filter(lambda SCREAMING_SNAKE_CASE     : p.requires_grad							,     model.parameters()     )
						UpperCamelCase				:		List[str]				   =			sum([np.prod(p.size()     ) for p in model_parameters]     )
						return params


__magic_name__       :					Tuple						=			logging.getLogger(__name__)

def      UpperCamelCase							(SCREAMING_SNAKE_CASE							,     SCREAMING_SNAKE_CASE     ):
						if metric == "rouge2":
												UpperCamelCase				:		Tuple				   =			"""{val_avg_rouge2:.4f}-{step_count}"""
						elif metric == "bleu":
												UpperCamelCase				:		int				   =			"""{val_avg_bleu:.4f}-{step_count}"""
						elif metric == "em":
												UpperCamelCase				:		Union[str, Any]				   =			"""{val_avg_em:.4f}-{step_count}"""
						elif metric == "loss":
												UpperCamelCase				:		Tuple				   =			"""{val_avg_loss:.4f}-{step_count}"""
						else:
												raise NotImplementedError(
												    f"""seq2seq callbacks only support rouge2 and bleu, got {metric}, You can make your own by adding to this"""
												    """ function."""     )

						UpperCamelCase				:		int				   =			ModelCheckpoint(
						    dirpath=SCREAMING_SNAKE_CASE							,     filename=SCREAMING_SNAKE_CASE							,     monitor=f"""val_{metric}"""							,     mode="""max"""							,     save_top_k=1							,     every_n_epochs=1							,     )

						return checkpoint_callback

def      UpperCamelCase							(SCREAMING_SNAKE_CASE							,     SCREAMING_SNAKE_CASE     ):
						return EarlyStopping(
						    monitor=f"""val_{metric}"""							,     mode="""min""" if """loss""" in metric else """max"""							,     patience=SCREAMING_SNAKE_CASE							,     verbose=SCREAMING_SNAKE_CASE							,     )






class 							lowercase__			(   pl.Callback	):

			"""simple docstring"""







			def   _a      (      self						,   _A						,   _A    ):






									'''simple docstring'''







									UpperCamelCase				:		str				   =			{f"""lr_group_{i}""": param["""lr"""] for i, param in enumerate(pl_module.trainer.optimizers[0].param_groups    )}
									pl_module.logger.log_metrics(_A    )







			@rank_zero_only
			def   _a      (      self						,   _A						,   _A						,   _A						,   _A=True    ):






									'''simple docstring'''







									logger.info(f"""***** {type_path} results at step {trainer.global_step:05d} *****"""    )
									UpperCamelCase				:		List[Any]				   =			trainer.callback_metrics
									trainer.logger.log_metrics({k: v for k, v in metrics.items() if k not in ["""log""", """progress_bar""", """preds"""]}    )
									# Log results
									UpperCamelCase				:		int				   =			Path(pl_module.hparams.output_dir    )
									if type_path == "test":
															UpperCamelCase				:		Tuple				   =			od / """test_results.txt"""
															UpperCamelCase				:		List[str]				   =			od / """test_generations.txt"""
									else:
															# this never gets hit. I prefer not to save intermediate generations, and results are in metrics.json
															# If people want this it will be easy enough to add back.
															UpperCamelCase				:		int				   =			od / f"""{type_path}_results/{trainer.global_step:05d}.txt"""
															UpperCamelCase				:		str				   =			od / f"""{type_path}_generations/{trainer.global_step:05d}.txt"""
															results_file.parent.mkdir(exist_ok=_A    )
															generations_file.parent.mkdir(exist_ok=_A    )
									with open(_A						,   """a+"""    ) as writer:
															for key in sorted(_A    ):
																					if key in ["log", "progress_bar", "preds"]:
																											continue
																					UpperCamelCase				:		int				   =			metrics[key]
																					if isinstance(_A						,   torch.Tensor    ):
																											UpperCamelCase				:		Optional[int]				   =			val.item()
																					UpperCamelCase				:		Union[str, Any]				   =			f"""{key}: {val:.6f}\n"""
																					writer.write(_A    )

									if not save_generations:
															return

									if "preds" in metrics:
															UpperCamelCase				:		int				   =			"""\n""".join(metrics["""preds"""]    )
															generations_file.open("""w+"""    ).write(_A    )







			@rank_zero_only
			def   _a      (      self						,   _A						,   _A    ):






									'''simple docstring'''







									try:
															UpperCamelCase				:		Any				   =			pl_module.model.model.num_parameters()
									except AttributeError:
															UpperCamelCase				:		Any				   =			pl_module.model.num_parameters()

									UpperCamelCase				:		Any				   =			count_trainable_parameters(_A    )
									# mp stands for million parameters
									trainer.logger.log_metrics({"""n_params""": npars, """mp""": npars / 1e6, """grad_mp""": n_trainable_pars / 1e6}    )







			@rank_zero_only
			def   _a      (      self						,   _A						,   _A    ):






									'''simple docstring'''







									save_json(pl_module.metrics						,   pl_module.metrics_save_path    )
									return self._write_logs(_A						,   _A						,   """test"""    )







			@rank_zero_only
			def   _a      (      self						,   _A						,   _A    ):






									'''simple docstring'''







									save_json(pl_module.metrics						,   pl_module.metrics_save_path    )
									# Uncommenting this will save val generations
									# return self._write_logs(trainer, pl_module, "valid")











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


SCREAMING_SNAKE_CASE__   :      List[str]				=		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     lowerCamelCase_					(   lowerCamelCase			):







				def __init__(    self							,       *__lowerCAmelCase							,       __lowerCAmelCase=None							,       __lowerCAmelCase=None							,       __lowerCAmelCase=None							,       **__lowerCAmelCase  ):
								"""simple docstring"""
								super().__init__(*__lowerCAmelCase							,       **__lowerCAmelCase  )
								__magic_name__		:Any   =   eval_examples
								__magic_name__		:str   =   post_process_function
								__magic_name__		:int   =   quant_trainer_args
								__magic_name__		:List[str]   =   1_2_8  # default number of calibration samples







				def       A						(    self							,       __lowerCAmelCase=None  ):
								"""simple docstring"""
								if calib_dataset is None and self.calib_dataset is None:
												raise ValueError('''Trainer: calibration requires an calib_dataset.'''  )
								__magic_name__		:Optional[Any]   =   calib_dataset if calib_dataset is not None else self.calib_dataset

								__magic_name__		:Optional[int]   =   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       A						(    self							,       __lowerCAmelCase=None  ):
								"""simple docstring"""
								__magic_name__		:Dict   =   self.train_dataset if calib_dataset is None else calib_dataset
								__magic_name__		:Any   =   self.get_calib_dataloader(__lowerCAmelCase  )

								__magic_name__		: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
												__magic_name__  ,					__magic_name__  ,					__magic_name__		:str   =   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  )
								__magic_name__		:Any   =   model







				def       A						(    self							,       __lowerCAmelCase=None							,       __lowerCAmelCase=None							,       __lowerCAmelCase=None							,       __lowerCAmelCase = "eval"  ):
								"""simple docstring"""
								__magic_name__		:Tuple   =   self.eval_dataset if eval_dataset is None else eval_dataset
								__magic_name__		:Optional[Any]   =   self.get_eval_dataloader(__lowerCAmelCase  )
								__magic_name__		:str   =   self.eval_examples if eval_examples is None else eval_examples

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

								if self.post_process_function is not None and self.compute_metrics is not None:
												__magic_name__		:Union[str, Any]   =   self.post_process_function(__lowerCAmelCase							,       __lowerCAmelCase							,       output.predictions  )
												__magic_name__		:int   =   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}_'''  ):
																				__magic_name__		:Dict   =   metrics.pop(__lowerCAmelCase  )

												self.log(__lowerCAmelCase  )
								else:
												__magic_name__		:List[str]   =   {}

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

								__magic_name__		:Optional[Any]   =   self.callback_handler.on_evaluate(self.args							,       self.state							,       self.control							,       __lowerCAmelCase  )
								return metrics







				def       A						(    self							,       __lowerCAmelCase							,       __lowerCAmelCase							,       __lowerCAmelCase=None							,       __lowerCAmelCase = "test"  ):
								"""simple docstring"""
								__magic_name__		:int   =   self.get_test_dataloader(__lowerCAmelCase  )

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

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

								__magic_name__		:Optional[Any]   =   self.post_process_function(__lowerCAmelCase							,       __lowerCAmelCase							,       output.predictions							,       '''predict'''  )
								__magic_name__		: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}_'''  ):
																__magic_name__		:List[str]   =   metrics.pop(__lowerCAmelCase  )

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







				def       A						(    self							,       __lowerCAmelCase="./"  ):
								"""simple docstring"""
								__magic_name__		:List[Any]   =   self.eval_dataset
								__magic_name__		:Any   =   self.get_eval_dataloader(__lowerCAmelCase  )

								__magic_name__		:int   =   next(iter(__lowerCAmelCase  )  )

								# saving device - to make it consistent
								__magic_name__		:str   =   torch.device('''cuda''' if torch.cuda.is_available() else '''cpu'''  )

								# convert to tuple
								__magic_name__		:int   =   tuple(v.to(__lowerCAmelCase  ) for k, v in batch.items()  )

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

								__magic_name__		:Any   =   True

								__magic_name__		:Optional[int]   =   self.model.to(__lowerCAmelCase  )

								model.eval()
								model.float()

								__magic_name__		:Any   =   model.module if hasattr(__lowerCAmelCase							,       '''module'''  ) else model
								quant_trainer.configure_model(__lowerCAmelCase							,       self.quant_trainer_args  )

								__magic_name__		:int   =   os.path.join(__lowerCAmelCase							,       '''model.onnx'''  )
								logger.info(F'''exporting model to {output_model_file}'''  )

								__magic_name__		:Dict   =   {0: '''batch_size''', 1: '''seq_len'''}

								torch.onnx.export(
								    __lowerCAmelCase							,       __lowerCAmelCase							,       __lowerCAmelCase							,       export_params=__lowerCAmelCase							,       opset_version=1_3							,       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'''  )






