


"""simple docstring"""


from importlib import import_module

from .logging import get_logger


UpperCamelCase						:				Dict             =      get_logger(__name__)



class 			lowerCamelCase__						:







						def __init__(							self   :    Optional[int]			,			_lowercase   :    List[str]			,			_lowercase   :    str=None		):
								A					       = attrs or []
								if module is not None:
										for key in module.__dict__:
												if key in attrs or not key.startswith('__'		):
														setattr(self			,			_lowercase			,			getattr(_lowercase			,			_lowercase		)		)
								A					       = module._original_module if isinstance(_lowercase			,			_PatchedModuleObj		) else module



class 			lowerCamelCase__						:
						lowerCAmelCase       =     []







						def __init__(							self   :    Optional[Any]			,			_lowercase   :    List[Any]			,			_lowercase   :    str			,			_lowercase   :    List[str]			,			_lowercase   :    Union[str, Any]=None		):
								A					       = obj
								A					       = target
								A					       = new
								A					       = target.split('.'		)[0]
								A					       = {}
								A					       = attrs or []







						def __enter__(							self   :    List[str]		):
								*A       , A					       = self.target.split('.'		)

								# Patch modules:
								# it's used to patch attributes of submodules like "os.path.join";
								# in this case we need to patch "os" and "os.path"

								for i in range(len(_lowercase		)		):
										try:
												A					       = import_module('.'.join(submodules[: i + 1]		)		)
										except ModuleNotFoundError:
												continue
										# We iterate over all the globals in self.obj in case we find "os" or "os.path"
										for attr in self.obj.__dir__():
												A					       = getattr(self.obj			,			_lowercase		)
												# We don't check for the name of the global, but rather if its value *is* "os" or "os.path".
												# This allows to patch renamed modules like "from os import path as ospath".
												if obj_attr is submodule or (
												    (isinstance(_lowercase			,			_PatchedModuleObj		) and obj_attr._original_module is submodule)
												):
														A					       = obj_attr
														# patch at top level
														setattr(self.obj			,			_lowercase			,			_PatchedModuleObj(_lowercase			,			attrs=self.attrs		)		)
														A					       = getattr(self.obj			,			_lowercase		)
														# construct lower levels patches
														for key in submodules[i + 1 :]:
																setattr(_lowercase			,			_lowercase			,			_PatchedModuleObj(getattr(_lowercase			,			_lowercase			,			_lowercase		)			,			attrs=self.attrs		)		)
																A					       = getattr(_lowercase			,			_lowercase		)
														# finally set the target attribute
														setattr(_lowercase			,			_lowercase			,			self.new		)

        # Patch attribute itself:
        # it's used for builtins like "open",
        # and also to patch "os.path.join" we may also need to patch "join"
        # itself if it was imported as "from os.path import join".

								if submodules:  # if it's an attribute of a submodule like "os.path.join"
										try:
												A					       = getattr(import_module('.'.join(_lowercase		)		)			,			_lowercase		)
										except (AttributeError, ModuleNotFoundError):
												return
										# We iterate over all the globals in self.obj in case we find "os.path.join"
										for attr in self.obj.__dir__():
												# We don't check for the name of the global, but rather if its value *is* "os.path.join".
												# This allows to patch renamed attributes like "from os.path import join as pjoin".
												if getattr(self.obj			,			_lowercase		) is attr_value:
														A					       = getattr(self.obj			,			_lowercase		)
														setattr(self.obj			,			_lowercase			,			self.new		)
								elif target_attr in globals()["__builtins__"]:  # if it'a s builtin like "open"
										A					       = globals()['__builtins__'][target_attr]
										setattr(self.obj			,			_lowercase			,			self.new		)
								else:
										raise RuntimeError(f'Tried to patch attribute {target_attr} instead of a submodule.'		)







						def __exit__(							self   :    List[Any]			,			*_lowercase   :    Dict		):
								for attr in list(self.original		):
										setattr(self.obj			,			_lowercase			,			self.original.pop(_lowercase		)		)







						def __a						(							self   :    List[str]		):
								self.__enter__()
								self._active_patches.append(self		)







						def __a						(							self   :    List[Any]		):
								try:
										self._active_patches.remove(self		)
								except ValueError:
										# If the patch hasn't been started this will fail
										return None

								return self.__exit__()









