




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 						__lowerCAmelCase      (      __magic_name__					):
							def __get__(		self		:List[Any]						, __magic_name__		:int						, __magic_name__		:Dict=None							):







								'''simple docstring'''







								if obj is None:
									return self
								if self.fget is None:
									raise AttributeError("""unreadable attribute"""							)
								a									=				"""__cached_""" + self.fget.__name__
								a									=				getattr(__magic_name__						, __magic_name__						, __magic_name__							)
								if cached is None:
									a									=				self.fget(__magic_name__							)
									setattr(__magic_name__						, __magic_name__						, __magic_name__							)
								return cached







def 						__A						(      __lowerCamelCase       ) ->			Any:
	a									=				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						(      __lowerCamelCase       ) ->			Any:
	if is_torch_fx_proxy(__lowerCamelCase       ):
		return True
	if is_torch_available():
		import torch

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

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

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

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

	return isinstance(__lowerCamelCase				,     np.ndarray       )





def 						__A						(      __lowerCamelCase       ) ->			Dict:
	return isinstance(__lowerCamelCase				,     np.ndarray       )





def 						__A						(      __lowerCamelCase       ) ->			str:
	return _is_numpy(__lowerCamelCase       )





def 						__A						(      __lowerCamelCase       ) ->			Tuple:
	import torch

	return isinstance(__lowerCamelCase				,     torch.Tensor       )





def 						__A						(      __lowerCamelCase       ) ->			List[Any]:
	return False if not is_torch_available() else _is_torch(__lowerCamelCase       )





def 						__A						(      __lowerCamelCase       ) ->			int:
	import torch

	return isinstance(__lowerCamelCase				,     torch.device       )





def 						__A						(      __lowerCamelCase       ) ->			Tuple:
	return False if not is_torch_available() else _is_torch_device(__lowerCamelCase       )





def 						__A						(      __lowerCamelCase       ) ->			Optional[int]:
	import torch

	if isinstance(__lowerCamelCase				,     __lowerCamelCase       ):
		if hasattr(__lowerCamelCase				,     __lowerCamelCase       ):
			a									=				getattr(__lowerCamelCase				,     __lowerCamelCase       )
		else:
			return False
	return isinstance(__lowerCamelCase				,     torch.dtype       )





def 						__A						(      __lowerCamelCase       ) ->			int:
	return False if not is_torch_available() else _is_torch_dtype(__lowerCamelCase       )





def 						__A						(      __lowerCamelCase       ) ->			int:
	import tensorflow as tf

	return isinstance(__lowerCamelCase				,     tf.Tensor       )





def 						__A						(      __lowerCamelCase       ) ->			Optional[int]:
	return False if not is_tf_available() else _is_tensorflow(__lowerCamelCase       )





def 						__A						(      __lowerCamelCase       ) ->			Optional[Any]:
	import tensorflow as tf

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





def 						__A						(      __lowerCamelCase       ) ->			Union[str, Any]:
	return False if not is_tf_available() else _is_tf_symbolic_tensor(__lowerCamelCase       )





def 						__A						(      __lowerCamelCase       ) ->			Union[str, Any]:
	import jax.numpy as jnp  # noqa: F811

	return isinstance(__lowerCamelCase				,     jnp.ndarray       )





def 						__A						(      __lowerCamelCase       ) ->			List[str]:
	return False if not is_flax_available() else _is_jax(__lowerCamelCase       )





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





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

class 						__lowerCAmelCase      (      __magic_name__					):
							def  lowerCamelCase__				(		self		:List[Any]							):







								'''simple docstring'''







								a									=				fields(self							)

								# Safety and consistency checks
								if not len(__magic_name__							):
									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									=				getattr(self						, class_fields[0].name							)
								a									=				all(getattr(self						, field.name							) is None for field in class_fields[1:]							)

								if other_fields_are_none and not is_tensor(__magic_name__							):
									if isinstance(__magic_name__						, __magic_name__							):
										a									=				first_field.items()
										a									=				True
									else:
										try:
											a									=				iter(__magic_name__							)
											a									=				True
										except TypeError:
											a									=				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(__magic_name__							):
											if (
											    not isinstance(__magic_name__						, (list, tuple)							)
											    or not len(__magic_name__							) == 2
											    or not isinstance(element[0]						, __magic_name__							)
											):
												if idx == 0:
													# If we do not have an iterator of key/values, set it as attribute
													a									=				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									=				element[1]
									elif first_field is not None:
										a									=				first_field
								else:
									for field in class_fields:
										a									=				getattr(self						, field.name							)
										if v is not None:
											a									=				v
							def __delitem__(		self		:str						, *__magic_name__		:List[Any]						, **__magic_name__		:Optional[Any]							):







								'''simple docstring'''







								raise Exception(F'You cannot use ``__delitem__`` on a {self.__class__.__name__} instance.'							)
							def  lowerCamelCase__				(		self		:List[str]						, *__magic_name__		:Dict						, **__magic_name__		:Any							):







								'''simple docstring'''







								raise Exception(F'You cannot use ``setdefault`` on a {self.__class__.__name__} instance.'							)
							def  lowerCamelCase__				(		self		:List[str]						, *__magic_name__		:List[Any]						, **__magic_name__		:Optional[Any]							):







								'''simple docstring'''







								raise Exception(F'You cannot use ``pop`` on a {self.__class__.__name__} instance.'							)
							def  lowerCamelCase__				(		self		:int						, *__magic_name__		:Optional[int]						, **__magic_name__		:Tuple							):







								'''simple docstring'''







								raise Exception(F'You cannot use ``update`` on a {self.__class__.__name__} instance.'							)
							def __getitem__(		self		:List[str]						, __magic_name__		:Any							):







								'''simple docstring'''







								if isinstance(__magic_name__						, __magic_name__							):
									a									=				dict(self.items()							)
									return inner_dict[k]
								else:
									return self.to_tuple()[k]
							def __setattr__(		self		:Any						, __magic_name__		:Union[str, Any]						, __magic_name__		:Any							):







								'''simple docstring'''







								if name in self.keys() and value is not None:
									# Don't call self.__setitem__ to avoid recursion errors
									super().__setitem__(__magic_name__						, __magic_name__							)
								super().__setattr__(__magic_name__						, __magic_name__							)
							def __setitem__(		self		:int						, __magic_name__		:int						, __magic_name__		:Optional[Any]							):







								'''simple docstring'''







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





							def  lowerCamelCase__				(		self		:Any							):







								'''simple docstring'''







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







