






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


SCREAMING_SNAKE_CASE__   :      Tuple				=		logging.getLogger(__name__)
class     lowerCamelCase_					(   lowerCamelCase			):
				a__       							=	'''summarization'''
				a__       							=	['''loss''']
				a__       							=	ROUGE_KEYS
				a__       							=	'''rouge2'''







				def __init__(    self							,       __lowerCAmelCase							,       **__lowerCAmelCase  ):
								"""simple docstring"""
								if hparams.sortish_sampler and hparams.gpus > 1:
												__magic_name__		:Dict   =   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__(__lowerCAmelCase							,       num_labels=__lowerCAmelCase							,       mode=self.mode							,       **__lowerCAmelCase  )
								use_task_specific_params(self.model							,       '''summarization'''  )
								save_git_info(self.hparams.output_dir  )
								__magic_name__		:Optional[int]   =   Path(self.output_dir  ) / '''metrics.json'''
								__magic_name__		:List[str]   =   Path(self.output_dir  ) / '''hparams.pkl'''
								pickle_save(self.hparams							,       self.hparams_save_path  )
								__magic_name__		:Optional[int]   =   0
								__magic_name__		:List[Any]   =   defaultdict(__lowerCAmelCase  )
								__magic_name__		:int   =   self.config.model_type
								__magic_name__		:Union[str, Any]   =   self.config.tgt_vocab_size if self.model_type == '''fsmt''' else self.config.vocab_size

								__magic_name__		:dict   =   {
								    "data_dir": self.hparams.data_dir,
								    "max_source_length": self.hparams.max_source_length,
								    "prefix": self.model.config.prefix or "",
								}
								__magic_name__		:List[Any]   =   {
								    '''train''': self.hparams.n_train,
								    '''val''': self.hparams.n_val,
								    '''test''': self.hparams.n_test,
								}
								__magic_name__		:Union[str, Any]   =   {k: v if v >= 0 else None for k, v in n_observations_per_split.items()}

								__magic_name__		:Optional[Any]   =   {
								    '''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()  )

								__magic_name__		:Tuple   =   get_git_info()['''repo_sha''']
								__magic_name__		:Any   =   hparams.num_workers
								__magic_name__		:List[str]   =   None  # default to config
								if self.model.config.decoder_start_token_id is None and isinstance(self.tokenizer							,       __lowerCAmelCase  ):
												__magic_name__		:Tuple   =   self.tokenizer.lang_code_to_id[hparams.tgt_lang]
												__magic_name__		:Union[str, Any]   =   self.decoder_start_token_id
								__magic_name__		:Any   =   (
								    SeqaSeqDataset if hasattr(self.tokenizer							,       '''prepare_seq2seq_batch'''  ) else LegacySeqaSeqDataset
								)
								__magic_name__		:List[str]   =   False
								__magic_name__		:List[Any]   =   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:
												__magic_name__		:Tuple   =   self.hparams.eval_max_gen_length
								else:
												__magic_name__		:Union[str, Any]   =   self.model.config.max_length
								__magic_name__		:List[str]   =   self.default_val_metric if self.hparams.val_metric is None else self.hparams.val_metric







				def       A						(    self							,       __lowerCAmelCase  ):
								"""simple docstring"""
								__magic_name__		:Tuple   =   {
								    k: self.tokenizer.batch_decode(v.tolist()  ) if '''mask''' not in k else v.shape for k, v in batch.items()
								}
								save_json(__lowerCAmelCase							,       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'''  )

								__magic_name__		:Tuple   =   True
								return readable_batch







				def       A						(    self							,       __lowerCAmelCase							,       **__lowerCAmelCase  ):
								"""simple docstring"""
								return self.model(__lowerCAmelCase							,       **__lowerCAmelCase  )







				def       A						(    self							,       __lowerCAmelCase  ):
								"""simple docstring"""
								__magic_name__		:str   =   self.tokenizer.batch_decode(
								    __lowerCAmelCase							,       skip_special_tokens=__lowerCAmelCase							,       clean_up_tokenization_spaces=__lowerCAmelCase  )
								return lmap(str.strip							,       __lowerCAmelCase  )







				def       A						(    self							,       __lowerCAmelCase  ):
								"""simple docstring"""
								__magic_name__		:Optional[Any]   =   self.tokenizer.pad_token_id
								__magic_name__  ,					__magic_name__		:Optional[int]   =   batch['''input_ids'''], batch['''attention_mask''']
								__magic_name__		:Dict   =   batch['''labels''']
								if isinstance(self.model							,       __lowerCAmelCase  ):
												__magic_name__		:List[str]   =   self.model._shift_right(__lowerCAmelCase  )
								else:
												__magic_name__		:Optional[Any]   =   shift_tokens_right(__lowerCAmelCase							,       __lowerCAmelCase  )
								if not self.already_saved_batch:  # This would be slightly better if it only happened on rank zero
												__magic_name__		:List[str]   =   decoder_input_ids
												self.save_readable_batch(__lowerCAmelCase  )

								__magic_name__		:List[Any]   =   self(__lowerCAmelCase							,       attention_mask=__lowerCAmelCase							,       decoder_input_ids=__lowerCAmelCase							,       use_cache=__lowerCAmelCase  )
								__magic_name__		:int   =   outputs['''logits''']
								if self.hparams.label_smoothing == 0:
												# Same behavior as modeling_bart.py, besides ignoring pad_token_id
												__magic_name__		:Union[str, Any]   =   nn.CrossEntropyLoss(ignore_index=__lowerCAmelCase  )

												assert lm_logits.shape[-1] == self.vocab_size
												__magic_name__		:Union[str, Any]   =   ce_loss_fct(lm_logits.view(-1							,       lm_logits.shape[-1]  )							,       tgt_ids.view(-1  )  )
								else:
												__magic_name__		:List[Any]   =   nn.functional.log_softmax(__lowerCAmelCase							,       dim=-1  )
												__magic_name__  ,					__magic_name__		:Tuple   =   label_smoothed_nll_loss(
												    __lowerCAmelCase							,       __lowerCAmelCase							,       self.hparams.label_smoothing							,       ignore_index=__lowerCAmelCase  )
								return (loss,)







				@property
				def       A						(    self  ):
								"""simple docstring"""
								return self.tokenizer.pad_token_id







				def       A						(    self							,       __lowerCAmelCase							,       __lowerCAmelCase  ):
								"""simple docstring"""
								__magic_name__		:int   =   self._step(__lowerCAmelCase  )

								__magic_name__		:Any   =   dict(zip(self.loss_names							,       __lowerCAmelCase  )  )
								# tokens per batch
								__magic_name__		:Dict   =   batch['''input_ids'''].ne(self.pad  ).sum() + batch['''labels'''].ne(self.pad  ).sum()
								__magic_name__		:List[Any]   =   batch['''input_ids'''].shape[0]
								__magic_name__		:List[str]   =   batch['''input_ids'''].eq(self.pad  ).sum()
								__magic_name__		:str   =   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       A						(    self							,       __lowerCAmelCase							,       __lowerCAmelCase  ):
								"""simple docstring"""
								return self._generative_step(__lowerCAmelCase  )







				def       A						(    self							,       __lowerCAmelCase							,       __lowerCAmelCase="val"  ):
								"""simple docstring"""
								self.step_count += 1
								__magic_name__		:Dict   =   {k: torch.stack([x[k] for x in outputs]  ).mean() for k in self.loss_names}
								__magic_name__		:Dict   =   losses['''loss''']
								__magic_name__		:Any   =   {
								    k: np.array([x[k] for x in outputs]  ).mean() for k in self.metric_names + ['''gen_time''', '''gen_len''']
								}
								__magic_name__		:Tuple   =   (
								    generative_metrics[self.val_metric] if self.val_metric in generative_metrics else losses[self.val_metric]
								)
								__magic_name__		:torch.FloatTensor   =   torch.tensor(__lowerCAmelCase  ).type_as(__lowerCAmelCase  )
								generative_metrics.update({k: v.item() for k, v in losses.items()}  )
								losses.update(__lowerCAmelCase  )
								__magic_name__		:Optional[int]   =   {F'''{prefix}_avg_{k}''': x for k, x in losses.items()}
								__magic_name__		:Tuple   =   self.step_count
								self.metrics[prefix].append(__lowerCAmelCase  )  # callback writes this to self.metrics_save_path
								__magic_name__		:Dict   =   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       A						(    self							,       __lowerCAmelCase							,       __lowerCAmelCase  ):
								"""simple docstring"""
								return calculate_rouge(__lowerCAmelCase							,       __lowerCAmelCase  )







				def       A						(    self							,       __lowerCAmelCase  ):
								"""simple docstring"""
								__magic_name__		:Optional[int]   =   time.time()

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







				def       A						(    self							,       __lowerCAmelCase							,       __lowerCAmelCase  ):
								"""simple docstring"""
								return self._generative_step(__lowerCAmelCase  )







				def       A						(    self							,       __lowerCAmelCase  ):
								"""simple docstring"""
								return self.validation_epoch_end(__lowerCAmelCase							,       prefix='''test'''  )







				def       A						(    self							,       __lowerCAmelCase  ):
								"""simple docstring"""
								__magic_name__		:Optional[Any]   =   self.n_obs[type_path]
								__magic_name__		:Optional[int]   =   self.target_lens[type_path]
								__magic_name__		:List[Any]   =   self.dataset_class(
								    self.tokenizer							,       type_path=__lowerCAmelCase							,       n_obs=__lowerCAmelCase							,       max_target_length=__lowerCAmelCase							,       **self.dataset_kwargs							,       )
								return dataset







				def       A						(    self							,       __lowerCAmelCase							,       __lowerCAmelCase							,       __lowerCAmelCase = False  ):
								"""simple docstring"""
								__magic_name__		:Optional[Any]   =   self.get_dataset(__lowerCAmelCase  )

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

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







				def       A						(    self  ):
								"""simple docstring"""
								__magic_name__		:int   =   self.get_dataloader('''train'''							,       batch_size=self.hparams.train_batch_size							,       shuffle=__lowerCAmelCase  )
								return dataloader







				def       A						(    self  ):
								"""simple docstring"""
								return self.get_dataloader('''val'''							,       batch_size=self.hparams.eval_batch_size  )







				def       A						(    self  ):
								"""simple docstring"""
								return self.get_dataloader('''test'''							,       batch_size=self.hparams.eval_batch_size  )







				@staticmethod
				def       A						(    __lowerCAmelCase							,       __lowerCAmelCase  ):
								"""simple docstring"""
								BaseTransformer.add_model_specific_args(__lowerCAmelCase							,       __lowerCAmelCase  )
								add_generic_args(__lowerCAmelCase							,       __lowerCAmelCase  )
								parser.add_argument(
								    '''--max_source_length'''							,       default=1_0_2_4							,       type=__lowerCAmelCase							,       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=5_6							,       type=__lowerCAmelCase							,       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_4_2							,       type=__lowerCAmelCase							,       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_4_2							,       type=__lowerCAmelCase							,       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=__lowerCAmelCase  )
								parser.add_argument('''--overwrite_output_dir'''							,       action='''store_true'''							,       default=__lowerCAmelCase  )
								parser.add_argument('''--max_tokens_per_batch'''							,       type=__lowerCAmelCase							,       default=__lowerCAmelCase  )
								parser.add_argument('''--logger_name'''							,       type=__lowerCAmelCase							,       choices=['''default''', '''wandb''', '''wandb_shared''']							,       default='''default'''  )
								parser.add_argument('''--n_train'''							,       type=__lowerCAmelCase							,       default=-1							,       required=__lowerCAmelCase							,       help='''# examples. -1 means use all.'''  )
								parser.add_argument('''--n_val'''							,       type=__lowerCAmelCase							,       default=5_0_0							,       required=__lowerCAmelCase							,       help='''# examples. -1 means use all.'''  )
								parser.add_argument('''--n_test'''							,       type=__lowerCAmelCase							,       default=-1							,       required=__lowerCAmelCase							,       help='''# examples. -1 means use all.'''  )
								parser.add_argument(
								    '''--task'''							,       type=__lowerCAmelCase							,       default='''summarization'''							,       required=__lowerCAmelCase							,       help='''# examples. -1 means use all.'''  )
								parser.add_argument('''--label_smoothing'''							,       type=__lowerCAmelCase							,       default=0.0							,       required=__lowerCAmelCase  )
								parser.add_argument('''--src_lang'''							,       type=__lowerCAmelCase							,       default=''''''							,       required=__lowerCAmelCase  )
								parser.add_argument('''--tgt_lang'''							,       type=__lowerCAmelCase							,       default=''''''							,       required=__lowerCAmelCase  )
								parser.add_argument('''--eval_beams'''							,       type=__lowerCAmelCase							,       default=__lowerCAmelCase							,       required=__lowerCAmelCase  )
								parser.add_argument(
								    '''--val_metric'''							,       type=__lowerCAmelCase							,       default=__lowerCAmelCase							,       required=__lowerCAmelCase							,       choices=['''bleu''', '''rouge2''', '''loss''', None]  )
								parser.add_argument('''--eval_max_gen_length'''							,       type=__lowerCAmelCase							,       default=__lowerCAmelCase							,       help='''never generate more than n tokens'''  )
								parser.add_argument('''--save_top_k'''							,       type=__lowerCAmelCase							,       default=1							,       required=__lowerCAmelCase							,       help='''How many checkpoints to save'''  )
								parser.add_argument(
								    '''--early_stopping_patience'''							,       type=__lowerCAmelCase							,       default=-1							,       required=__lowerCAmelCase							,       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     lowerCamelCase_					(   lowerCamelCase			):
				a__       							=	'''translation'''
				a__       							=	['''loss''']
				a__       							=	['''bleu''']
				a__       							=	'''bleu'''







				def __init__(    self							,       __lowerCAmelCase							,       **__lowerCAmelCase  ):
								"""simple docstring"""
								super().__init__(__lowerCAmelCase							,       **__lowerCAmelCase  )
								__magic_name__		:Any   =   hparams.src_lang
								__magic_name__		:Union[str, Any]   =   hparams.tgt_lang







				def       A						(    self							,       __lowerCAmelCase							,       __lowerCAmelCase  ):
								"""simple docstring"""
								return calculate_bleu(__lowerCAmelCase							,       __lowerCAmelCase  )







def   __lowercase       (			snake_case,	snake_case=None			):







				"""simple docstring"""






				Path(args.output_dir			).mkdir(exist_ok=snake_case			)
				check_output_dir(snake_case,	expected_items=3			)

				if model is None:
								if "summarization" in args.task:
												__magic_name__		:SummarizationModule   =   SummarizationModule(snake_case			)
								else:
												__magic_name__		:SummarizationModule   =   TranslationModule(snake_case			)
				__magic_name__		:Dict   =   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'''			)
				):
								__magic_name__		:Optional[int]   =   True  # don't pollute wandb logs unnecessarily
				elif args.logger_name == "wandb":
								from pytorch_lightning.loggers import WandbLogger

								__magic_name__		:List[str]   =   os.environ.get('''WANDB_PROJECT''',	snake_case			)
								__magic_name__		:Tuple   =   WandbLogger(name=model.output_dir.name,	project=snake_case			)

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

								__magic_name__		:Optional[Any]   =   WandbLogger(name=model.output_dir.name,	project=f'''hf_{dataset}'''			)

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

				__magic_name__		:Dict   =   args.val_metric == '''loss'''
				__magic_name__		:pl.Trainer   =   generic_train(
				    snake_case,	snake_case,	logging_callback=SeqaSeqLoggingCallback(),	checkpoint_callback=get_checkpoint_callback(
				        args.output_dir,	model.val_metric,	args.save_top_k,	snake_case			),	early_stopping_callback=snake_case,	logger=snake_case,	)
				pickle_save(model.hparams,	model.output_dir / '''hparams.pkl'''			)
				if not args.do_predict:
								return model

				__magic_name__		:Union[str, Any]   =   ''''''
				__magic_name__		:Tuple   =   sorted(glob.glob(os.path.join(args.output_dir,	'''*.ckpt'''			),	recursive=snake_case			)			)
				if checkpoints:
								__magic_name__		:Dict   =   checkpoints[-1]
								__magic_name__		:Any   =   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__":
					SCREAMING_SNAKE_CASE__   :      Union[str, Any]				=		argparse.ArgumentParser()
					SCREAMING_SNAKE_CASE__   :      Optional[Any]				=		pl.Trainer.add_argparse_args(parser)
					SCREAMING_SNAKE_CASE__   :      Optional[int]				=		SummarizationModule.add_model_specific_args(parser, os.getcwd())

					SCREAMING_SNAKE_CASE__   :      Union[str, Any]				=		parser.parse_args()

					main(args)














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