"""simple docstring"""


from dataclasses import dataclass, field
from typing import Tuple

from ..utils import cached_property, is_tf_available, logging, requires_backends
from .benchmark_args_utils import BenchmarkArguments


if is_tf_available():
	import tensorflow as tf


UpperCamelCase						:				Optional[Any]             =      logging.get_logger(__name__)



@dataclass
class 			lowerCamelCase__						(   UpperCAmelCase_			):
						lowerCAmelCase       =     [
						    """no_inference""",
						    """no_cuda""",
						    """no_tpu""",
						    """no_speed""",
						    """no_memory""",
						    """no_env_print""",
						    """no_multi_process""",
						]







						def __init__(							self   :    str			,			**_lowercase   :    Union[str, Any]		):
								for deprecated_arg in self.deprecated_args:
										if deprecated_arg in kwargs:
												A					       = deprecated_arg[3:]
												A					       = not kwargs.pop(_lowercase		)
												logger.warning(
												    f'{deprecated_arg} is depreciated. Please use --no-{positive_arg} or'
												    f' {positive_arg}={kwargs[positive_arg]}'		)
								A					       = kwargs.pop('tpu_name'			,			self.tpu_name		)
								A					       = kwargs.pop('device_idx'			,			self.device_idx		)
								A					       = kwargs.pop('eager_mode'			,			self.eager_mode		)
								A					       = kwargs.pop('use_xla'			,			self.use_xla		)
								super().__init__(**_lowercase		)

						lowerCAmelCase       =     field(
						    default=UpperCAmelCase_							,    metadata={"""help""": """Name of TPU"""}							,    )
						lowerCAmelCase       =     field(
						    default=0							,    metadata={"""help""": """CPU / GPU device index. Defaults to 0."""}							,    )
						lowerCAmelCase       =     field(default=UpperCAmelCase_							,    metadata={"""help""": """Benchmark models in eager model."""}			)
						lowerCAmelCase       =     field(
						    default=UpperCAmelCase_							,    metadata={
						        """help""": """Benchmark models using XLA JIT compilation. Note that `eager_model` has to be set to `False`."""
						    }							,    )







						@cached_property
						def __a						(							self   :    Optional[Any]		):
								requires_backends(self			,			['tf']		)
								A					       = None
								if self.tpu:
										try:
												if self.tpu_name:
														A					       = tf.distribute.cluster_resolver.TPUClusterResolver(self.tpu_name		)
												else:
														A					       = tf.distribute.cluster_resolver.TPUClusterResolver()
										except ValueError:
												A					       = None
								return tpu







						@cached_property
						def __a						(							self   :    Dict		):
								requires_backends(self			,			['tf']		)
								if self.is_tpu:
										tf.config.experimental_connect_to_cluster(self._setup_tpu		)
										tf.tpu.experimental.initialize_tpu_system(self._setup_tpu		)

										A					       = tf.distribute.TPUStrategy(self._setup_tpu		)
								else:
										# currently no multi gpu is allowed
										if self.is_gpu:
												# TODO: Currently only single GPU is supported
												tf.config.set_visible_devices(self.gpu_list[self.device_idx]			,			'GPU'		)
												A					       = tf.distribute.OneDeviceStrategy(device=f'/gpu:{self.device_idx}'		)
										else:
												tf.config.set_visible_devices([]			,			'GPU'		)  # disable GPU
												A					       = tf.distribute.OneDeviceStrategy(device=f'/cpu:{self.device_idx}'		)

								return strategy







						@property
						def __a						(							self   :    List[Any]		):
								requires_backends(self			,			['tf']		)
								return self._setup_tpu is not None







						@property
						def __a						(							self   :    Optional[Any]		):
								requires_backends(self			,			['tf']		)
								return self._setup_strategy







						@property
						def __a						(							self   :    str		):
								requires_backends(self			,			['tf']		)
								return tf.config.list_physical_devices('GPU'		)







						@property
						def __a						(							self   :    Any		):
								requires_backends(self			,			['tf']		)
								if self.cuda:
										return len(self.gpu_list		)
								return 0







						@property
						def __a						(							self   :    Dict		):
								return self.n_gpu > 0





