


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

__UpperCAmelCase      :Dict			    =       logging.get_logger(__name__)




def      _a     (						_lowercase :     bool      , _lowercase :     bool  ):





     '''simple docstring'''






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

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

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





     '''simple docstring'''






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



class      a    (		_a	):


     """simple docstring"""






     SCREAMING_SNAKE_CASE	:			TensorFlowBenchmarkArguments
     SCREAMING_SNAKE_CASE	:			PretrainedConfig
     SCREAMING_SNAKE_CASE	:			str							       =       "TensorFlow"

     @property
     def 			lowerCamelCase__			(    self					:		Optional[Any]      )						->							List[Any]:
          return tf.__version__

     def 			lowerCamelCase__			(    self					:		Union[str, Any]							,			snake_case					:		str							,			snake_case					:		int							,			snake_case					:		int      )						->							float:
          # initialize GPU on separate process
          __UpperCAmelCase     :			Union[str, Any]  							=      self.args.strategy
          if strategy is None:
               raise ValueError('''A device strategy has to be initialized before using TensorFlow.'''      )
          __UpperCAmelCase     :			Tuple  							=      self._prepare_inference_func(snake_case							,			snake_case							,			snake_case      )
          return self._measure_speed(_inference      )

     def 			lowerCamelCase__			(    self					:		int							,			snake_case					:		str							,			snake_case					:		int							,			snake_case					:		int      )						->							float:
          __UpperCAmelCase     :			int  							=      self.args.strategy
          if strategy is None:
               raise ValueError('''A device strategy has to be initialized before using TensorFlow.'''      )
          __UpperCAmelCase     :			Union[str, Any]  							=      self._prepare_train_func(snake_case							,			snake_case							,			snake_case      )
          return self._measure_speed(_train      )

     def 			lowerCamelCase__			(    self					:		Tuple							,			snake_case					:		str							,			snake_case					:		int							,			snake_case					:		int      )						->							[Memory, Optional[MemorySummary]]:
          # initialize GPU on separate process
          if self.args.is_gpu:
               tf.config.experimental.set_memory_growth(self.args.gpu_list[self.args.device_idx]							,			snake_case      )
          __UpperCAmelCase     :			str  							=      self.args.strategy
          if strategy is None:
               raise ValueError('''A device strategy has to be initialized before using TensorFlow.'''      )
          __UpperCAmelCase     :			Dict  							=      self._prepare_inference_func(snake_case							,			snake_case							,			snake_case      )
          return self._measure_memory(_inference      )

     def 			lowerCamelCase__			(    self					:		Tuple							,			snake_case					:		str							,			snake_case					:		int							,			snake_case					:		int      )						->							[Memory, Optional[MemorySummary]]:
          if self.args.is_gpu:
               tf.config.experimental.set_memory_growth(self.args.gpu_list[self.args.device_idx]							,			snake_case      )
          __UpperCAmelCase     :			Optional[Any]  							=      self.args.strategy
          if strategy is None:
               raise ValueError('''A device strategy has to be initialized before using TensorFlow.'''      )

          __UpperCAmelCase     :			Optional[int]  							=      self._prepare_train_func(snake_case							,			snake_case							,			snake_case      )
          return self._measure_memory(_train      )

     def 			lowerCamelCase__			(    self					:		Tuple							,			snake_case					:		str							,			snake_case					:		int							,			snake_case					:		int      )						->							Callable[[], None]:
          __UpperCAmelCase     :			Optional[Any]  							=      self.config_dict[model_name]

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

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

          # encoder-decoder has vocab size saved differently
          __UpperCAmelCase     :			Dict  							=      config.vocab_size if hasattr(snake_case							,			'''vocab_size'''      ) else config.encoder.vocab_size
          __UpperCAmelCase     :			Dict  							=      random_input_ids(snake_case							,			snake_case							,			snake_case      )

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

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

          __UpperCAmelCase     :			Dict  							=      encoder_decoder_forward if config.is_encoder_decoder else encoder_forward

          return _inference

     def 			lowerCamelCase__			(    self					:		Optional[Any]							,			snake_case					:		str							,			snake_case					:		int							,			snake_case					:		int      )						->							Callable[[], None]:
          __UpperCAmelCase     :			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.'''      )

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

          # encoder-decoder has vocab size saved differently
          __UpperCAmelCase     :			List[str]  							=      config.vocab_size if hasattr(snake_case							,			'''vocab_size'''      ) else config.encoder.vocab_size
          __UpperCAmelCase     :			Optional[Any]  							=      random_input_ids(snake_case							,			snake_case							,			snake_case      )

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

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

          __UpperCAmelCase     :			List[str]  							=      encoder_decoder_train if config.is_encoder_decoder else encoder_train

          return _train

     def 			lowerCamelCase__			(    self					:		str							,			snake_case					:		Optional[int]      )						->							float:
          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(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
                    __UpperCAmelCase     :			Optional[int]  							=      timeit.repeat(
                        snake_case							,			repeat=self.args.repeat							,			number=10							,			)

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






     def 			lowerCamelCase__			(    self					:		Union[str, Any]							,			snake_case					:		Callable[[], None]      )						->							[Memory, MemorySummary]:
          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.'''      )
                         __UpperCAmelCase     :			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.'''      )
                              __UpperCAmelCase     :			Dict  							=      '''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     :			Tuple  							=      nvml.nvmlDeviceGetHandleByIndex(self.args.device_idx      )
                              __UpperCAmelCase     :			int  							=      nvml.nvmlDeviceGetMemoryInfo(snake_case      )
                              __UpperCAmelCase     :			Optional[Any]  							=      meminfo.used
                              __UpperCAmelCase     :			int  							=      Memory(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.'''      )
                              __UpperCAmelCase     :			int  							=      None
                         else:
                              __UpperCAmelCase     :			Optional[Any]  							=      measure_peak_memory_cpu(snake_case      )
                              __UpperCAmelCase     :			List[str]  							=      Memory(snake_case      ) if isinstance(snake_case							,			snake_case      ) else memory_bytes
                    if self.args.trace_memory_line_by_line:
                         __UpperCAmelCase     :			Tuple  							=      stop_memory_tracing(snake_case      )
                         if memory is None:
                              __UpperCAmelCase     :			str  							=      summary.total
                    else:
                         __UpperCAmelCase     :			Optional[int]  							=      None

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



'''simple docstring'''



# Copyright 2021 The HuggingFace Team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from pathlib import Path

import torch

from ...utils import is_npu_available, is_xpu_available
from .config_args import ClusterConfig, default_json_config_file
from .config_utils import SubcommandHelpFormatter


__UpperCAmelCase      :Tuple			    =       "Create a default config file for Accelerate with only a few flags set."




def      _a     (						_lowercase :     List[Any]="no"      , _lowercase :     str = default_json_config_file      , _lowercase :     bool = False  ):





     '''simple docstring'''






     __UpperCAmelCase     :			Dict  							=      Path(_lowercase  )
     path.parent.mkdir(parents=_lowercase      , exist_ok=_lowercase  )
     if path.exists():
          print(
              F'Configuration already exists at {save_location}, will not override. Run `accelerate config` manually or pass a different `save_location`.'  )
          return False
     __UpperCAmelCase     :			List[str]  							=      mixed_precision.lower()
     if mixed_precision not in ["no", "fp16", "bf16", "fp8"]:
          raise ValueError(
              F'`mixed_precision` should be one of \'no\', \'fp16\', \'bf16\', or \'fp8\'. Received {mixed_precision}'  )
     __UpperCAmelCase     :			int  							=      {
         '''compute_environment''': '''LOCAL_MACHINE''',
         '''mixed_precision''': mixed_precision,
     }
     if torch.cuda.is_available():
          __UpperCAmelCase     :			Optional[Any]  							=      torch.cuda.device_count()
          __UpperCAmelCase     :			List[str]  							=      num_gpus
          __UpperCAmelCase     :			int  							=      False
          if num_gpus > 1:
               __UpperCAmelCase     :			Any  							=      '''MULTI_GPU'''
          else:
               __UpperCAmelCase     :			int  							=      '''NO'''
     elif is_xpu_available() and use_xpu:
          __UpperCAmelCase     :			List[Any]  							=      torch.xpu.device_count()
          __UpperCAmelCase     :			List[Any]  							=      num_xpus
          __UpperCAmelCase     :			Optional[int]  							=      False
          if num_xpus > 1:
               __UpperCAmelCase     :			Any  							=      '''MULTI_XPU'''
          else:
               __UpperCAmelCase     :			Optional[Any]  							=      '''NO'''
     elif is_npu_available():
          __UpperCAmelCase     :			Dict  							=      torch.npu.device_count()
          __UpperCAmelCase     :			Any  							=      num_npus
          __UpperCAmelCase     :			Any  							=      False
          if num_npus > 1:
               __UpperCAmelCase     :			Dict  							=      '''MULTI_NPU'''
          else:
               __UpperCAmelCase     :			Optional[int]  							=      '''NO'''
     else:
          __UpperCAmelCase     :			List[str]  							=      0
          __UpperCAmelCase     :			Dict  							=      True
          __UpperCAmelCase     :			Dict  							=      1
          __UpperCAmelCase     :			Tuple  							=      '''NO'''
     __UpperCAmelCase     :			List[Any]  							=      ClusterConfig(**_lowercase  )
     config.to_json_file(_lowercase  )
     return path




def      _a     (						_lowercase :     Union[str, Any]      , _lowercase :     str  ):





     '''simple docstring'''






     __UpperCAmelCase     :			Optional[int]  							=      parser.add_parser('''default'''      , parents=_lowercase      , help=_lowercase      , formatter_class=_lowercase  )
     parser.add_argument(
         '''--config_file'''      , default=_lowercase      , help=(
             '''The path to use to store the config file. Will default to a file named default_config.yaml in the cache '''
             '''location, which is the content of the environment `HF_HOME` suffixed with \'accelerate\', or if you don\'t have '''
             '''such an environment variable, your cache directory (\'~/.cache\' or the content of `XDG_CACHE_HOME`) suffixed '''
             '''with \'huggingface\'.'''
         )      , dest='''save_location'''      , )

     parser.add_argument(
         '''--mixed_precision'''      , choices=['''no''', '''fp16''', '''bf16''']      , type=_lowercase      , help='''Whether or not to use mixed precision training. '''
         '''Choose between FP16 and BF16 (bfloat16) training. '''
         '''BF16 training is only supported on Nvidia Ampere GPUs and PyTorch 1.10 or later.'''      , default='''no'''      , )
     parser.set_defaults(func=_lowercase  )
     return parser




def      _a     (						_lowercase :     List[Any]  ):





     '''simple docstring'''






     __UpperCAmelCase     :			str  							=      write_basic_config(args.mixed_precision      , args.save_location  )
     if config_file:
          print(F'accelerate configuration saved at {config_file}'  )