

import timeit
from typing import Callable, Optional

from ..configuration_utils import PretrainedConfig
from ..models.auto.modeling_auto import MODEL_MAPPING, MODEL_WITH_LM_HEAD_MAPPING
from ..utils import is_pyanvml_available, is_torch_available, logging
from .benchmark_utils import (
    Benchmark,
    Memory,
    MemorySummary,
    measure_peak_memory_cpu,
    start_memory_tracing,
    stop_memory_tracing,
)


if is_torch_available():
 import torch

 from .benchmark_args import PyTorchBenchmarkArguments


if is_pyanvml_available():
 import pyanvml.pyanvml as nvml


_UpperCamelCase     =    logging.get_logger(__name__)



class 					lowercase		( _UpperCamelCase      ):



 '''simple docstring'''


 __SCREAMING_SNAKE_CASE      							=       42
 __SCREAMING_SNAKE_CASE      							=       42
 __SCREAMING_SNAKE_CASE      							=       "PyTorch"




 @property
 def 						UpperCamelCase__							(self				)				->      Dict:






  """simple docstring"""





  return torch.__version__




 def 						UpperCamelCase__							(self , __a , __a , __a				)				->      float:






  """simple docstring"""





  UpperCAmelCase__           =       self._prepare_inference_func(__a , __a , __a				)
  return self._measure_speed(_inference				)




 def 						UpperCamelCase__							(self , __a , __a , __a				)				->      [Memory, Optional[MemorySummary]]:






  """simple docstring"""





  UpperCAmelCase__           =       self._prepare_inference_func(__a , __a , __a				)
  return self._measure_memory(_inference				)




 def 						UpperCamelCase__							(self , __a , __a , __a				)				->      float:






  """simple docstring"""





  UpperCAmelCase__           =       self._prepare_train_func(__a , __a , __a				)
  return self._measure_speed(_train				)




 def 						UpperCamelCase__							(self , __a , __a , __a				)				->      [Memory, Optional[MemorySummary]]:






  """simple docstring"""





  UpperCAmelCase__           =       self._prepare_train_func(__a , __a , __a				)
  return self._measure_memory(_train				)




 def 						UpperCamelCase__							(self , __a , __a , __a				)				->      Callable[[], None]:






  """simple docstring"""





  UpperCAmelCase__           =       self.config_dict[model_name]

  if self.args.torchscript:
   UpperCAmelCase__           =       True

  UpperCAmelCase__           =       (
      hasattr(__a , 'architectures'				)
      and isinstance(config.architectures , __a				)
      and len(config.architectures				) > 0
  )
  if not self.args.only_pretrain_model and has_model_class_in_config:
   try:
    UpperCAmelCase__           =       config.architectures[0]
    UpperCAmelCase__           =       __import__('transformers' , fromlist=[model_class]				)
    UpperCAmelCase__           =       getattr(__a , __a				)
    UpperCAmelCase__           =       model_cls(__a				)
   except ImportError:
    raise ImportError(
        F"{model_class} does not exist. If you just want to test the pretrained model, you might want to"
        ' set `--only_pretrain_model` or `args.only_pretrain_model=True`.'				)
  else:
   UpperCAmelCase__           =       MODEL_MAPPING[config.__class__](__a				)

  model.eval()
  model.to(self.args.device				)

  # encoder-decoder has vocab size saved differently
  UpperCAmelCase__           =       config.vocab_size if hasattr(__a , 'vocab_size'				) else config.encoder.vocab_size
  UpperCAmelCase__           =       torch.randint(__a , (batch_size, sequence_length) , dtype=torch.long , device=self.args.device				)

  if self.args.fpaa:
   logger.info('Running training in Mixed Precision...'				)
   if not self.args.is_gpu:
    raise ValueError('Mixed precision is possible only for GPU.'				)
   # amp seems to have memory leaks so that memory usage
   # is measured using .half() for now https://github.com/NVIDIA/apex/issues/439
   model.half()

  if self.args.torchscript:
   with torch.no_grad():
    UpperCAmelCase__           =       torch.jit.trace(__a , __a				)
  else:
   UpperCAmelCase__           =       model

  def encoder_decoder_forward():
   with torch.no_grad():
    UpperCAmelCase__           =       inference_model(__a , decoder_input_ids=__a				)
   return outputs

  def encoder_forward():
   with torch.no_grad():
    UpperCAmelCase__           =       inference_model(__a				)
   return outputs

  UpperCAmelCase__           =       encoder_decoder_forward if config.is_encoder_decoder else encoder_forward
  return _forward




 def 						UpperCamelCase__							(self , __a , __a , __a				)				->      Callable[[], None]:






  """simple docstring"""





  UpperCAmelCase__           =       self.config_dict[model_name]

  UpperCAmelCase__           =       (
      hasattr(__a , 'architectures'				)
      and isinstance(config.architectures , __a				)
      and len(config.architectures				) > 0
  )
  if not self.args.only_pretrain_model and has_model_class_in_config:
   try:
    UpperCAmelCase__           =       config.architectures[0]
    UpperCAmelCase__           =       __import__('transformers' , fromlist=[model_class]				)
    UpperCAmelCase__           =       getattr(__a , __a				)
    UpperCAmelCase__           =       model_cls(__a				)
   except ImportError:
    raise ImportError(
        F"{model_class} does not exist. If you just want to test the pretrained model, you might want to"
        ' set `--only_pretrain_model` or `args.only_pretrain_model=True`.'				)
  else:
   UpperCAmelCase__           =       MODEL_WITH_LM_HEAD_MAPPING[config.__class__](__a				)

  if self.args.torchscript:
   raise NotImplementedError('Training for torchscript is currently not implemented'				)
  else:
   UpperCAmelCase__           =       model

  model.train()
  model.to(self.args.device				)

  # encoder-decoder has vocab size saved differently
  UpperCAmelCase__           =       config.vocab_size if hasattr(__a , 'vocab_size'				) else config.encoder.vocab_size
  UpperCAmelCase__           =       torch.randint(__a , (batch_size, sequence_length) , dtype=torch.long , device=self.args.device				)

  if self.args.fpaa:
   logger.info('Running training in Mixed Precision...'				)
   if not self.args.is_gpu:
    raise ValueError('Mixed precision is possible only for GPU.'				)

   # amp seems to have memory leaks so that memory usage
   # is measured using .half() for now https://github.com/NVIDIA/apex/issues/439
   model.half()

  def compute_loss_and_backprob_encoder():
   UpperCAmelCase__           =       train_model(__a , labels=__a				)[0]
   loss.backward()
   return loss

  def compute_loss_and_backprob_encoder_decoder():
   UpperCAmelCase__           =       train_model(__a , decoder_input_ids=__a , labels=__a				)[0]
   loss.backward()
   return loss

  UpperCAmelCase__           =       (
      compute_loss_and_backprob_encoder_decoder
      if config.is_encoder_decoder
      else compute_loss_and_backprob_encoder
  )
  return _train




 def 						UpperCamelCase__							(self , __a				)				->      float:






  """simple docstring"""





  try:
   if self.args.is_tpu or self.args.torchscript:
    # run additional 10 times to stabilize compilation for tpu and torchscript
    logger.info('Do inference on TPU or torchscript. Running model 5 times to stabilize compilation'				)
    timeit.repeat(
        __a , repeat=1 , number=5 , )

   # as written in https://docs.python.org/2/library/timeit.html#timeit.Timer.repeat, min should be taken rather than the average
   UpperCAmelCase__           =       timeit.repeat(
       __a , repeat=self.args.repeat , number=10 , )

   if self.args.is_tpu and self.args.torch_xla_tpu_print_metrics:
    import torch_xla.debug.metrics as met

    self.print_fn(met.metrics_report()				)

   return min(__a				) / 10.0
  except RuntimeError as e:
   self.print_fn(F"Doesn't fit on GPU. {e}"				)
   return "N/A"




 def 						UpperCamelCase__							(self , __a				)				->      [Memory, MemorySummary]:






  """simple docstring"""





  try:
   if self.args.trace_memory_line_by_line:
    UpperCAmelCase__           =       start_memory_tracing('transformers'				)

   if self.args.is_tpu:
    # tpu
    raise NotImplementedError(
        'Memory Benchmarking is currently not implemented for TPU. Please disable memory benchmarking with'
        ' `--no-memory` or `args.memory=False`'				)
   elif self.args.is_gpu:
    if not is_pyanvml_available():
     logger.warning(
         'py3nvml not installed, we won\'t log GPU memory usage. '
         'Install py3nvml (pip install py3nvml) to log information about GPU.'				)
     UpperCAmelCase__           =       'N/A'
    else:
     logger.info(
         'Measuring total GPU usage on GPU device. Make sure to not have additional processes running'
         ' on the same GPU.'				)
     # init nvml
     nvml.nvmlInit()
     func()
     UpperCAmelCase__           =       nvml.nvmlDeviceGetHandleByIndex(self.args.device_idx				)
     UpperCAmelCase__           =       nvml.nvmlDeviceGetMemoryInfo(__a				)
     UpperCAmelCase__           =       meminfo.used
     UpperCAmelCase__           =       Memory(__a				)
     # shutdown nvml
     nvml.nvmlShutdown()
   else:
    # cpu
    UpperCAmelCase__           =       measure_peak_memory_cpu(__a				)
    UpperCAmelCase__           =       Memory(__a				) if isinstance(__a , __a				) else memory_bytes

   if self.args.trace_memory_line_by_line:
    UpperCAmelCase__           =       stop_memory_tracing(__a				)
   else:
    UpperCAmelCase__           =       None

   return memory, summary
  except RuntimeError as e:
   self.print_fn(F"Doesn't fit on GPU. {e}"				)
   return "N/A", None