class 						__lowerCAmelCase      (      __magic_name__ ,			__magic_name__					):
							@classmethod
							def  lowerCamelCase__				(		cls		:List[Any]						, __magic_name__		:Dict							):







								'''simple docstring'''







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







class 						__lowerCAmelCase      (      __magic_name__					):
							UpperCamelCase__   	=    '''longest'''
							UpperCamelCase__   	=    '''max_length'''
							UpperCamelCase__   	=    '''do_not_pad'''







class 						__lowerCAmelCase      (      __magic_name__					):
							UpperCamelCase__   	=    '''pt'''
							UpperCamelCase__   	=    '''tf'''
							UpperCamelCase__   	=    '''np'''
							UpperCamelCase__   	=    '''jax'''







class 						__lowerCAmelCase      :
							def __init__(		self		:Union[str, Any]						, __magic_name__		:List[ContextManager]							):







								'''simple docstring'''







								a									=				context_managers
								a									=				ExitStack()
							def __enter__(		self		:int							):







								'''simple docstring'''







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





							def __exit__(		self		:Tuple						, *__magic_name__		:Dict						, **__magic_name__		:Dict							):







								'''simple docstring'''







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







def 						__A						(      __lowerCamelCase       ) ->			List[str]:
	a									=				infer_framework(__lowerCamelCase       )
	if framework == "tf":
		a									=				inspect.signature(model_class.call       )  # TensorFlow models
	elif framework == "pt":
		a									=				inspect.signature(model_class.forward       )  # PyTorch models
	else:
		a									=				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						(      __lowerCamelCase       ) ->			Union[str, Any]:
	a									=				model_class.__name__
	a									=				infer_framework(__lowerCamelCase       )
	if framework == "tf":
		a									=				inspect.signature(model_class.call       )  # TensorFlow models
	elif framework == "pt":
		a									=				inspect.signature(model_class.forward       )  # PyTorch models
	else:
		a									=				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						(      __lowerCamelCase				,     __lowerCamelCase = ""				,     __lowerCamelCase = "."       ) ->			List[Any]:

	def _flatten_dict(__lowerCamelCase				,     __lowerCamelCase=""				,     __lowerCamelCase="."       ):
		for k, v in d.items():
			a									=				str(__lowerCamelCase       ) + delimiter + str(__lowerCamelCase       ) if parent_key else k
			if v and isinstance(__lowerCamelCase				,     __lowerCamelCase       ):
				yield from flatten_dict(__lowerCamelCase				,     __lowerCamelCase				,     delimiter=__lowerCamelCase       ).items()
			else:
				yield key, v

	return dict(_flatten_dict(__lowerCamelCase				,     __lowerCamelCase				,     __lowerCamelCase       )       )





@contextmanager
def 						__A						(      __lowerCamelCase				,     __lowerCamelCase = False       ) ->			int:
	if use_temp_dir:
		with tempfile.TemporaryDirectory() as tmp_dir:
			yield tmp_dir
	else:
		yield working_dir





def 						__A						(      __lowerCamelCase				,     __lowerCamelCase=None       ) ->			List[str]:
	if is_numpy_array(__lowerCamelCase       ):
		return np.transpose(__lowerCamelCase				,     axes=__lowerCamelCase       )
	elif is_torch_tensor(__lowerCamelCase       ):
		return array.T if axes is None else array.permute(*__lowerCamelCase       )
	elif is_tf_tensor(__lowerCamelCase       ):
		import tensorflow as tf

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





