






import inspect
import tempfile
from collections import OrderedDict, UserDict
from collections.abc import MutableMapping
from contextlib import ExitStack, contextmanager
from dataclasses import fields
from enum import Enum
from typing import Any, ContextManager, List, Tuple

import numpy as np

from .import_utils import is_flax_available, is_tf_available, is_torch_available, is_torch_fx_proxy


if is_flax_available():
			import jax.numpy as jnp




class 							snake_case_       (    __UpperCamelCase      ):

						"""simple docstring"""



						def __get__(self:					str ,					__UpperCAmelCase:					Any ,					__UpperCAmelCase:					Any=None   )    ->     Optional[int]:




											'''simple docstring'''



											if obj is None:
																return self
											if self.fget is None:
																raise AttributeError("unreadable attribute"   )
											__a					:						int      =					"__cached_" + self.fget.__name__
											__a					:						Optional[int]      =					getattr(__UpperCAmelCase ,					__UpperCAmelCase ,					__UpperCAmelCase   )
											if cached is None:
																__a					:						Union[str, Any]      =					self.fget(__UpperCAmelCase   )
																setattr(__UpperCAmelCase ,					__UpperCAmelCase ,					__UpperCAmelCase   )
											return cached







def     a_   (__A      )				->						Dict:



					"""simple docstring"""
					__a					:						Optional[Any]      =					val.lower()
					if val in {"y", "yes", "t", "true", "on", "1"}:
										return 1
					if val in {"n", "no", "f", "false", "off", "0"}:
										return 0
					raise ValueError(f'invalid truth value {val!r}'      )







def     a_   (__A      )				->						Dict:



					"""simple docstring"""
					if is_torch_fx_proxy(__A      ):
										return True
					if is_torch_available():
										import torch

										if isinstance(__A				,       torch.Tensor      ):
															return True
					if is_tf_available():
										import tensorflow as tf

										if isinstance(__A				,       tf.Tensor      ):
															return True

					if is_flax_available():
										import jax.numpy as jnp
										from jax.core import Tracer

										if isinstance(__A				,       (jnp.ndarray, Tracer)      ):
															return True

					return isinstance(__A				,       np.ndarray      )







def     a_   (__A      )				->						str:



					"""simple docstring"""
					return isinstance(__A				,       np.ndarray      )







def     a_   (__A      )				->						Union[str, Any]:



					"""simple docstring"""
					return _is_numpy(__A      )







def     a_   (__A      )				->						Tuple:



					"""simple docstring"""
					import torch

					return isinstance(__A				,       torch.Tensor      )







def     a_   (__A      )				->						str:



					"""simple docstring"""
					return False if not is_torch_available() else _is_torch(__A      )







def     a_   (__A      )				->						int:



					"""simple docstring"""
					import torch

					return isinstance(__A				,       torch.device      )







def     a_   (__A      )				->						Any:



					"""simple docstring"""
					return False if not is_torch_available() else _is_torch_device(__A      )







def     a_   (__A      )				->						List[Any]:



					"""simple docstring"""
					import torch

					if isinstance(__A				,       __A      ):
										if hasattr(__A				,       __A      ):
															__a					:						List[Any]      =					getattr(__A				,       __A      )
										else:
															return False
					return isinstance(__A				,       torch.dtype      )







def     a_   (__A      )				->						Optional[Any]:



					"""simple docstring"""
					return False if not is_torch_available() else _is_torch_dtype(__A      )







def     a_   (__A      )				->						List[str]:



					"""simple docstring"""
					import tensorflow as tf

					return isinstance(__A				,       tf.Tensor      )







def     a_   (__A      )				->						List[str]:



					"""simple docstring"""
					return False if not is_tf_available() else _is_tensorflow(__A      )







def     a_   (__A      )				->						Union[str, Any]:



					"""simple docstring"""
					import tensorflow as tf

					# the `is_symbolic_tensor` predicate is only available starting with TF 2.14
					if hasattr(__A				,       "is_symbolic_tensor"      ):
										return tf.is_symbolic_tensor(__A      )
					return type(__A      ) == tf.Tensor







