



"""simple docstring"""







import logging
import os
import sys
from dataclasses import dataclass, field
from importlib import import_module
from typing import Dict, List, Optional, Tuple

import numpy as np
from seqeval.metrics import accuracy_score, fa_score, precision_score, recall_score
from torch import nn
from utils_ner import Split, TokenClassificationDataset, TokenClassificationTask

import transformers
from transformers import (
    AutoConfig,
    AutoModelForTokenClassification,
    AutoTokenizer,
    DataCollatorWithPadding,
    EvalPrediction,
    HfArgumentParser,
    Trainer,
    TrainingArguments,
    set_seed,
)
from transformers.trainer_utils import is_main_process


lowercase__		:    Union[str, Any]				   =     logging.getLogger(__name__)







@dataclass
class 				UpperCamelCase__       :




      """simple docstring"""




      _SCREAMING_SNAKE_CASE      =					field(
          metadata={"""help""": """Path to pretrained model or model identifier from huggingface.co/models"""}  )
      _SCREAMING_SNAKE_CASE      =					field(
          default=lowercase_, metadata={"""help""": """Pretrained config name or path if not the same as model_name"""}  )
      _SCREAMING_SNAKE_CASE      =					field(
          default="""NER""", metadata={"""help""": """Task type to fine tune in training (e.g. NER, POS, etc)"""}  )
      _SCREAMING_SNAKE_CASE      =					field(
          default=lowercase_, metadata={"""help""": """Pretrained tokenizer name or path if not the same as model_name"""}  )
      _SCREAMING_SNAKE_CASE      =					field(default=lowercase_, 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=lowercase_, metadata={"""help""": """Where do you want to store the pretrained models downloaded from huggingface.co"""}, )