def 						__A						(      __lowerCamelCase				,     __lowerCamelCase       ) ->			List[str]:
	if is_numpy_array(__lowerCamelCase       ):
		return np.reshape(__lowerCamelCase				,     __lowerCamelCase       )
	elif is_torch_tensor(__lowerCamelCase       ):
		return array.reshape(*__lowerCamelCase       )
	elif is_tf_tensor(__lowerCamelCase       ):
		import tensorflow as tf

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





def 						__A						(      __lowerCamelCase				,     __lowerCamelCase=None       ) ->			str:
	if is_numpy_array(__lowerCamelCase       ):
		return np.squeeze(__lowerCamelCase				,     axis=__lowerCamelCase       )
	elif is_torch_tensor(__lowerCamelCase       ):
		return array.squeeze() if axis is None else array.squeeze(dim=__lowerCamelCase       )
	elif is_tf_tensor(__lowerCamelCase       ):
		import tensorflow as tf

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





def 						__A						(      __lowerCamelCase				,     __lowerCamelCase       ) ->			str:
	if is_numpy_array(__lowerCamelCase       ):
		return np.expand_dims(__lowerCamelCase				,     __lowerCamelCase       )
	elif is_torch_tensor(__lowerCamelCase       ):
		return array.unsqueeze(dim=__lowerCamelCase       )
	elif is_tf_tensor(__lowerCamelCase       ):
		import tensorflow as tf

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





def 						__A						(      __lowerCamelCase       ) ->			int:
	if is_numpy_array(__lowerCamelCase       ):
		return np.size(__lowerCamelCase       )
	elif is_torch_tensor(__lowerCamelCase       ):
		return array.numel()
	elif is_tf_tensor(__lowerCamelCase       ):
		import tensorflow as tf

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





def 						__A						(      __lowerCamelCase				,     __lowerCamelCase       ) ->			Optional[Any]:
	for key, value in auto_map.items():
		if isinstance(__lowerCamelCase				,     (tuple, list)       ):
			a									=				[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									=				f'{repo_id}--{value}'

	return auto_map





def 						__A						(      __lowerCamelCase       ) ->			Optional[Any]:
	for base_class in inspect.getmro(__lowerCamelCase       ):
		a									=				base_class.__module__
		a									=				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}.'       )







import operator as op


__UpperCamelCase   :			Optional[Any]          = "scaler.pt"
__UpperCamelCase   :			Optional[Any]          = "pytorch_model"
__UpperCamelCase   :			str          = "random_states"
__UpperCamelCase   :			Optional[int]          = "optimizer"
__UpperCamelCase   :			Optional[int]          = "scheduler"
__UpperCamelCase   :			str          = "pytorch_model.bin"
__UpperCamelCase   :			List[str]          = "pytorch_model.bin.index.json"
__UpperCamelCase   :			List[str]          = "model.safetensors"
__UpperCamelCase   :			Optional[int]          = "model.safetensors.index.json"
__UpperCamelCase   :			List[str]          = "1.10.2"
__UpperCamelCase   :			Dict          = "py38"
__UpperCamelCase   :			List[str]          = "4.17.0"
__UpperCamelCase   :			Any          = ["ml.p3.16xlarge", "ml.p3dn.24xlarge", "ml.p4dn.24xlarge"]
__UpperCamelCase   :			Any          = ["FULL_SHARD", "SHARD_GRAD_OP", "NO_SHARD", "HYBRID_SHARD", "HYBRID_SHARD_ZERO2"]
__UpperCamelCase   :			int          = ["TRANSFORMER_BASED_WRAP", "SIZE_BASED_WRAP", "NO_WRAP"]
__UpperCamelCase   :			Dict          = ["BACKWARD_PRE", "BACKWARD_POST", "NO_PREFETCH"]
__UpperCamelCase   :			str          = ["FULL_STATE_DICT", "LOCAL_STATE_DICT", "SHARDED_STATE_DICT"]
__UpperCamelCase   :			List[Any]          = "2.0.1"
__UpperCamelCase   :			int          = ["pdsh", "standard", "openmpi", "mvapich"]
__UpperCamelCase   :			List[str]          = ["default", "reduce-overhead", "max-autotune"]

__UpperCamelCase   :			List[Any]          = {">": op.gt, ">=": op.ge, "==": op.eq, "!=": op.ne, "<=": op.le, "<": op.lt}

# These are the args for `torch.distributed.launch` for pytorch < 1.9
__UpperCamelCase   :			List[Any]          = [
    "nnodes",
    "nproc_per_node",
    "rdzv_backend",
    "rdzv_endpoint",
    "rdzv_id",
    "rdzv_conf",
    "standalone",
    "max_restarts",
    "monitor_interval",
    "start_method",
    "role",
    "module",
    "m",
    "no_python",
    "run_path",
    "log_dir",
    "r",
    "redirects",
    "t",
    "tee",
    "node_rank",
    "master_addr",
    "master_port",
]

__UpperCamelCase   :			List[str]          = ["DEEPSPEED", "MULTI_GPU", "FSDP", "MEGATRON_LM"]
__UpperCamelCase   :			int          = ["DEEPSPEED", "MULTI_XPU", "FSDP"]