def     a_   (__A      )				->						Dict:



					"""simple docstring"""
					return False if not is_tf_available() else _is_tf_symbolic_tensor(__A      )







def     a_   (__A      )				->						List[Any]:



					"""simple docstring"""
					import jax.numpy as jnp  # noqa: F811

					return isinstance(__A				,       jnp.ndarray      )







def     a_   (__A      )				->						Optional[Any]:



					"""simple docstring"""
					return False if not is_flax_available() else _is_jax(__A      )







def     a_   (__A      )				->						Any:



					"""simple docstring"""
					if isinstance(__A				,       (dict, UserDict)      ):
										return {k: to_py_obj(__A      ) for k, v in obj.items()}
					elif isinstance(__A				,       (list, tuple)      ):
										return [to_py_obj(__A      ) for o in obj]
					elif is_tf_tensor(__A      ):
										return obj.numpy().tolist()
					elif is_torch_tensor(__A      ):
										return obj.detach().cpu().tolist()
					elif is_jax_tensor(__A      ):
										return np.asarray(__A      ).tolist()
					elif isinstance(__A				,       (np.ndarray, np.number)      ):  # tolist also works on 0d np arrays
										return obj.tolist()
					else:
										return obj







def     a_   (__A      )				->						List[Any]:



					"""simple docstring"""
					if isinstance(__A				,       (dict, UserDict)      ):
										return {k: to_numpy(__A      ) for k, v in obj.items()}
					elif isinstance(__A				,       (list, tuple)      ):
										return np.array(__A      )
					elif is_tf_tensor(__A      ):
										return obj.numpy()
					elif is_torch_tensor(__A      ):
										return obj.detach().cpu().numpy()
					elif is_jax_tensor(__A      ):
										return np.asarray(__A      )
					else:
										return obj




