



'''simple docstring'''





import asyncio
import os
import shutil
import subprocess
import sys
import tempfile
import unittest
from distutils.util import strtobool
from functools import partial
from pathlib import Path
from typing import List, Union
from unittest import mock

import torch

from ..state import AcceleratorState, PartialState
from ..utils import (
    gather,
    is_bnb_available,
    is_comet_ml_available,
    is_datasets_available,
    is_deepspeed_available,
    is_mps_available,
    is_safetensors_available,
    is_tensorboard_available,
    is_torch_version,
    is_tpu_available,
    is_transformers_available,
    is_wandb_available,
    is_xpu_available,
)





def 						__snake_case(				_lowerCAmelCase     ,   _lowerCAmelCase=False		)		-> List[str]:
      try:
            snake_case__  :    Optional[int]    						=      os.environ[key]
      except KeyError:
            # KEY isn't set, default to `default`.
            snake_case__  :    Dict    						=      default
      else:
            # KEY is set, convert it to True or False.
            try:
                  snake_case__  :    List[str]    						=      strtobool(_lowerCAmelCase		)
            except ValueError:
                  # More values are supported, but let's keep the message simple.
                  raise ValueError(f"If set, {key} must be yes or no."		)
      return _value


__a          =		parse_flag_from_env("RUN_SLOW", default=False)





def 						__snake_case(				_lowerCAmelCase		)		-> List[Any]:
      return unittest.skip("""Test was skipped"""		)(_lowerCAmelCase		)





def 						__snake_case(				_lowerCAmelCase		)		-> Union[str, Any]:
      return unittest.skipUnless(_run_slow_tests     ,   """test is slow"""		)(_lowerCAmelCase		)





def 						__snake_case(				_lowerCAmelCase		)		-> List[str]:
      return unittest.skipUnless(not torch.cuda.is_available()     ,   """test requires only a CPU"""		)(_lowerCAmelCase		)





def 						__snake_case(				_lowerCAmelCase		)		-> Any:
      return unittest.skipUnless(torch.cuda.is_available()     ,   """test requires a GPU"""		)(_lowerCAmelCase		)





def 						__snake_case(				_lowerCAmelCase		)		-> int:
      return unittest.skipUnless(is_xpu_available()     ,   """test requires a XPU"""		)(_lowerCAmelCase		)





def 						__snake_case(				_lowerCAmelCase		)		-> Union[str, Any]:
      return unittest.skipUnless(is_mps_available()     ,   """test requires a `mps` backend support in `torch`"""		)(_lowerCAmelCase		)





def 						__snake_case(				_lowerCAmelCase		)		-> List[str]:
      return unittest.skipUnless(
          is_transformers_available() and is_datasets_available()     ,   """test requires the Hugging Face suite"""		)(_lowerCAmelCase		)





def 						__snake_case(				_lowerCAmelCase		)		-> List[Any]:
      return unittest.skipUnless(is_bnb_available()     ,   """test requires the bitsandbytes library"""		)(_lowerCAmelCase		)





def 						__snake_case(				_lowerCAmelCase		)		-> Any:
      return unittest.skipUnless(is_tpu_available()     ,   """test requires TPU"""		)(_lowerCAmelCase		)





def 						__snake_case(				_lowerCAmelCase		)		-> Union[str, Any]:
      return unittest.skipUnless(torch.cuda.device_count() == 1     ,   """test requires a GPU"""		)(_lowerCAmelCase		)





def 						__snake_case(				_lowerCAmelCase		)		-> List[str]:
      return unittest.skipUnless(torch.xpu.device_count() == 1     ,   """test requires a XPU"""		)(_lowerCAmelCase		)





def 						__snake_case(				_lowerCAmelCase		)		-> Dict:
      return unittest.skipUnless(torch.cuda.device_count() > 1     ,   """test requires multiple GPUs"""		)(_lowerCAmelCase		)





def 						__snake_case(				_lowerCAmelCase		)		-> List[str]:
      return unittest.skipUnless(torch.xpu.device_count() > 1     ,   """test requires multiple XPUs"""		)(_lowerCAmelCase		)





def 						__snake_case(				_lowerCAmelCase		)		-> List[Any]:
      return unittest.skipUnless(is_safetensors_available()     ,   """test requires safetensors"""		)(_lowerCAmelCase		)





def 						__snake_case(				_lowerCAmelCase		)		-> Union[str, Any]:
      return unittest.skipUnless(is_deepspeed_available()     ,   """test requires DeepSpeed"""		)(_lowerCAmelCase		)





def 						__snake_case(				_lowerCAmelCase		)		-> Optional[int]:
      return unittest.skipUnless(is_torch_version(""">="""     ,   """1.12.0"""		)     ,   """test requires torch version >= 1.12.0"""		)(_lowerCAmelCase		)





