






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

lowerCamelCase__       		=  logging.get_logger(__name__)






def 	UpperCamelCase	(							snake_case__  : bool						,snake_case__  : bool	):




     '''simple docstring'''






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

          @wraps(snake_case__	)
          @tf.function(experimental_compile=snake_case__	)
          def run_in_graph_mode(*snake_case__  : Optional[Any]						,**snake_case__  : Optional[int]	):
               return func(*snake_case__						,**snake_case__	)

          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	(							snake_case__  : int						,snake_case__  : int						,snake_case__  : int	):




     '''simple docstring'''






     __snake_case      :Any 							=    random.Random()
     __snake_case      :Optional[Any] 							=    [rng.randint(0						,vocab_size - 1	) for i in range(batch_size * sequence_length	)]
     return tf.constant(snake_case__						,shape=(batch_size, sequence_length)						,dtype=tf.intaa	)




class       snake_case__ (				lowercase_):

       '''simple docstring'''
       lowerCamelCase				:					TensorFlowBenchmarkArguments
       lowerCamelCase				:					PretrainedConfig
       lowerCamelCase				:					str								=			"TensorFlow"



       @property
       def        __lowercase    (				self     )			->   Any:






            '''simple docstring'''





            return tf.__version__



       def        __lowercase    (				self      ,    a__      ,    a__      ,    a__     )			->   float:






            '''simple docstring'''





            __snake_case      :Tuple 							=    self.args.strategy
            if strategy is None:
                 raise ValueError("""A device strategy has to be initialized before using TensorFlow."""     )
            __snake_case      :int 							=    self._prepare_inference_func(a__      ,    a__      ,    a__     )
            return self._measure_speed(_inference     )



       def        __lowercase    (				self      ,    a__      ,    a__      ,    a__     )			->   float:






            '''simple docstring'''





            __snake_case      :Optional[int] 							=    self.args.strategy
            if strategy is None:
                 raise ValueError("""A device strategy has to be initialized before using TensorFlow."""     )
            __snake_case      :Dict 							=    self._prepare_train_func(a__      ,    a__      ,    a__     )
            return self._measure_speed(_train     )



       def        __lowercase    (				self      ,    a__      ,    a__      ,    a__     )			->   [Memory, Optional[MemorySummary]]:






            '''simple docstring'''





            if self.args.is_gpu:
                 tf.config.experimental.set_memory_growth(self.args.gpu_list[self.args.device_idx]      ,    a__     )
            __snake_case      :int 							=    self.args.strategy
            if strategy is None:
                 raise ValueError("""A device strategy has to be initialized before using TensorFlow."""     )
            __snake_case      :Optional[int] 							=    self._prepare_inference_func(a__      ,    a__      ,    a__     )
            return self._measure_memory(_inference     )



       def        __lowercase    (				self      ,    a__      ,    a__      ,    a__     )			->   [Memory, Optional[MemorySummary]]:






            '''simple docstring'''





            if self.args.is_gpu:
                 tf.config.experimental.set_memory_growth(self.args.gpu_list[self.args.device_idx]      ,    a__     )
            __snake_case      :Optional[Any] 							=    self.args.strategy
            if strategy is None:
                 raise ValueError("""A device strategy has to be initialized before using TensorFlow."""     )

            __snake_case      :int 							=    self._prepare_train_func(a__      ,    a__      ,    a__     )
            return self._measure_memory(_train     )



       def        __lowercase    (				self      ,    a__      ,    a__      ,    a__     )			->   Callable[[], None]:






            '''simple docstring'''





            __snake_case      :Tuple 							=    self.config_dict[model_name]

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

            __snake_case      :str 							=    (
                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:
                      __snake_case      :Any 							=    """TF""" + config.architectures[0]  # prepend 'TF' for tensorflow model
                      __snake_case      :Dict 							=    __import__("""transformers"""      ,    fromlist=[model_class]     )
                      __snake_case      :List[str] 							=    getattr(a__      ,    a__     )
                      __snake_case      :Dict 							=    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:
                 __snake_case      :Union[str, Any] 							=    TF_MODEL_MAPPING[config.__class__](a__     )

            # encoder-decoder has vocab size saved differently
            __snake_case      :List[str] 							=    config.vocab_size if hasattr(a__      ,    """vocab_size"""     ) else config.encoder.vocab_size
            __snake_case      :str 							=    random_input_ids(a__      ,    a__      ,    a__     )

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

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

            __snake_case      :List[str] 							=    encoder_decoder_forward if config.is_encoder_decoder else encoder_forward

            return _inference



       def        __lowercase    (				self      ,    a__      ,    a__      ,    a__     )			->   Callable[[], None]:






            '''simple docstring'''





            __snake_case      :Optional[int] 							=    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."""     )

            __snake_case      :int 							=    (
                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:
                      __snake_case      :int 							=    """TF""" + config.architectures[0]  # prepend 'TF' for tensorflow model
                      __snake_case      :Union[str, Any] 							=    __import__("""transformers"""      ,    fromlist=[model_class]     )
                      __snake_case      :Optional[int] 							=    getattr(a__      ,    a__     )
                      __snake_case      :str 							=    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:
                 __snake_case      :List[str] 							=    TF_MODEL_WITH_LM_HEAD_MAPPING[config.__class__](a__     )

            # encoder-decoder has vocab size saved differently
            __snake_case      :str 							=    config.vocab_size if hasattr(a__      ,    """vocab_size"""     ) else config.encoder.vocab_size
            __snake_case      :List[Any] 							=    random_input_ids(a__      ,    a__      ,    a__     )

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

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

            __snake_case      :List[Any] 							=    encoder_decoder_train if config.is_encoder_decoder else encoder_train

            return _train



       def        __lowercase    (				self      ,    a__     )			->   float:






            '''simple docstring'''





            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(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
                      __snake_case      :str 							=    timeit.repeat(
                          a__      ,    repeat=self.args.repeat      ,    number=10      ,    )

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



       def        __lowercase    (				self      ,    a__     )			->   [Memory, MemorySummary]:






            '''simple docstring'''





            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."""     )
                           __snake_case      :int 							=    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."""     )
                                __snake_case      :Optional[int] 							=    """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()
                                __snake_case      :str 							=    nvml.nvmlDeviceGetHandleByIndex(self.args.device_idx     )
                                __snake_case      :str 							=    nvml.nvmlDeviceGetMemoryInfo(a__     )
                                __snake_case      :str 							=    meminfo.used
                                __snake_case      :str 							=    Memory(a__     )
                                # 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."""     )
                                __snake_case      :Optional[Any] 							=    None
                           else:
                                __snake_case      :Union[str, Any] 							=    measure_peak_memory_cpu(a__     )
                                __snake_case      :List[str] 							=    Memory(a__     ) if isinstance(a__      ,    a__     ) else memory_bytes
                      if self.args.trace_memory_line_by_line:
                           __snake_case      :Optional[Any] 							=    stop_memory_tracing(a__     )
                           if memory is None:
                                __snake_case      :Optional[Any] 							=    summary.total
                      else:
                           __snake_case      :List[str] 							=    None

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