@dataclass
class 				UpperCamelCase__       :




      """simple docstring"""




      _SCREAMING_SNAKE_CASE      =					field(
          metadata={"""help""": """The input data dir. Should contain the .txt files for a CoNLL-2003-formatted task."""}  )
      _SCREAMING_SNAKE_CASE      =					field(
          default=lowercase_, metadata={"""help""": """Path to a file containing all labels. If not specified, CoNLL-2003 labels are used."""}, )
      _SCREAMING_SNAKE_CASE      =					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."""
              )
          }, )
      _SCREAMING_SNAKE_CASE      =					field(
          default=lowercase_, metadata={"""help""": """Overwrite the cached training and evaluation sets"""}  )




def     UpperCamelCase_   (   )						->       Any:

  """simple docstring"""




  lowerCAmelCase_       :    str								=			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.
    lowerCAmelCase_						,lowerCAmelCase_						,lowerCAmelCase_       :    List[Any]								=			parser.parse_json_file(json_file=os.path.abspath(sys.argv[1]						)						)
  else:
    lowerCAmelCase_						,lowerCAmelCase_						,lowerCAmelCase_       :    Optional[Any]								=			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.'						)

  lowerCAmelCase_       :    Any								=			import_module('tasks'						)
  try:
    lowerCAmelCase_       :    Union[str, Any]								=			getattr(lowerCAmelCase__   ,       model_args.task_type						)
    lowerCAmelCase_       :    TokenClassificationTask								=			token_classification_task_clazz()
  except AttributeError:
    raise ValueError(
        f"Task {model_args.task_type} needs to be defined as a TokenClassificationTask subclass in {module}. "
        f"Available tasks classes are: {TokenClassificationTask.__subclasses__()}"						)

  # 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'   ,       lowerCAmelCase__						)

  # Set seed
  set_seed(training_args.seed						)

  # Prepare CONLL-2003 task
  lowerCAmelCase_       :    List[Any]								=			token_classification_task.get_labels(data_args.labels						)
  lowerCAmelCase_       :    Dict[int, str]								=			dict(enumerate(lowerCAmelCase__						)						)
  lowerCAmelCase_       :    Tuple								=			len(lowerCAmelCase__						)

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

  lowerCAmelCase_       :    int								=			AutoConfig.from_pretrained(
      model_args.config_name if model_args.config_name else model_args.model_name_or_path   ,       num_labels=lowerCAmelCase__   ,       idalabel=lowerCAmelCase__   ,       labelaid={label: i for i, label in enumerate(lowerCAmelCase__						)}   ,       cache_dir=model_args.cache_dir   ,       )
  lowerCAmelCase_       :    str								=			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=model_args.use_fast   ,       )
  lowerCAmelCase_       :    Any								=			AutoModelForTokenClassification.from_pretrained(
      model_args.model_name_or_path   ,       from_tf=bool('.ckpt' in model_args.model_name_or_path						)   ,       config=lowerCAmelCase__   ,       cache_dir=model_args.cache_dir   ,       )

  # Get datasets
  lowerCAmelCase_       :    Optional[int]								=			(
      TokenClassificationDataset(
          token_classification_task=lowerCAmelCase__   ,       data_dir=data_args.data_dir   ,       tokenizer=lowerCAmelCase__   ,       labels=lowerCAmelCase__   ,       model_type=config.model_type   ,       max_seq_length=data_args.max_seq_length   ,       overwrite_cache=data_args.overwrite_cache   ,       mode=Split.train   ,       )
      if training_args.do_train
      else None
  )
  lowerCAmelCase_       :    List[Any]								=			(
      TokenClassificationDataset(
          token_classification_task=lowerCAmelCase__   ,       data_dir=data_args.data_dir   ,       tokenizer=lowerCAmelCase__   ,       labels=lowerCAmelCase__   ,       model_type=config.model_type   ,       max_seq_length=data_args.max_seq_length   ,       overwrite_cache=data_args.overwrite_cache   ,       mode=Split.dev   ,       )
      if training_args.do_eval
      else None
  )

  def align_predictions(lowerCAmelCase__				:    np.ndarray   ,       lowerCAmelCase__				:    np.ndarray						) -> Tuple[List[int], List[int]]:
    lowerCAmelCase_       :    List[str]								=			np.argmax(lowerCAmelCase__   ,       axis=2						)

    lowerCAmelCase_						,lowerCAmelCase_       :    Union[str, Any]								=			preds.shape

    lowerCAmelCase_       :    Optional[Any]								=			[[] for _ in range(lowerCAmelCase__						)]
    lowerCAmelCase_       :    List[str]								=			[[] for _ in range(lowerCAmelCase__						)]

    for i in range(lowerCAmelCase__						):
      for j in range(lowerCAmelCase__						):
        if label_ids[i, j] != nn.CrossEntropyLoss().ignore_index:
          out_label_list[i].append(label_map[label_ids[i][j]]						)
          preds_list[i].append(label_map[preds[i][j]]						)

    return preds_list, out_label_list

  def compute_metrics(lowerCAmelCase__				:    EvalPrediction						) -> Dict:
    lowerCAmelCase_						,lowerCAmelCase_       :    Optional[Any]								=			align_predictions(p.predictions   ,       p.label_ids						)
    return {
        "accuracy_score": accuracy_score(lowerCAmelCase__   ,       lowerCAmelCase__						),
        "precision": precision_score(lowerCAmelCase__   ,       lowerCAmelCase__						),
        "recall": recall_score(lowerCAmelCase__   ,       lowerCAmelCase__						),
        "f1": fa_score(lowerCAmelCase__   ,       lowerCAmelCase__						),
    }

  # Data collator
  lowerCAmelCase_       :    str								=			DataCollatorWithPadding(lowerCAmelCase__   ,       pad_to_multiple_of=8						) if training_args.fpaa else None

  # Initialize our Trainer
  lowerCAmelCase_       :    Dict								=			Trainer(
      model=lowerCAmelCase__   ,       args=lowerCAmelCase__   ,       train_dataset=lowerCAmelCase__   ,       eval_dataset=lowerCAmelCase__   ,       compute_metrics=lowerCAmelCase__   ,       data_collator=lowerCAmelCase__   ,       )

  # 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_process_zero():
      tokenizer.save_pretrained(training_args.output_dir						)

    # Evaluation
  lowerCAmelCase_       :    Dict								=			{}
  if training_args.do_eval:
    logger.info('*** Evaluate ***'						)

    lowerCAmelCase_       :    Union[str, Any]								=			trainer.evaluate()

    lowerCAmelCase_       :    Tuple								=			os.path.join(training_args.output_dir   ,       'eval_results.txt'						)
    if trainer.is_world_process_zero():
      with open(lowerCAmelCase__   ,       'w'						) as writer:
        logger.info('***** Eval results *****'						)
        for key, value in result.items():
          logger.info('  %s = %s'   ,       lowerCAmelCase__   ,       lowerCAmelCase__						)
          writer.write('%s = %s\n' % (key, value)						)

      results.update(lowerCAmelCase__						)

    # Predict
  if training_args.do_predict:
    lowerCAmelCase_       :    List[str]								=			TokenClassificationDataset(
        token_classification_task=lowerCAmelCase__   ,       data_dir=data_args.data_dir   ,       tokenizer=lowerCAmelCase__   ,       labels=lowerCAmelCase__   ,       model_type=config.model_type   ,       max_seq_length=data_args.max_seq_length   ,       overwrite_cache=data_args.overwrite_cache   ,       mode=Split.test   ,       )

    lowerCAmelCase_						,lowerCAmelCase_						,lowerCAmelCase_       :    Optional[int]								=			trainer.predict(lowerCAmelCase__						)
    lowerCAmelCase_						,lowerCAmelCase_       :    Tuple								=			align_predictions(lowerCAmelCase__   ,       lowerCAmelCase__						)

    lowerCAmelCase_       :    List[str]								=			os.path.join(training_args.output_dir   ,       'test_results.txt'						)
    if trainer.is_world_process_zero():
      with open(lowerCAmelCase__   ,       'w'						) as writer:
        for key, value in metrics.items():
          logger.info('  %s = %s'   ,       lowerCAmelCase__   ,       lowerCAmelCase__						)
          writer.write('%s = %s\n' % (key, value)						)

        # Save predictions
    lowerCAmelCase_       :    int								=			os.path.join(training_args.output_dir   ,       'test_predictions.txt'						)
    if trainer.is_world_process_zero():
      with open(lowerCAmelCase__   ,       'w'						) as writer:
        with open(os.path.join(data_args.data_dir   ,       'test.txt'						)   ,       'r'						) as f:
          token_classification_task.write_predictions_to_file(lowerCAmelCase__   ,       lowerCAmelCase__   ,       lowerCAmelCase__						)

  return results

def     UpperCamelCase_   (   lowerCAmelCase__				:    Any						)						->       Optional[int]:

  """simple docstring"""




  main()


if __name__ == "__main__":
     main()










"""simple docstring"""







import random
import timeit
from functools import wraps
from typing import Callable, Optional

from ..configuration_utils import PretrainedConfig
from ..models.auto.modeling_tf_auto import TF_MODEL_MAPPING, TF_MODEL_WITH_LM_HEAD_MAPPING
from ..utils import is_pyanvml_available, is_tf_available, logging
from .benchmark_utils import (
    Benchmark,
    Memory,
    MemorySummary,
    measure_peak_memory_cpu,
    start_memory_tracing,
    stop_memory_tracing,
)


if is_tf_available():
     import tensorflow as tf
     from tensorflow.python.framework.errors_impl import ResourceExhaustedError

     from .benchmark_args_tf import TensorFlowBenchmarkArguments

if is_pyanvml_available():
     import pyanvml.pyanvml as nvml

lowercase__		:    str				   =     logging.get_logger(__name__)

def     UpperCamelCase_   (   lowerCAmelCase__				:    bool   ,       lowerCAmelCase__				:    bool						)						->       List[Any]:

  """simple docstring"""




  def run_func(lowerCAmelCase__				:    int						):
    @wraps(lowerCAmelCase__						)
    def run_in_eager_mode(*lowerCAmelCase__				:    List[Any]   ,       **lowerCAmelCase__				:    int						):
      return func(*lowerCAmelCase__   ,       **lowerCAmelCase__						)

    @wraps(lowerCAmelCase__						)
    @tf.function(experimental_compile=lowerCAmelCase__						)
    def run_in_graph_mode(*lowerCAmelCase__				:    Dict   ,       **lowerCAmelCase__				:    Any						):
      return func(*lowerCAmelCase__   ,       **lowerCAmelCase__						)

    if do_eager_mode is True:
      if use_xla is not False:
        raise ValueError(
            'Cannot run model in XLA, if `args.eager_mode` is set to `True`. Please set `args.eager_mode=False`.'						)
      return run_in_eager_mode
    else:
      return run_in_graph_mode

  return run_func

def     UpperCamelCase_   (   lowerCAmelCase__				:    int   ,       lowerCAmelCase__				:    int   ,       lowerCAmelCase__				:    int						)						->       ["tf.Tensor"]:

  """simple docstring"""




  lowerCAmelCase_       :    Dict								=			random.Random()
  lowerCAmelCase_       :    List[str]								=			[rng.randint(0   ,       vocab_size - 1						) for i in range(batch_size * sequence_length						)]
  return tf.constant(lowerCAmelCase__   ,       shape=(batch_size, sequence_length)   ,       dtype=tf.intaa						)







class 				UpperCamelCase__       (     lowercase_  ):




      """simple docstring"""




      _SCREAMING_SNAKE_CASE      =					42
      _SCREAMING_SNAKE_CASE      =					42
      _SCREAMING_SNAKE_CASE      =					"TensorFlow"



      @property
      def 					SCREAMING_SNAKE_CASE__			(				self    :				Optional[Any]	):
        return tf.__version__



      def 					SCREAMING_SNAKE_CASE__			(				self    :				Union[str, Any]   ,      SCREAMING_SNAKE_CASE_    :				str   ,      SCREAMING_SNAKE_CASE_    :				int   ,      SCREAMING_SNAKE_CASE_    :				int	):
        # initialize GPU on separate process
        lowerCAmelCase_       :    List[Any]								=			self.args.strategy
        if strategy is None:
          raise ValueError('A device strategy has to be initialized before using TensorFlow.'	)
        lowerCAmelCase_       :    List[str]								=			self._prepare_inference_func(SCREAMING_SNAKE_CASE_   ,      SCREAMING_SNAKE_CASE_   ,      SCREAMING_SNAKE_CASE_	)
        return self._measure_speed(_inference	)



      def 					SCREAMING_SNAKE_CASE__			(				self    :				Any   ,      SCREAMING_SNAKE_CASE_    :				str   ,      SCREAMING_SNAKE_CASE_    :				int   ,      SCREAMING_SNAKE_CASE_    :				int	):
        lowerCAmelCase_       :    Optional[int]								=			self.args.strategy
        if strategy is None:
          raise ValueError('A device strategy has to be initialized before using TensorFlow.'	)
        lowerCAmelCase_       :    Any								=			self._prepare_train_func(SCREAMING_SNAKE_CASE_   ,      SCREAMING_SNAKE_CASE_   ,      SCREAMING_SNAKE_CASE_	)
        return self._measure_speed(_train	)



      def 					SCREAMING_SNAKE_CASE__			(				self    :				List[str]   ,      SCREAMING_SNAKE_CASE_    :				str   ,      SCREAMING_SNAKE_CASE_    :				int   ,      SCREAMING_SNAKE_CASE_    :				int	):
        # initialize GPU on separate process
        if self.args.is_gpu:
          tf.config.experimental.set_memory_growth(self.args.gpu_list[self.args.device_idx]   ,      SCREAMING_SNAKE_CASE_	)
        lowerCAmelCase_       :    Any								=			self.args.strategy
        if strategy is None:
          raise ValueError('A device strategy has to be initialized before using TensorFlow.'	)
        lowerCAmelCase_       :    Optional[Any]								=			self._prepare_inference_func(SCREAMING_SNAKE_CASE_   ,      SCREAMING_SNAKE_CASE_   ,      SCREAMING_SNAKE_CASE_	)
        return self._measure_memory(_inference	)



      def 					SCREAMING_SNAKE_CASE__			(				self    :				Any   ,      SCREAMING_SNAKE_CASE_    :				str   ,      SCREAMING_SNAKE_CASE_    :				int   ,      SCREAMING_SNAKE_CASE_    :				int	):
        if self.args.is_gpu:
          tf.config.experimental.set_memory_growth(self.args.gpu_list[self.args.device_idx]   ,      SCREAMING_SNAKE_CASE_	)
        lowerCAmelCase_       :    Any								=			self.args.strategy
        if strategy is None:
          raise ValueError('A device strategy has to be initialized before using TensorFlow.'	)

        lowerCAmelCase_       :    Optional[int]								=			self._prepare_train_func(SCREAMING_SNAKE_CASE_   ,      SCREAMING_SNAKE_CASE_   ,      SCREAMING_SNAKE_CASE_	)
        return self._measure_memory(_train	)



      def 					SCREAMING_SNAKE_CASE__			(				self    :				Any   ,      SCREAMING_SNAKE_CASE_    :				str   ,      SCREAMING_SNAKE_CASE_    :				int   ,      SCREAMING_SNAKE_CASE_    :				int	):
        lowerCAmelCase_       :    Any								=			self.config_dict[model_name]

        if self.args.fpaa:
          raise NotImplementedError('Mixed precision is currently not supported.'	)

        lowerCAmelCase_       :    Union[str, Any]								=			(
            hasattr(SCREAMING_SNAKE_CASE_   ,      'architectures'	)
            and isinstance(config.architectures   ,      SCREAMING_SNAKE_CASE_	)
            and len(config.architectures	) > 0
        )
        if not self.args.only_pretrain_model and has_model_class_in_config:
          try:
            lowerCAmelCase_       :    Any								=			'TF' + config.architectures[0]  # prepend 'TF' for tensorflow model
            lowerCAmelCase_       :    Any								=			__import__('transformers'   ,      fromlist=[model_class]	)
            lowerCAmelCase_       :    Dict								=			getattr(SCREAMING_SNAKE_CASE_   ,      SCREAMING_SNAKE_CASE_	)
            lowerCAmelCase_       :    List[str]								=			model_cls(SCREAMING_SNAKE_CASE_	)
          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:
          lowerCAmelCase_       :    str								=			TF_MODEL_MAPPING[config.__class__](SCREAMING_SNAKE_CASE_	)

        # encoder-decoder has vocab size saved differently
        lowerCAmelCase_       :    List[Any]								=			config.vocab_size if hasattr(SCREAMING_SNAKE_CASE_   ,      'vocab_size'	) else config.encoder.vocab_size
        lowerCAmelCase_       :    Tuple								=			random_input_ids(SCREAMING_SNAKE_CASE_   ,      SCREAMING_SNAKE_CASE_   ,      SCREAMING_SNAKE_CASE_	)

        @run_with_tf_optimizations(self.args.eager_mode   ,      self.args.use_xla	)
        def encoder_decoder_forward():
          return model(SCREAMING_SNAKE_CASE_   ,      decoder_input_ids=SCREAMING_SNAKE_CASE_   ,      training=SCREAMING_SNAKE_CASE_	)

        @run_with_tf_optimizations(self.args.eager_mode   ,      self.args.use_xla	)
        def encoder_forward():
          return model(SCREAMING_SNAKE_CASE_   ,      training=SCREAMING_SNAKE_CASE_	)

        lowerCAmelCase_       :    List[Any]								=			encoder_decoder_forward if config.is_encoder_decoder else encoder_forward

        return _inference



      def 					SCREAMING_SNAKE_CASE__			(				self    :				Optional[int]   ,      SCREAMING_SNAKE_CASE_    :				str   ,      SCREAMING_SNAKE_CASE_    :				int   ,      SCREAMING_SNAKE_CASE_    :				int	):
        lowerCAmelCase_       :    Union[str, Any]								=			self.config_dict[model_name]

        if self.args.eager_mode is not False:
          raise ValueError('Training cannot be done in eager mode. Please make sure that `args.eager_mode = False`.'	)

        if self.args.fpaa:
          raise NotImplementedError('Mixed precision is currently not supported.'	)

        lowerCAmelCase_       :    Dict								=			(
            hasattr(SCREAMING_SNAKE_CASE_   ,      'architectures'	)
            and isinstance(config.architectures   ,      SCREAMING_SNAKE_CASE_	)
            and len(config.architectures	) > 0
        )
        if not self.args.only_pretrain_model and has_model_class_in_config:
          try:
            lowerCAmelCase_       :    Optional[Any]								=			'TF' + config.architectures[0]  # prepend 'TF' for tensorflow model
            lowerCAmelCase_       :    int								=			__import__('transformers'   ,      fromlist=[model_class]	)
            lowerCAmelCase_       :    Any								=			getattr(SCREAMING_SNAKE_CASE_   ,      SCREAMING_SNAKE_CASE_	)
            lowerCAmelCase_       :    Optional[Any]								=			model_cls(SCREAMING_SNAKE_CASE_	)
          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:
          lowerCAmelCase_       :    Union[str, Any]								=			TF_MODEL_WITH_LM_HEAD_MAPPING[config.__class__](SCREAMING_SNAKE_CASE_	)

        # encoder-decoder has vocab size saved differently
        lowerCAmelCase_       :    int								=			config.vocab_size if hasattr(SCREAMING_SNAKE_CASE_   ,      'vocab_size'	) else config.encoder.vocab_size
        lowerCAmelCase_       :    Optional[Any]								=			random_input_ids(SCREAMING_SNAKE_CASE_   ,      SCREAMING_SNAKE_CASE_   ,      SCREAMING_SNAKE_CASE_	)

        @run_with_tf_optimizations(self.args.eager_mode   ,      self.args.use_xla	)
        def encoder_decoder_train():
          lowerCAmelCase_       :    str								=			model(SCREAMING_SNAKE_CASE_   ,      decoder_input_ids=SCREAMING_SNAKE_CASE_   ,      labels=SCREAMING_SNAKE_CASE_   ,      training=SCREAMING_SNAKE_CASE_	)[0]
          lowerCAmelCase_       :    Optional[int]								=			tf.gradients(SCREAMING_SNAKE_CASE_   ,      model.trainable_variables	)
          return gradients

        @run_with_tf_optimizations(self.args.eager_mode   ,      self.args.use_xla	)
        def encoder_train():
          lowerCAmelCase_       :    Dict								=			model(SCREAMING_SNAKE_CASE_   ,      labels=SCREAMING_SNAKE_CASE_   ,      training=SCREAMING_SNAKE_CASE_	)[0]
          lowerCAmelCase_       :    str								=			tf.gradients(SCREAMING_SNAKE_CASE_   ,      model.trainable_variables	)
          return gradients

        lowerCAmelCase_       :    int								=			encoder_decoder_train if config.is_encoder_decoder else encoder_train

        return _train



      def 					SCREAMING_SNAKE_CASE__			(				self    :				List[str]   ,      SCREAMING_SNAKE_CASE_    :				Tuple	):
        with self.args.strategy.scope():
          try:
            if self.args.is_tpu or self.args.use_xla:
              # run additional 10 times to stabilize compilation for tpu
              logger.info('Do inference on TPU. Running model 5 times to stabilize compilation'	)
              timeit.repeat(SCREAMING_SNAKE_CASE_   ,      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
            lowerCAmelCase_       :    Dict								=			timeit.repeat(
                SCREAMING_SNAKE_CASE_   ,      repeat=self.args.repeat   ,      number=1_0   ,      )

            return min(SCREAMING_SNAKE_CASE_	) / 10.0
          except ResourceExhaustedError as e:
            self.print_fn(F"Doesn't fit on GPU. {e}"	)





      def 					SCREAMING_SNAKE_CASE__			(				self    :				int   ,      SCREAMING_SNAKE_CASE_    :				Callable[[], None]	):
        logger.info(
            'Note that TensorFlow allocates more memory than '
            'it might need to speed up computation. '
            'The memory reported here corresponds to the memory '
            'reported by `nvidia-smi`, which can vary depending '
            'on total available memory on the GPU that is used.'	)
        with self.args.strategy.scope():
          try:
            if self.args.trace_memory_line_by_line:
              if not self.args.eager_mode:
                raise ValueError(
                    '`args.eager_mode` is set to `False`. Make sure to run model in eager mode to measure memory'
                    ' consumption line by line.'	)
              lowerCAmelCase_       :    Union[str, Any]								=			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 `args.memory=False`'	)
            elif self.args.is_gpu:
              # 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.'	)
                lowerCAmelCase_       :    Tuple								=			'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()
                lowerCAmelCase_       :    int								=			nvml.nvmlDeviceGetHandleByIndex(self.args.device_idx	)
                lowerCAmelCase_       :    Union[str, Any]								=			nvml.nvmlDeviceGetMemoryInfo(SCREAMING_SNAKE_CASE_	)
                lowerCAmelCase_       :    List[Any]								=			meminfo.used
                lowerCAmelCase_       :    int								=			Memory(SCREAMING_SNAKE_CASE_	)
                # shutdown nvml
                nvml.nvmlShutdown()
            else:
              # cpu
              if self.args.trace_memory_line_by_line:
                logger.info(
                    'When enabling line by line tracing, the max peak memory for CPU is inaccurate in'
                    ' TensorFlow.'	)
                lowerCAmelCase_       :    Optional[int]								=			None
              else:
                lowerCAmelCase_       :    Union[str, Any]								=			measure_peak_memory_cpu(SCREAMING_SNAKE_CASE_	)
                lowerCAmelCase_       :    Any								=			Memory(SCREAMING_SNAKE_CASE_	) if isinstance(SCREAMING_SNAKE_CASE_   ,      SCREAMING_SNAKE_CASE_	) else memory_bytes
            if self.args.trace_memory_line_by_line:
              lowerCAmelCase_       :    List[Any]								=			stop_memory_tracing(SCREAMING_SNAKE_CASE_	)
              if memory is None:
                lowerCAmelCase_       :    Union[str, Any]								=			summary.total
            else:
              lowerCAmelCase_       :    List[str]								=			None

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