def 						__snake_case(				_lowerCAmelCase=None     ,   _lowerCAmelCase=None		)		-> Any:
      if test_case is None:
            return partial(_lowerCAmelCase     ,   version=_lowerCAmelCase		)
      return unittest.skipUnless(is_torch_version(""">="""     ,   _lowerCAmelCase		)     ,   f"test requires torch version >= {version}"		)(_lowerCAmelCase		)





def 						__snake_case(				_lowerCAmelCase		)		-> int:
      return unittest.skipUnless(is_tensorboard_available()     ,   """test requires Tensorboard"""		)(_lowerCAmelCase		)





def 						__snake_case(				_lowerCAmelCase		)		-> Any:
      return unittest.skipUnless(is_wandb_available()     ,   """test requires wandb"""		)(_lowerCAmelCase		)





def 						__snake_case(				_lowerCAmelCase		)		-> Optional[Any]:
      return unittest.skipUnless(is_comet_ml_available()     ,   """test requires comet_ml"""		)(_lowerCAmelCase		)


__a          =		(
    any([is_wandb_available(), is_tensorboard_available()]) and not is_comet_ml_available()
)





def 						__snake_case(				_lowerCAmelCase		)		-> int:
      return unittest.skipUnless(
          _atleast_one_tracker_available     ,   """test requires at least one tracker to be available and for `comet_ml` to not be installed"""     ,   )(_lowerCAmelCase		)







class     UpperCAmelCase_       (       unittest.TestCase	):
    """simple docstring"""







    lowercase					=		True




    @classmethod
    def lowerCamelCase       (    cls					:     Any						):
          snake_case__  :    Union[str, Any]    						=      tempfile.mkdtemp()




    @classmethod
    def lowerCamelCase       (    cls					:     int						):
          if os.path.exists(cls.tmpdir						):
                shutil.rmtree(cls.tmpdir						)




    def lowerCamelCase       (    self					:     Tuple						):
          if self.clear_on_setup:
                for path in Path(self.tmpdir						).glob("""**/*"""						):
                      if path.is_file():
                            path.unlink()
                      elif path.is_dir():
                            shutil.rmtree(snake_case_						)







class     UpperCAmelCase_       (       unittest.TestCase	):
    """simple docstring"""







    def lowerCamelCase       (    self					:     Any						):
          super().tearDown()
          # Reset the state of the AcceleratorState singleton.
          AcceleratorState._reset_state()
          PartialState._reset_state()







class     UpperCAmelCase_       (       unittest.TestCase	):
    """simple docstring"""







    def lowerCamelCase       (    self					:     Optional[int] ,     snake_case_					:     Union[mock.Mock, List[mock.Mock]]						):
          snake_case__  :    Dict    						=      mocks if isinstance(snake_case_ ,     (tuple, list)						) else [mocks]
          for m in self.mocks:
                m.start()
                self.addCleanup(m.stop						)





def 						__snake_case(				_lowerCAmelCase		)		-> int:
      snake_case__  :    Union[str, Any]    						=      AcceleratorState()
      snake_case__  :    int    						=      tensor[None].clone().to(state.device		)
      snake_case__  :    Optional[Any]    						=      gather(_lowerCAmelCase		).cpu()
      snake_case__  :    str    						=      tensor[0].cpu()
      for i in range(tensors.shape[0]		):
            if not torch.equal(tensors[i]     ,   _lowerCAmelCase		):
                  return False
      return True







class     UpperCAmelCase_       :
    """simple docstring"""







    def __init__(    self					:     List[Any] ,     snake_case_					:     Tuple ,     snake_case_					:     Union[str, Any] ,     snake_case_					:     List[Any]						):
          snake_case__  :    List[Any]    						=      returncode
          snake_case__  :    List[Any]    						=      stdout
          snake_case__  :    List[Any]    						=      stderr





async def 						__snake_case(				_lowerCAmelCase     ,   _lowerCAmelCase		)		-> Optional[int]:
      while True:
            snake_case__  :    Optional[int]    						=      await stream.readline()
            if line:
                  callback(_lowerCAmelCase		)
            else:
                  break