# Lint as: python3
import sys
from collections.abc import Mapping
from typing import TYPE_CHECKING

import numpy as np
import pyarrow as pa

from .. import config
from ..utils.py_utils import map_nested
from .formatting import TensorFormatter


if TYPE_CHECKING:
     import torch




class       snake_case__ (				TensorFormatter[Mapping, "torch.Tensor", Mapping]):

       '''simple docstring'''



       def __init__(				self      ,    a__=None      ,    **a__     )			->   Tuple:






            '''simple docstring'''





            super().__init__(features=a__     )
            __snake_case      :int 							=    torch_tensor_kwargs
            import torch  # noqa import torch at initialization



       def        __lowercase    (				self      ,    a__     )			->   List[str]:






            '''simple docstring'''





            import torch

            if isinstance(a__      ,    a__     ) and column:
                 if all(
                     isinstance(a__      ,    torch.Tensor     ) and x.shape == column[0].shape and x.dtype == column[0].dtype
                     for x in column     ):
                      return torch.stack(a__     )
            return column



       def        __lowercase    (				self      ,    a__     )			->   Union[str, Any]:






            '''simple docstring'''





            import torch

            if isinstance(a__      ,    (str, bytes, type(a__     ))     ):
                 return value
            elif isinstance(a__      ,    (np.character, np.ndarray)     ) and np.issubdtype(value.dtype      ,    np.character     ):
                 return value.tolist()

            __snake_case      :Optional[int] 							=    {}

            if isinstance(a__      ,    (np.number, np.ndarray)     ) and np.issubdtype(value.dtype      ,    np.integer     ):
                 __snake_case      :List[Any] 							=    {"""dtype""": torch.intaa}
            elif isinstance(a__      ,    (np.number, np.ndarray)     ) and np.issubdtype(value.dtype      ,    np.floating     ):
                 __snake_case      :Tuple 							=    {"""dtype""": torch.floataa}
            elif config.PIL_AVAILABLE and "PIL" in sys.modules:
                 import PIL.Image

                 if isinstance(a__      ,    PIL.Image.Image     ):
                      __snake_case      :Union[str, Any] 							=    np.asarray(a__     )
            return torch.tensor(a__      ,    **{**default_dtype, **self.torch_tensor_kwargs}     )



       def        __lowercase    (				self      ,    a__     )			->   str:






            '''simple docstring'''





            import torch

            # support for torch, tf, jax etc.
            if hasattr(a__      ,    """__array__"""     ) and not isinstance(a__      ,    torch.Tensor     ):
                 __snake_case      :Optional[Any] 							=    data_struct.__array__()
            # support for nested types like struct of list of struct
            if isinstance(a__      ,    np.ndarray     ):
                 if data_struct.dtype == object:  # torch tensors cannot be instantied from an array of objects
                      return self._consolidate([self.recursive_tensorize(a__     ) for substruct in data_struct]     )
            elif isinstance(a__      ,    (list, tuple)     ):
                 return self._consolidate([self.recursive_tensorize(a__     ) for substruct in data_struct]     )
            return self._tensorize(a__     )



       def        __lowercase    (				self      ,    a__     )			->   Union[str, Any]:






            '''simple docstring'''





            return map_nested(self._recursive_tensorize      ,    a__      ,    map_list=a__     )



       def        __lowercase    (				self      ,    a__     )			->   Mapping:






            '''simple docstring'''





            __snake_case      :Tuple 							=    self.numpy_arrow_extractor().extract_row(a__     )
            __snake_case      :Any 							=    self.python_features_decoder.decode_row(a__     )
            return self.recursive_tensorize(a__     )



       def        __lowercase    (				self      ,    a__     )			->   "torch.Tensor":






            '''simple docstring'''





            __snake_case      :List[str] 							=    self.numpy_arrow_extractor().extract_column(a__     )
            __snake_case      :List[Any] 							=    self.python_features_decoder.decode_column(a__      ,    pa_table.column_names[0]     )
            __snake_case      :Optional[Any] 							=    self.recursive_tensorize(a__     )
            __snake_case      :Any 							=    self._consolidate(a__     )
            return column



       def        __lowercase    (				self      ,    a__     )			->   Mapping:






            '''simple docstring'''





            __snake_case      :Optional[int] 							=    self.numpy_arrow_extractor().extract_batch(a__     )
            __snake_case      :Tuple 							=    self.python_features_decoder.decode_batch(a__     )
            __snake_case      :Tuple 							=    self.recursive_tensorize(a__     )
            for column_name in batch:
                 __snake_case      :str 							=    self._consolidate(batch[column_name]     )
            return batch


