






import numpy as np
import torch
from torch.utils.data import Dataset

from utils import logger
class     lowerCamelCase_					(   lowerCamelCase			):







				def __init__(    self							,       __lowerCAmelCase							,       __lowerCAmelCase  ):
								"""simple docstring"""
								__magic_name__		:Optional[int]   =   params

								__magic_name__		:Any   =   np.array(__lowerCAmelCase  )
								__magic_name__		:Optional[Any]   =   np.array([len(__lowerCAmelCase  ) for t in data]  )

								self.check()
								self.remove_long_sequences()
								self.remove_empty_sequences()
								self.remove_unknown_sequences()
								self.check()
								self.print_statistics()







				def __getitem__(    self							,       __lowerCAmelCase  ):
								"""simple docstring"""
								return (self.token_ids[index], self.lengths[index])







				def __len__(    self  ):
								"""simple docstring"""
								return len(self.lengths  )







				def       A						(    self  ):
								"""simple docstring"""
								assert len(self.token_ids  ) == len(self.lengths  )
								assert all(self.lengths[i] == len(self.token_ids[i]  ) for i in range(len(self.lengths  )  )  )







				def       A						(    self  ):
								"""simple docstring"""
								__magic_name__		:Any   =   self.params.max_model_input_size
								__magic_name__		:int   =   self.lengths > max_len
								logger.info(F'''Splitting {sum(__lowerCAmelCase  )} too long sequences.'''  )

								def divide_chunks(__lowerCAmelCase							,       __lowerCAmelCase  ):
												return [l[i : i + n] for i in range(0							,       len(__lowerCAmelCase  )							,       __lowerCAmelCase  )]

								__magic_name__		:Optional[int]   =   []
								__magic_name__		:List[Any]   =   []
								if self.params.mlm:
												__magic_name__  ,					__magic_name__		:Optional[Any]   =   self.params.special_tok_ids['''cls_token'''], self.params.special_tok_ids['''sep_token''']
								else:
												__magic_name__  ,					__magic_name__		:Tuple   =   self.params.special_tok_ids['''bos_token'''], self.params.special_tok_ids['''eos_token''']

								for seq_, len_ in zip(self.token_ids							,       self.lengths  ):
												assert (seq_[0] == cls_id) and (seq_[-1] == sep_id), seq_
												if len_ <= max_len:
																new_tok_ids.append(seq_  )
																new_lengths.append(len_  )
												else:
																__magic_name__		:int   =   []
																for sub_s in divide_chunks(seq_							,       max_len - 2  ):
																				if sub_s[0] != cls_id:
																								__magic_name__		:List[Any]   =   np.insert(__lowerCAmelCase							,       0							,       __lowerCAmelCase  )
																				if sub_s[-1] != sep_id:
																								__magic_name__		:Union[str, Any]   =   np.insert(__lowerCAmelCase							,       len(__lowerCAmelCase  )							,       __lowerCAmelCase  )
																				assert len(__lowerCAmelCase  ) <= max_len
																				assert (sub_s[0] == cls_id) and (sub_s[-1] == sep_id), sub_s
																				sub_seqs.append(__lowerCAmelCase  )

																new_tok_ids.extend(__lowerCAmelCase  )
																new_lengths.extend([len(__lowerCAmelCase  ) for l in sub_seqs]  )

								__magic_name__		:Tuple   =   np.array(__lowerCAmelCase  )
								__magic_name__		:Optional[int]   =   np.array(__lowerCAmelCase  )







				def       A						(    self  ):
								"""simple docstring"""
								__magic_name__		:Optional[Any]   =   len(self  )
								__magic_name__		:int   =   self.lengths > 1_1
								__magic_name__		:List[str]   =   self.token_ids[indices]
								__magic_name__		:Union[str, Any]   =   self.lengths[indices]
								__magic_name__		:List[str]   =   len(self  )
								logger.info(F'''Remove {init_size - new_size} too short (<=11 tokens) sequences.'''  )







				def       A						(    self  ):
								"""simple docstring"""
								if "unk_token" not in self.params.special_tok_ids:
												return
								else:
												__magic_name__		:Tuple   =   self.params.special_tok_ids['''unk_token''']
								__magic_name__		:Dict   =   len(self  )
								__magic_name__		:Tuple   =   np.array([np.count_nonzero(a == unk_token_id  ) for a in self.token_ids]  )
								__magic_name__		:int   =   (unk_occs / self.lengths) < 0.5
								__magic_name__		:str   =   self.token_ids[indices]
								__magic_name__		:str   =   self.lengths[indices]
								__magic_name__		:Any   =   len(self  )
								logger.info(F'''Remove {init_size - new_size} sequences with a high level of unknown tokens (50%).'''  )







				def       A						(    self  ):
								"""simple docstring"""
								if not self.params.is_master:
												return
								logger.info(F'''{len(self  )} sequences'''  )
								# data_len = sum(self.lengths)
								# nb_unique_tokens = len(Counter(list(chain(*self.token_ids))))
								# logger.info(f'{data_len} tokens ({nb_unique_tokens} unique)')

								# unk_idx = self.params.special_tok_ids['unk_token']
								# nb_unknown = sum([(t==unk_idx).sum() for t in self.token_ids])
								# logger.info(f'{nb_unknown} unknown tokens (covering {100*nb_unknown/data_len:.2f}% of the data)')







				def       A						(    self							,       __lowerCAmelCase  ):
								"""simple docstring"""
								__magic_name__		:Optional[Any]   =   [t[0] for t in batch]
								__magic_name__		:List[Any]   =   [t[1] for t in batch]
								assert len(__lowerCAmelCase  ) == len(__lowerCAmelCase  )

								# Max for paddings
								__magic_name__		:Tuple   =   max(__lowerCAmelCase  )

								# Pad token ids
								if self.params.mlm:
												__magic_name__		:Any   =   self.params.special_tok_ids['''pad_token''']
								else:
												__magic_name__		:str   =   self.params.special_tok_ids['''unk_token''']
								__magic_name__		:Any   =   [list(t.astype(__lowerCAmelCase  )  ) + [pad_idx] * (max_seq_len_ - len(__lowerCAmelCase  )) for t in token_ids]
								assert len(tk_  ) == len(__lowerCAmelCase  )
								assert all(len(__lowerCAmelCase  ) == max_seq_len_ for t in tk_  )

								__magic_name__		:Optional[int]   =   torch.tensor(tk_  )  # (bs, max_seq_len_)
								__magic_name__		:Optional[int]   =   torch.tensor(__lowerCAmelCase  )  # (bs)
								return tk_t, lg_t














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