async def 						__snake_case(				_lowerCAmelCase     ,   _lowerCAmelCase=None     ,   _lowerCAmelCase=None     ,   _lowerCAmelCase=None     ,   _lowerCAmelCase=False     ,   _lowerCAmelCase=False		)		-> _RunOutput:
      if echo:
            print("""\nRunning: """     ,   """ """.join(_lowerCAmelCase		)		)

      snake_case__  :    Any    						=      await asyncio.create_subprocess_exec(
          cmd[0]     ,   *cmd[1:]     ,   stdin=_lowerCAmelCase     ,   stdout=asyncio.subprocess.PIPE     ,   stderr=asyncio.subprocess.PIPE     ,   env=_lowerCAmelCase     ,   )

      # note: there is a warning for a possible deadlock when using `wait` with huge amounts of data in the pipe
      # https://docs.python.org/3/library/asyncio-subprocess.html#asyncio.asyncio.subprocess.Process.wait
      #
      # If it starts hanging, will need to switch to the following code. The problem is that no data
      # will be seen until it's done and if it hangs for example there will be no debug info.
      # out, err = await p.communicate()
      # return _RunOutput(p.returncode, out, err)

      snake_case__  :    List[Any]    						=      []
      snake_case__  :    Any    						=      []

      def tee(_lowerCAmelCase     ,   _lowerCAmelCase     ,   _lowerCAmelCase     ,   _lowerCAmelCase=""		):
            snake_case__  :    str    						=      line.decode("""utf-8"""		).rstrip()
            sink.append(_lowerCAmelCase		)
            if not quiet:
                  print(_lowerCAmelCase     ,   _lowerCAmelCase     ,   file=_lowerCAmelCase		)

    # XXX: the timeout doesn't seem to make any difference here
      await asyncio.wait(
          [
              asyncio.create_task(_read_stream(p.stdout     ,   lambda _lowerCAmelCase		: tee(_lowerCAmelCase     ,   _lowerCAmelCase     ,   sys.stdout     ,   label="""stdout:"""		)		)		),
              asyncio.create_task(_read_stream(p.stderr     ,   lambda _lowerCAmelCase		: tee(_lowerCAmelCase     ,   _lowerCAmelCase     ,   sys.stderr     ,   label="""stderr:"""		)		)		),
          ]     ,   timeout=_lowerCAmelCase     ,   )
      return _RunOutput(await p.wait()     ,   _lowerCAmelCase     ,   _lowerCAmelCase		)





def 						__snake_case(				_lowerCAmelCase     ,   _lowerCAmelCase=None     ,   _lowerCAmelCase=None     ,   _lowerCAmelCase=180     ,   _lowerCAmelCase=False     ,   _lowerCAmelCase=True		)		-> _RunOutput:
      snake_case__  :    Optional[Any]    						=      asyncio.get_event_loop()
      snake_case__  :    List[Any]    						=      loop.run_until_complete(
          _stream_subprocess(_lowerCAmelCase     ,   env=_lowerCAmelCase     ,   stdin=_lowerCAmelCase     ,   timeout=_lowerCAmelCase     ,   quiet=_lowerCAmelCase     ,   echo=_lowerCAmelCase		)		)

      snake_case__  :    List[Any]    						=      """ """.join(_lowerCAmelCase		)
      if result.returncode > 0:
            snake_case__  :    List[str]    						=      """\n""".join(result.stderr		)
            raise RuntimeError(
                f"'{cmd_str}' failed with returncode {result.returncode}\n\n"
                f"The combined stderr from workers follows:\n{stderr}"		)

      return result







class     UpperCAmelCase_       (       _a	):
    """simple docstring"""







    pass





def 						__snake_case(				_lowerCAmelCase     ,   _lowerCAmelCase=False		)		-> List[Any]:
      try:
            snake_case__  :    List[Any]    						=      subprocess.check_output(_lowerCAmelCase     ,   stderr=subprocess.STDOUT		)
            if return_stdout:
                  if hasattr(_lowerCAmelCase     ,   """decode"""		):
                        snake_case__  :    str    						=      output.decode("""utf-8"""		)
                  return output
      except subprocess.CalledProcessError as e:
            raise SubprocessCallException(
                f"Command `{' '.join(_lowerCAmelCase		)}` failed with the following error:\n\n{e.output.decode()}"		) from e






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

snake_case_ : Tuple    		=       logging.get_logger(__name__)


def    A						(__A   :    bool   ,				__A   :    bool       )   ->      Optional[Any]:







     """simple docstring"""


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

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

          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						(__A   :    int   ,				__A   :    int   ,				__A   :    int       )   ->      ["tf.Tensor"]:







     """simple docstring"""


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