import logging
import os
import sys
from dataclasses import dataclass, field
from typing import Optional

import transformers
from transformers import (
    AutoConfig,
    AutoModelForQuestionAnswering,
    AutoTokenizer,
    DataCollatorWithPadding,
    HfArgumentParser,
    SquadDataset,
    Trainer,
    TrainingArguments,
)
from transformers import SquadDataTrainingArguments as DataTrainingArguments
from transformers.trainer_utils import is_main_process


_UpperCamelCase     =    logging.getLogger(__name__)



@dataclass
class 					lowercase		:



 '''simple docstring'''


 __SCREAMING_SNAKE_CASE      							=       field(
     metadata={"""help""": """Path to pretrained model or model identifier from huggingface.co/models"""}      )
 __SCREAMING_SNAKE_CASE      							=       field(
     default=_UpperCamelCase				,       metadata={"""help""": """Pretrained config name or path if not the same as model_name"""}      )
 __SCREAMING_SNAKE_CASE      							=       field(
     default=_UpperCamelCase				,       metadata={"""help""": """Pretrained tokenizer name or path if not the same as model_name"""}      )
 __SCREAMING_SNAKE_CASE      							=       field(default=_UpperCamelCase				,       metadata={"""help""": """Set this flag to use fast tokenization."""}      )
 # If you want to tweak more attributes on your tokenizer, you should do it in a distinct script,
 # or just modify its tokenizer_config.json.
 __SCREAMING_SNAKE_CASE      							=       field(
     default=_UpperCamelCase				,       metadata={"""help""": """Where do you want to store the pretrained models downloaded from huggingface.co"""}				,       )