class 							snake_case_       (    __UpperCamelCase      ):

						"""simple docstring"""



						def        UpperCAmelCase__					(self:					int   )    ->     Optional[Any]:




											'''simple docstring'''



											__a					:						Any      =					fields(self   )

											# Safety and consistency checks
											if not len(__UpperCAmelCase   ):
																raise ValueError(f'{self.__class__.__name__} has no fields.'   )
											if not all(field.default is None for field in class_fields[1:]   ):
																raise ValueError(f'{self.__class__.__name__} should not have more than one required field.'   )

											__a					:						Any      =					getattr(self ,					class_fields[0].name   )
											__a					:						Any      =					all(getattr(self ,					field.name   ) is None for field in class_fields[1:]   )

											if other_fields_are_none and not is_tensor(__UpperCAmelCase   ):
																if isinstance(__UpperCAmelCase ,					__UpperCAmelCase   ):
																					__a					:						Optional[Any]      =					first_field.items()
																					__a					:						Optional[int]      =					True
																else:
																					try:
																										__a					:						List[Any]      =					iter(__UpperCAmelCase   )
																										__a					:						int      =					True
																					except TypeError:
																										__a					:						List[str]      =					False

            # if we provided an iterator as first field and the iterator is a (key, value) iterator
            # set the associated fields
																if first_field_iterator:
																					for idx, element in enumerate(__UpperCAmelCase   ):
																										if (
																										    not isinstance(__UpperCAmelCase ,					(list, tuple)   )
																										    or not len(__UpperCAmelCase   ) == 2
																										    or not isinstance(element[0] ,					__UpperCAmelCase   )
																										):
																															if idx == 0:
																																				# If we do not have an iterator of key/values, set it as attribute
																																				__a					:						int      =					first_field
																															else:
																																				# If we have a mixed iterator, raise an error
																																				raise ValueError(
																																				    f'Cannot set key/value for {element}. It needs to be a tuple (key, value).'   )
																															break
																										setattr(self ,					element[0] ,					element[1]   )
																										if element[1] is not None:
																															__a					:						Tuple      =					element[1]
																elif first_field is not None:
																					__a					:						Optional[Any]      =					first_field
											else:
																for field in class_fields:
																					__a					:						int      =					getattr(self ,					field.name   )
																					if v is not None:
																										__a					:						List[str]      =					v



						def __delitem__(self:					int ,					*__UpperCAmelCase:					Any ,					**__UpperCAmelCase:					str   )    ->     Dict:




											'''simple docstring'''



											raise Exception(f'You cannot use ``__delitem__`` on a {self.__class__.__name__} instance.'   )



						def        UpperCAmelCase__					(self:					List[Any] ,					*__UpperCAmelCase:					str ,					**__UpperCAmelCase:					str   )    ->     Optional[Any]:




											'''simple docstring'''



											raise Exception(f'You cannot use ``setdefault`` on a {self.__class__.__name__} instance.'   )



						def        UpperCAmelCase__					(self:					Union[str, Any] ,					*__UpperCAmelCase:					int ,					**__UpperCAmelCase:					Any   )    ->     Dict:




											'''simple docstring'''



											raise Exception(f'You cannot use ``pop`` on a {self.__class__.__name__} instance.'   )



						def        UpperCAmelCase__					(self:					str ,					*__UpperCAmelCase:					List[str] ,					**__UpperCAmelCase:					List[Any]   )    ->     str:




											'''simple docstring'''



											raise Exception(f'You cannot use ``update`` on a {self.__class__.__name__} instance.'   )



						def __getitem__(self:					str ,					__UpperCAmelCase:					Union[str, Any]   )    ->     Dict:




											'''simple docstring'''



											if isinstance(__UpperCAmelCase ,					__UpperCAmelCase   ):
																__a					:						Union[str, Any]      =					dict(self.items()   )
																return inner_dict[k]
											else:
																return self.to_tuple()[k]



						def __setattr__(self:					Any ,					__UpperCAmelCase:					Optional[int] ,					__UpperCAmelCase:					Dict   )    ->     List[Any]:




											'''simple docstring'''



											if name in self.keys() and value is not None:
																# Don't call self.__setitem__ to avoid recursion errors
																super().__setitem__(__UpperCAmelCase ,					__UpperCAmelCase   )
											super().__setattr__(__UpperCAmelCase ,					__UpperCAmelCase   )



						def __setitem__(self:					Optional[int] ,					__UpperCAmelCase:					List[Any] ,					__UpperCAmelCase:					List[str]   )    ->     str:




											'''simple docstring'''



											super().__setitem__(__UpperCAmelCase ,					__UpperCAmelCase   )
											# Don't call self.__setattr__ to avoid recursion errors
											super().__setattr__(__UpperCAmelCase ,					__UpperCAmelCase   )



						def        UpperCAmelCase__					(self:					List[str]   )    ->     Tuple[Any]:




											'''simple docstring'''



											return tuple(self[k] for k in self.keys()   )




class 							snake_case_       (    __UpperCamelCase		,							__UpperCamelCase      ):

						"""simple docstring"""



						@classmethod
						def        UpperCAmelCase__					(cls:					str ,					__UpperCAmelCase:					Optional[Any]   )    ->     int:




											'''simple docstring'''



											raise ValueError(
											    f'{value} is not a valid {cls.__name__}, please select one of {list(cls._valueamember_map_.keys()   )}'   )




class 							snake_case_       (    __UpperCamelCase      ):

						"""simple docstring"""



						snake_case__        =      """longest"""
						snake_case__        =      """max_length"""
						snake_case__        =      """do_not_pad"""




class 							snake_case_       (    __UpperCamelCase      ):

						"""simple docstring"""



						snake_case__        =      """pt"""
						snake_case__        =      """tf"""
						snake_case__        =      """np"""
						snake_case__        =      """jax"""