class __snake_case			(			a		):
   UpperCAmelCase__  :    TensorFlowBenchmarkArguments
   UpperCAmelCase__  :    PretrainedConfig
   UpperCAmelCase__  :    str          =  "TensorFlow"







   @property
   def lowerCamelCase						(      self		:						List[str]):

        """simple docstring"""


        return tf.__version__







   def lowerCamelCase						(      self		:						Dict					,						_snake_case		:						str					,						_snake_case		:						int					,						_snake_case		:						int):

        """simple docstring"""


        UpperCAmelCase_          =							self.args.strategy
        if strategy is None:
             raise ValueError('''A device strategy has to be initialized before using TensorFlow.''')
        UpperCAmelCase_          =							self._prepare_inference_func(_snake_case					,						_snake_case					,						_snake_case)
        return self._measure_speed(_inference)







   def lowerCamelCase						(      self		:						Any					,						_snake_case		:						str					,						_snake_case		:						int					,						_snake_case		:						int):

        """simple docstring"""


        UpperCAmelCase_          =							self.args.strategy
        if strategy is None:
             raise ValueError('''A device strategy has to be initialized before using TensorFlow.''')
        UpperCAmelCase_          =							self._prepare_train_func(_snake_case					,						_snake_case					,						_snake_case)
        return self._measure_speed(_train)







   def lowerCamelCase						(      self		:						Any					,						_snake_case		:						str					,						_snake_case		:						int					,						_snake_case		:						int):

        """simple docstring"""


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







   def lowerCamelCase						(      self		:						Optional[Any]					,						_snake_case		:						str					,						_snake_case		:						int					,						_snake_case		:						int):

        """simple docstring"""


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

        UpperCAmelCase_          =							self._prepare_train_func(_snake_case					,						_snake_case					,						_snake_case)
        return self._measure_memory(_train)







   def lowerCamelCase						(      self		:						Optional[int]					,						_snake_case		:						str					,						_snake_case		:						int					,						_snake_case		:						int):

        """simple docstring"""


        UpperCAmelCase_          =							self.config_dict[model_name]

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

        UpperCAmelCase_          =							(
            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_          =							'''TF''' + config.architectures[0]  # prepend 'TF' for tensorflow model
                  UpperCAmelCase_          =							__import__('''transformers'''					,						fromlist=[model_class])
                  UpperCAmelCase_          =							getattr(_snake_case					,						_snake_case)
                  UpperCAmelCase_          =							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_          =							TF_MODEL_MAPPING[config.__class__](_snake_case)

        # encoder-decoder has vocab size saved differently
        UpperCAmelCase_          =							config.vocab_size if hasattr(_snake_case					,						'''vocab_size''') else config.encoder.vocab_size
        UpperCAmelCase_          =							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_          =							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):

        """simple docstring"""


        UpperCAmelCase_          =							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_          =							(
            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_          =							'''TF''' + config.architectures[0]  # prepend 'TF' for tensorflow model
                  UpperCAmelCase_          =							__import__('''transformers'''					,						fromlist=[model_class])
                  UpperCAmelCase_          =							getattr(_snake_case					,						_snake_case)
                  UpperCAmelCase_          =							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_          =							TF_MODEL_WITH_LM_HEAD_MAPPING[config.__class__](_snake_case)

        # encoder-decoder has vocab size saved differently
        UpperCAmelCase_          =							config.vocab_size if hasattr(_snake_case					,						'''vocab_size''') else config.encoder.vocab_size
        UpperCAmelCase_          =							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_          =							model(_snake_case					,						decoder_input_ids=_snake_case					,						labels=_snake_case					,						training=_snake_case)[0]
             UpperCAmelCase_          =							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_          =							model(_snake_case					,						labels=_snake_case					,						training=_snake_case)[0]
             UpperCAmelCase_          =							tf.gradients(_snake_case					,						model.trainable_variables)
             return gradients

        UpperCAmelCase_          =							encoder_decoder_train if config.is_encoder_decoder else encoder_train

        return _train







   def lowerCamelCase						(      self		:						Any					,						_snake_case		:						Optional[Any]):

        """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(_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_          =							timeit.repeat(
                      _snake_case					,						repeat=self.args.repeat					,						number=10					,						)

                  return min(_snake_case) / 1_0.0
             except ResourceExhaustedError as e:
                  self.print_fn(F"""Doesn't fit on GPU. {e}""")







   def lowerCamelCase						(      self		:						Dict					,						_snake_case		:						Callable[[], None]):

        """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.''')
                       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 `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_          =							'''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(_snake_case)
                            UpperCAmelCase_          =							meminfo.used
                            UpperCAmelCase_          =							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_          =							None
                       else:
                            UpperCAmelCase_          =							measure_peak_memory_cpu(_snake_case)
                            UpperCAmelCase_          =							Memory(_snake_case) if isinstance(_snake_case					,						_snake_case) else memory_bytes
                  if self.args.trace_memory_line_by_line:
                       UpperCAmelCase_          =							stop_memory_tracing(_snake_case)
                       if memory is None:
                            UpperCAmelCase_          =							summary.total
                  else:
                       UpperCAmelCase_          =							None

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