def 		UpperCamelCase_(    ) ->				List[str]:
 # See all possible arguments in src/transformers/training_args.py
 # or by passing the --help flag to this script.
 # We now keep distinct sets of args, for a cleaner separation of concerns.

 UpperCAmelCase__           =       HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments)     )

 if len(sys.argv     ) == 2 and sys.argv[1].endswith('.json'     ):
  # If we pass only one argument to the script and it's the path to a json file,
  # let's parse it to get our arguments.
  UpperCAmelCase__       ,					UpperCAmelCase__       ,					UpperCAmelCase__           =       parser.parse_json_file(json_file=os.path.abspath(sys.argv[1]     )     )
 else:
  UpperCAmelCase__       ,					UpperCAmelCase__       ,					UpperCAmelCase__           =       parser.parse_args_into_dataclasses()

 if (
     os.path.exists(training_args.output_dir     )
     and os.listdir(training_args.output_dir     )
     and training_args.do_train
     and not training_args.overwrite_output_dir
 ):
  raise ValueError(
      f"Output directory ({training_args.output_dir}) already exists and is not empty. Use"
      ' --overwrite_output_dir to overcome.'     )

 # Setup logging
 logging.basicConfig(
     format='%(asctime)s - %(levelname)s - %(name)s - %(message)s'						,					datefmt='%m/%d/%Y %H:%M:%S'						,					level=logging.INFO if training_args.local_rank in [-1, 0] else logging.WARN						,					)
 logger.warning(
     'Process rank: %s, device: %s, n_gpu: %s, distributed training: %s, 16-bits training: %s'						,					training_args.local_rank						,					training_args.device						,					training_args.n_gpu						,					bool(training_args.local_rank != -1     )						,					training_args.fpaa						,					)
 # Set the verbosity to info of the Transformers logger (on main process only):
 if is_main_process(training_args.local_rank     ):
  transformers.utils.logging.set_verbosity_info()
  transformers.utils.logging.enable_default_handler()
  transformers.utils.logging.enable_explicit_format()
 logger.info('Training/evaluation parameters %s'						,					snake_case__     )

 # Prepare Question-Answering task
 # Load pretrained model and tokenizer
 #
 # Distributed training:
 # The .from_pretrained methods guarantee that only one local process can concurrently
 # download model & vocab.

 UpperCAmelCase__           =       AutoConfig.from_pretrained(
     model_args.config_name if model_args.config_name else model_args.model_name_or_path						,					cache_dir=model_args.cache_dir						,					)
 UpperCAmelCase__           =       AutoTokenizer.from_pretrained(
     model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path						,					cache_dir=model_args.cache_dir						,					use_fast=snake_case__						,					)
 UpperCAmelCase__           =       AutoModelForQuestionAnswering.from_pretrained(
     model_args.model_name_or_path						,					from_tf=bool('.ckpt' in model_args.model_name_or_path     )						,					config=snake_case__						,					cache_dir=model_args.cache_dir						,					)

 # Get datasets
 UpperCAmelCase__           =       hasattr(model.config						,					'lang2id'     )
 UpperCAmelCase__           =       (
     SquadDataset(
         snake_case__						,					tokenizer=snake_case__						,					is_language_sensitive=snake_case__						,					cache_dir=model_args.cache_dir     )
     if training_args.do_train
     else None
 )
 UpperCAmelCase__           =       (
     SquadDataset(
         snake_case__						,					tokenizer=snake_case__						,					mode='dev'						,					is_language_sensitive=snake_case__						,					cache_dir=model_args.cache_dir						,					)
     if training_args.do_eval
     else None
 )

 # Data collator
 UpperCAmelCase__           =       DataCollatorWithPadding(snake_case__						,					pad_to_multiple_of=8     ) if training_args.fpaa else None

 # Initialize our Trainer
 UpperCAmelCase__           =       Trainer(
     model=snake_case__						,					args=snake_case__						,					train_dataset=snake_case__						,					eval_dataset=snake_case__						,					data_collator=snake_case__						,					)

 # Training
 if training_args.do_train:
  trainer.train(
      model_path=model_args.model_name_or_path if os.path.isdir(model_args.model_name_or_path     ) else None     )
  trainer.save_model()
  # For convenience, we also re-save the tokenizer to the same directory,
  # so that you can share your model easily on huggingface.co/models =)
  if trainer.is_world_master():
   tokenizer.save_pretrained(training_args.output_dir     )
def 		UpperCamelCase_(    snake_case__:						Optional[int]     ) ->				Union[str, Any]:
 # For xla_spawn (TPUs)
 main()


if __name__ == "__main__":
 main()