class 							snake_case_       :

						"""simple docstring"""



						def __init__(self:					Optional[int] ,					__UpperCAmelCase:					List[ContextManager]   )    ->     Optional[Any]:




											'''simple docstring'''



											__a					:						str      =					context_managers
											__a					:						Dict      =					ExitStack()



						def __enter__(self:					Optional[Any]   )    ->     List[str]:




											'''simple docstring'''



											for context_manager in self.context_managers:
																self.stack.enter_context(__UpperCAmelCase   )



						def __exit__(self:					Any ,					*__UpperCAmelCase:					Dict ,					**__UpperCAmelCase:					Dict   )    ->     int:




											'''simple docstring'''



											self.stack.__exit__(*__UpperCAmelCase ,					**__UpperCAmelCase   )







def     a_   (__A      )				->						Optional[int]:



					"""simple docstring"""
					__a					:						Optional[Any]      =					infer_framework(__A      )
					if framework == "tf":
										__a					:						Optional[int]      =					inspect.signature(model_class.call      )  # TensorFlow models
					elif framework == "pt":
										__a					:						str      =					inspect.signature(model_class.forward      )  # PyTorch models
					else:
										__a					:						Any      =					inspect.signature(model_class.__call__      )  # Flax models

					for p in signature.parameters:
										if p == "return_loss" and signature.parameters[p].default is True:
															return True

					return False







def     a_   (__A      )				->						Optional[int]:



					"""simple docstring"""
					__a					:						Union[str, Any]      =					model_class.__name__
					__a					:						Tuple      =					infer_framework(__A      )
					if framework == "tf":
										__a					:						int      =					inspect.signature(model_class.call      )  # TensorFlow models
					elif framework == "pt":
										__a					:						Any      =					inspect.signature(model_class.forward      )  # PyTorch models
					else:
										__a					:						int      =					inspect.signature(model_class.__call__      )  # Flax models

					if "QuestionAnswering" in model_name:
										return [p for p in signature.parameters if "label" in p or p in ("start_positions", "end_positions")]
					else:
										return [p for p in signature.parameters if "label" in p]







def     a_   (__A				,       __A = ""				,       __A = "."      )				->						str:



					"""simple docstring"""

					def _flatten_dict(__A				,       __A=""				,       __A="."      ):
										for k, v in d.items():
															__a					:						Union[str, Any]      =					str(__A      ) + delimiter + str(__A      ) if parent_key else k
															if v and isinstance(__A				,       __A      ):
																				yield from flatten_dict(__A				,       __A				,       delimiter=__A      ).items()
															else:
																				yield key, v

					return dict(_flatten_dict(__A				,       __A				,       __A      )      )







@contextmanager
def     a_   (__A				,       __A = False      )				->						Optional[Any]:



					"""simple docstring"""
					if use_temp_dir:
										with tempfile.TemporaryDirectory() as tmp_dir:
															yield tmp_dir
					else:
										yield working_dir







def     a_   (__A				,       __A=None      )				->						Union[str, Any]:



					"""simple docstring"""
					if is_numpy_array(__A      ):
										return np.transpose(__A				,       axes=__A      )
					elif is_torch_tensor(__A      ):
										return array.T if axes is None else array.permute(*__A      )
					elif is_tf_tensor(__A      ):
										import tensorflow as tf

										return tf.transpose(__A				,       perm=__A      )
					elif is_jax_tensor(__A      ):
										return jnp.transpose(__A				,       axes=__A      )
					else:
										raise ValueError(f'Type not supported for transpose: {type(__A      )}.'      )







def     a_   (__A				,       __A      )				->						Dict:



					"""simple docstring"""
					if is_numpy_array(__A      ):
										return np.reshape(__A				,       __A      )
					elif is_torch_tensor(__A      ):
										return array.reshape(*__A      )
					elif is_tf_tensor(__A      ):
										import tensorflow as tf

										return tf.reshape(__A				,       __A      )
					elif is_jax_tensor(__A      ):
										return jnp.reshape(__A				,       __A      )
					else:
										raise ValueError(f'Type not supported for reshape: {type(__A      )}.'      )







