
'''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_       :   Dict   =       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  UpperCAmelCase__						(       __snake_case ):



    def __init__(	self      :       Any,*__A      :       Optional[int],__A      :       Tuple=None,__A      :       Optional[Any]=None,__A      :       Dict=None,**__A      :       int     ):
          super().__init__(*A_,**A_     )
          _lowerCamelCase				:   Tuple								=   eval_examples
          _lowerCamelCase				:   Dict								=   post_process_function
          _lowerCamelCase				:   Union[str, Any]								=   quant_trainer_args
          _lowerCamelCase				:   Any								=   1_2_8  # default number of calibration samples



    def   lowerCamelCase_  (	self      :       List[Any],__A      :       List[str]=None     ):




          if calib_dataset is None and self.calib_dataset is None:
                raise ValueError("Trainer: calibration requires an calib_dataset."     )
          _lowerCamelCase				:   Any								=   calib_dataset if calib_dataset is not None else self.calib_dataset

          _lowerCamelCase				:   Dict								=   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   lowerCamelCase_  (	self      :       str,__A      :       Tuple=None     ):
          _lowerCamelCase				:   Any								=   self.train_dataset if calib_dataset is None else calib_dataset
          _lowerCamelCase				:   Dict								=   self.get_calib_dataloader(A_     )

          _lowerCamelCase				:   Optional[int]								=   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
                _lowerCamelCase				:   List[Any]								=   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     )
          _lowerCamelCase				:   str								=   model



    def   lowerCamelCase_  (	self      :       Optional[Any],__A      :       List[Any]=None,__A      :       Dict=None,__A      :       str=None,__A      :       List[Any] = "eval"     ):
          _lowerCamelCase				:   Optional[Any]								=   self.eval_dataset if eval_dataset is None else eval_dataset
          _lowerCamelCase				:   Any								=   self.get_eval_dataloader(A_     )
          _lowerCamelCase				:   List[Any]								=   self.eval_examples if eval_examples is None else eval_examples

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

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

                self.log(A_     )
          else:
                _lowerCamelCase				:   List[Any]								=   {}

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

          _lowerCamelCase				:   Tuple								=   self.callback_handler.on_evaluate(self.args,self.state,self.control,A_     )
          return metrics



    def   lowerCamelCase_  (	self      :       Any,__A      :       List[Any],__A      :       List[str],__A      :       List[str]=None,__A      :       List[Any] = "test"     ):
          _lowerCamelCase				:   Optional[int]								=   self.get_test_dataloader(A_     )

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

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

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

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



    def   lowerCamelCase_  (	self      :       List[Any],__A      :       Any="./"     ):
          _lowerCamelCase				:   str								=   self.eval_dataset
          _lowerCamelCase				:   Dict								=   self.get_eval_dataloader(A_     )

          _lowerCamelCase				:   List[str]								=   next(iter(A_     )     )

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

          # convert to tuple
          _lowerCamelCase				:   Union[str, Any]								=   tuple(v.to(A_     ) for k, v in batch.items()     )

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

          _lowerCamelCase				:   str								=   True

          _lowerCamelCase				:   int								=   self.model.to(A_     )

          model.eval()
          model.float()

          _lowerCamelCase				:   Tuple								=   model.module if hasattr(A_,"module"     ) else model
          quant_trainer.configure_model(A_,self.quant_trainer_args     )

          _lowerCamelCase				:   int								=   os.path.join(A_,"model.onnx"     )
          logger.info(f'exporting model to {output_model_file}'     )

          _lowerCamelCase				:   List[Any]								=   {0: "batch_size", 1: "seq_len"}

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







'''simple docstring'''






import os
import time
from dataclasses import dataclass, field
from enum import Enum
from typing import Dict, List, Optional, Union

import torch
from filelock import FileLock
from torch.utils.data import Dataset

from ...models.auto.modeling_auto import MODEL_FOR_QUESTION_ANSWERING_MAPPING
from ...tokenization_utils import PreTrainedTokenizer
from ...utils import logging
from ..processors.squad import SquadFeatures, SquadVaProcessor, SquadVaProcessor, squad_convert_examples_to_features


UpperCAmelCase_       :   Optional[Any]   =       logging.get_logger(__name__)

UpperCAmelCase_       :   Any   =       list(MODEL_FOR_QUESTION_ANSWERING_MAPPING.keys())
UpperCAmelCase_       :   str   =       tuple(conf.model_type for conf in MODEL_CONFIG_CLASSES)

@dataclass
class  UpperCAmelCase__						:
    lowerCAmelCase_				    =		field(
        default=A						,	metadata={'help': 'Model type selected in the list: ' + ', '.join(A )} )
    lowerCAmelCase_				    =		field(
        default=A						,	metadata={'help': 'The input data dir. Should contain the .json files for the SQuAD task.'} )
    lowerCAmelCase_				    =		field(
        default=128						,	metadata={
            'help': (
                'The maximum total input sequence length after tokenization. Sequences longer '
                'than this will be truncated, sequences shorter will be padded.'
            )
        }						,	)
    lowerCAmelCase_				    =		field(
        default=128						,	metadata={'help': 'When splitting up a long document into chunks, how much stride to take between chunks.'}						,	)
    lowerCAmelCase_				    =		field(
        default=64						,	metadata={
            'help': (
                'The maximum number of tokens for the question. Questions longer than this will '
                'be truncated to this length.'
            )
        }						,	)
    lowerCAmelCase_				    =		field(
        default=30						,	metadata={
            'help': (
                'The maximum length of an answer that can be generated. This is needed because the start '
                'and end predictions are not conditioned on one another.'
            )
        }						,	)
    lowerCAmelCase_				    =		field(
        default=A						,	metadata={'help': 'Overwrite the cached training and evaluation sets'} )
    lowerCAmelCase_				    =		field(
        default=A						,	metadata={'help': 'If true, the SQuAD examples contain some that do not have an answer.'} )
    lowerCAmelCase_				    =		field(
        default=0.0						,	metadata={'help': 'If null_score - best_non_null is greater than the threshold predict null.'} )
    lowerCAmelCase_				    =		field(
        default=20						,	metadata={'help': 'If null_score - best_non_null is greater than the threshold predict null.'} )
    lowerCAmelCase_				    =		field(
        default=0						,	metadata={
            'help': (
                'language id of input for language-specific xlm models (see'
                ' tokenization_xlm.PRETRAINED_INIT_CONFIGURATION)'
            )
        }						,	)
    lowerCAmelCase_				    =		field(default=1						,	metadata={'help': 'multiple threads for converting example to features'} )


class  UpperCAmelCase__						(       A ):
    lowerCAmelCase_				    =		'train'
    lowerCAmelCase_				    =		'dev'


class  UpperCAmelCase__						(       A ):
    lowerCAmelCase_				    =		42
    lowerCAmelCase_				    =		42
    lowerCAmelCase_				    =		42
    lowerCAmelCase_				    =		42



    def __init__(	self      :       Optional[int],__A      :       SquadDataTrainingArguments,__A      :       PreTrainedTokenizer,__A      :       Optional[int] = None,__A      :       Union[str, Split] = Split.train,__A      :       Optional[bool] = False,__A      :       Optional[str] = None,__A      :       Optional[str] = "pt",):
          _lowerCamelCase				:   Tuple								=   args
          _lowerCamelCase				:   List[str]								=   is_language_sensitive
          _lowerCamelCase				:   Dict								=   SquadVaProcessor() if args.version_2_with_negative else SquadVaProcessor()
          if isinstance(__A,__A     ):
                try:
                      _lowerCamelCase				:   Union[str, Any]								=   Split[mode]
                except KeyError:
                      raise KeyError("mode is not a valid split name"     )
          _lowerCamelCase				:   str								=   mode
          # Load data features from cache or dataset file
          _lowerCamelCase				:   str								=   "v2" if args.version_2_with_negative else "v1"
          _lowerCamelCase				:   Optional[Any]								=   os.path.join(
              cache_dir if cache_dir is not None else args.data_dir,f'cached_{mode.value}_{tokenizer.__class__.__name__}_{args.max_seq_length}_{version_tag}',)

          # Make sure only the first process in distributed training processes the dataset,
          # and the others will use the cache.
          _lowerCamelCase				:   Tuple								=   cached_features_file + ".lock"
          with FileLock(__A     ):
                if os.path.exists(__A     ) and not args.overwrite_cache:
                      _lowerCamelCase				:   int								=   time.time()
                      _lowerCamelCase				:   int								=   torch.load(__A     )

                      # Legacy cache files have only features, while new cache files
                      # will have dataset and examples also.
                      _lowerCamelCase				:   Union[str, Any]								=   self.old_features["features"]
                      _lowerCamelCase				:   List[Any]								=   self.old_features.get("dataset",__A     )
                      _lowerCamelCase				:   List[Any]								=   self.old_features.get("examples",__A     )
                      logger.info(
                          f'Loading features from cached file {cached_features_file} [took %.3f s]',time.time() - start     )

                      if self.dataset is None or self.examples is None:
                            logger.warning(
                                f'Deleting cached file {cached_features_file} will allow dataset and examples to be cached in'
                                " future run"     )
                else:
                      if mode == Split.dev:
                            _lowerCamelCase				:   Dict								=   self.processor.get_dev_examples(args.data_dir     )
                      else:
                            _lowerCamelCase				:   Dict								=   self.processor.get_train_examples(args.data_dir     )

                      _lowerCamelCase						,		_lowerCamelCase				:   Dict								=   squad_convert_examples_to_features(
                          examples=self.examples,tokenizer=__A,max_seq_length=args.max_seq_length,doc_stride=args.doc_stride,max_query_length=args.max_query_length,is_training=mode == Split.train,threads=args.threads,return_dataset=__A,)

                      _lowerCamelCase				:   List[Any]								=   time.time()
                      torch.save(
                          {"features": self.features, "dataset": self.dataset, "examples": self.examples},__A,)
                      # ^ This seems to take a lot of time so I want to investigate why and how we can improve.
                      logger.info(
                          f'Saving features into cached file {cached_features_file} [took {time.time() - start:.3f} s]'     )



    def __len__(	self      :       Optional[Any]     ):
          return len(self.features     )



    def __getitem__(	self      :       Tuple,__A      :       str     ):
          # Convert to Tensors and build dataset
          _lowerCamelCase				:   List[str]								=   self.features[i]

          _lowerCamelCase				:   List[str]								=   torch.tensor(feature.input_ids,dtype=torch.long     )
          _lowerCamelCase				:   Optional[int]								=   torch.tensor(feature.attention_mask,dtype=torch.long     )
          _lowerCamelCase				:   Union[str, Any]								=   torch.tensor(feature.token_type_ids,dtype=torch.long     )
          _lowerCamelCase				:   str								=   torch.tensor(feature.cls_index,dtype=torch.long     )
          _lowerCamelCase				:   str								=   torch.tensor(feature.p_mask,dtype=torch.float     )
          _lowerCamelCase				:   Tuple								=   torch.tensor(feature.is_impossible,dtype=torch.float     )

          _lowerCamelCase				:   Optional[Any]								=   {
              "input_ids": input_ids,
              "attention_mask": attention_mask,
              "token_type_ids": token_type_ids,
          }

          if self.args.model_type in ["xlm", "roberta", "distilbert", "camembert"]:
                del inputs["token_type_ids"]

          if self.args.model_type in ["xlnet", "xlm"]:
                inputs.update({"cls_index": cls_index, "p_mask": p_mask}     )
                if self.args.version_2_with_negative:
                      inputs.update({"is_impossible": is_impossible}     )
                if self.is_language_sensitive:
                      inputs.update({"langs": (torch.ones(input_ids.shape,dtype=torch.intaa     ) * self.args.lang_id)}     )

          if self.mode == Split.train:
                _lowerCamelCase				:   List[str]								=   torch.tensor(feature.start_position,dtype=torch.long     )
                _lowerCamelCase				:   Any								=   torch.tensor(feature.end_position,dtype=torch.long     )
                inputs.update({"start_positions": start_positions, "end_positions": end_positions}     )

          return inputs