def     a_   (__A				,       __A=None      )				->						Any:



					"""simple docstring"""
					if is_numpy_array(__A      ):
										return np.squeeze(__A				,       axis=__A      )
					elif is_torch_tensor(__A      ):
										return array.squeeze() if axis is None else array.squeeze(dim=__A      )
					elif is_tf_tensor(__A      ):
										import tensorflow as tf

										return tf.squeeze(__A				,       axis=__A      )
					elif is_jax_tensor(__A      ):
										return jnp.squeeze(__A				,       axis=__A      )
					else:
										raise ValueError(f'Type not supported for squeeze: {type(__A      )}.'      )







def     a_   (__A				,       __A      )				->						str:



					"""simple docstring"""
					if is_numpy_array(__A      ):
										return np.expand_dims(__A				,       __A      )
					elif is_torch_tensor(__A      ):
										return array.unsqueeze(dim=__A      )
					elif is_tf_tensor(__A      ):
										import tensorflow as tf

										return tf.expand_dims(__A				,       axis=__A      )
					elif is_jax_tensor(__A      ):
										return jnp.expand_dims(__A				,       axis=__A      )
					else:
										raise ValueError(f'Type not supported for expand_dims: {type(__A      )}.'      )







def     a_   (__A      )				->						Dict:



					"""simple docstring"""
					if is_numpy_array(__A      ):
										return np.size(__A      )
					elif is_torch_tensor(__A      ):
										return array.numel()
					elif is_tf_tensor(__A      ):
										import tensorflow as tf

										return tf.size(__A      )
					elif is_jax_tensor(__A      ):
										return array.size
					else:
										raise ValueError(f'Type not supported for expand_dims: {type(__A      )}.'      )







def     a_   (__A				,       __A      )				->						Union[str, Any]:



					"""simple docstring"""
					for key, value in auto_map.items():
										if isinstance(__A				,       (tuple, list)      ):
															__a					:						Dict      =					[f'{repo_id}--{v}' if (v is not None and "--" not in v) else v for v in value]
										elif value is not None and "--" not in value:
															__a					:						Optional[int]      =					f'{repo_id}--{value}'

					return auto_map







def     a_   (__A      )				->						Optional[Any]:



					"""simple docstring"""
					for base_class in inspect.getmro(__A      ):
										__a					:						Union[str, Any]      =					base_class.__module__
										__a					:						List[str]      =					base_class.__name__
										if module.startswith("tensorflow"      ) or module.startswith("keras"      ) or name == "TFPreTrainedModel":
															return "tf"
										elif module.startswith("torch"      ) or name == "PreTrainedModel":
															return "pt"
										elif module.startswith("flax"      ) or module.startswith("jax"      ) or name == "FlaxPreTrainedModel":
															return "flax"
					else:
										raise TypeError(f'Could not infer framework from class {model_class}.'      )













# coding=utf-8
# Copyright 2020 The HuggingFace Inc. team.
#
# 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.

# this script dumps information about the environment

import os
import sys

import transformers


UpperCAmelCase__      			=						'''3'''

print('''Python version:''', sys.version)
print('''transformers version:''', transformers.__version__)

try:
			import torch

			print('''Torch version:''', torch.__version__)
			print('''Cuda available:''', torch.cuda.is_available())
			print('''Cuda version:''', torch.version.cuda)
			print('''CuDNN version:''', torch.backends.cudnn.version())
			print('''Number of GPUs available:''', torch.cuda.device_count())
			print('''NCCL version:''', torch.cuda.nccl.version())
except ImportError:
			print('''Torch version:''', None)

try:
			import deepspeed

			print('''DeepSpeed version:''', deepspeed.__version__)
except ImportError:
			print('''DeepSpeed version:''', None)

try:
			import tensorflow as tf

			print('''TensorFlow version:''', tf.__version__)
			print('''TF GPUs available:''', bool(tf.config.list_physical_devices('''GPU''')))
			print('''Number of TF GPUs available:''', len(tf.config.list_physical_devices('''GPU''')))
except ImportError:
			print('''TensorFlow version:''', None)





