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



     def __get__(					self				,      lowerCAmelCase__				,      lowerCAmelCase__=None       ):
            # See docs.python.org/3/howto/descriptor.html#properties
            if obj is None:
                   return self
            if self.fget is None:
                   raise AttributeError('unreadable attribute'       )
            _A=	'__cached_' + self.fget.__name__
            _A=	getattr(lowerCAmelCase__				,      lowerCAmelCase__				,      lowerCAmelCase__       )
            if cached is None:
                   _A=	self.fget(lowerCAmelCase__       )
                   setattr(lowerCAmelCase__				,      lowerCAmelCase__				,      lowerCAmelCase__       )
            return cached


def 							UpperCamelCase				(    lowerCAmelCase_   )		->						int:




       '''simple docstring'''






       _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 							UpperCamelCase				(    lowerCAmelCase_   )		->						str:




       '''simple docstring'''






       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 							UpperCamelCase				(    lowerCAmelCase_   )		->						Union[str, Any]:




       '''simple docstring'''






       return isinstance(lowerCAmelCase_       ,					np.ndarray   )

def 							UpperCamelCase				(    lowerCAmelCase_   )		->						Optional[int]:




       '''simple docstring'''






       return _is_numpy(lowerCAmelCase_   )

def 							UpperCamelCase				(    lowerCAmelCase_   )		->						int:




       '''simple docstring'''






       import torch

       return isinstance(lowerCAmelCase_       ,					torch.Tensor   )

def 							UpperCamelCase				(    lowerCAmelCase_   )		->						List[Any]:




       '''simple docstring'''






       return False if not is_torch_available() else _is_torch(lowerCAmelCase_   )

def 							UpperCamelCase				(    lowerCAmelCase_   )		->						List[str]:




       '''simple docstring'''






       import torch

       return isinstance(lowerCAmelCase_       ,					torch.device   )

def 							UpperCamelCase				(    lowerCAmelCase_   )		->						Optional[Any]:




       '''simple docstring'''






       return False if not is_torch_available() else _is_torch_device(lowerCAmelCase_   )

def 							UpperCamelCase				(    lowerCAmelCase_   )		->						Union[str, Any]:




       '''simple docstring'''






       import torch

       if isinstance(lowerCAmelCase_       ,					lowerCAmelCase_   ):
              if hasattr(lowerCAmelCase_       ,					lowerCAmelCase_   ):
                     _A=	getattr(lowerCAmelCase_       ,					lowerCAmelCase_   )
              else:
                     return False
       return isinstance(lowerCAmelCase_       ,					torch.dtype   )

def 							UpperCamelCase				(    lowerCAmelCase_   )		->						str:




       '''simple docstring'''






       return False if not is_torch_available() else _is_torch_dtype(lowerCAmelCase_   )

def 							UpperCamelCase				(    lowerCAmelCase_   )		->						Optional[Any]:




       '''simple docstring'''






       import tensorflow as tf

       return isinstance(lowerCAmelCase_       ,					tf.Tensor   )

def 							UpperCamelCase				(    lowerCAmelCase_   )		->						Union[str, Any]:




       '''simple docstring'''






       return False if not is_tf_available() else _is_tensorflow(lowerCAmelCase_   )

def 							UpperCamelCase				(    lowerCAmelCase_   )		->						Any:




       '''simple docstring'''






       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 							UpperCamelCase				(    lowerCAmelCase_   )		->						Optional[int]:




       '''simple docstring'''






       return False if not is_tf_available() else _is_tf_symbolic_tensor(lowerCAmelCase_   )

def 							UpperCamelCase				(    lowerCAmelCase_   )		->						str:




       '''simple docstring'''






       import jax.numpy as jnp  # noqa: F811

       return isinstance(lowerCAmelCase_       ,					jnp.ndarray   )

def 							UpperCamelCase				(    lowerCAmelCase_   )		->						str:




       '''simple docstring'''






       return False if not is_flax_available() else _is_jax(lowerCAmelCase_   )

def 							UpperCamelCase				(    lowerCAmelCase_   )		->						Optional[int]:




       '''simple docstring'''






       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 							UpperCamelCase				(    lowerCAmelCase_   )		->						Any:




       '''simple docstring'''






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



     def 			a__  (					self       ):
            _A=	fields(self       )

            # Safety and consistency checks
            if not len(lowerCAmelCase__       ):
                   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(lowerCAmelCase__       ):
                   if isinstance(lowerCAmelCase__				,      lowerCAmelCase__       ):
                          _A=	first_field.items()
                          _A=	True
                   else:
                          try:
                                 _A=	iter(lowerCAmelCase__       )
                                 _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(lowerCAmelCase__       ):
                                 if (
                                     not isinstance(lowerCAmelCase__				,      (list, tuple)       )
                                     or not len(lowerCAmelCase__       ) == 2
                                     or not isinstance(element[0]				,      lowerCAmelCase__       )
                                 ):
                                        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				,      *lowerCAmelCase__				,      **lowerCAmelCase__       ):
            raise Exception(f"You cannot use ``__delitem__`` on a {self.__class__.__name__} instance."       )



     def 			a__  (					self				,      *lowerCAmelCase__				,      **lowerCAmelCase__       ):
            raise Exception(f"You cannot use ``setdefault`` on a {self.__class__.__name__} instance."       )



     def 			a__  (					self				,      *lowerCAmelCase__				,      **lowerCAmelCase__       ):
            raise Exception(f"You cannot use ``pop`` on a {self.__class__.__name__} instance."       )



     def 			a__  (					self				,      *lowerCAmelCase__				,      **lowerCAmelCase__       ):
            raise Exception(f"You cannot use ``update`` on a {self.__class__.__name__} instance."       )



     def __getitem__(					self				,      lowerCAmelCase__       ):
            if isinstance(lowerCAmelCase__				,      lowerCAmelCase__       ):
                   _A=	dict(self.items()       )
                   return inner_dict[k]
            else:
                   return self.to_tuple()[k]



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



     def __setitem__(					self				,      lowerCAmelCase__				,      lowerCAmelCase__       ):
            # Will raise a KeyException if needed
            super().__setitem__(lowerCAmelCase__				,      lowerCAmelCase__       )
            # Don't call self.__setattr__ to avoid recursion errors
            super().__setattr__(lowerCAmelCase__				,      lowerCAmelCase__       )





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





class      lowerCAmelCase						(					_a			,		_a			):



     @classmethod
     def 			a__  (					cls				,      lowerCAmelCase__       ):
            raise ValueError(
                f"{value} is not a valid {cls.__name__}, please select one of {list(cls._valueamember_map_.keys()       )}"       )





class      lowerCAmelCase						(					_a			):
     _SCREAMING_SNAKE_CASE     :     str		="""longest"""
     _SCREAMING_SNAKE_CASE     :     int		="""max_length"""
     _SCREAMING_SNAKE_CASE     :     Optional[Any]		="""do_not_pad"""





class      lowerCAmelCase						(					_a			):
     _SCREAMING_SNAKE_CASE     :     List[str]		="""pt"""
     _SCREAMING_SNAKE_CASE     :     Optional[int]		="""tf"""
     _SCREAMING_SNAKE_CASE     :     Dict		="""np"""
     _SCREAMING_SNAKE_CASE     :     List[Any]		="""jax"""





class      lowerCAmelCase						:



     def __init__(					self				,      lowerCAmelCase__       ):
            _A=	context_managers
            _A=	ExitStack()



     def __enter__(					self       ):
            for context_manager in self.context_managers:
                   self.stack.enter_context(lowerCAmelCase__       )





     def __exit__(					self				,      *lowerCAmelCase__				,      **lowerCAmelCase__       ):
            self.stack.__exit__(*lowerCAmelCase__				,      **lowerCAmelCase__       )


def 							UpperCamelCase				(    lowerCAmelCase_   )		->						List[str]:




       '''simple docstring'''






       _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 							UpperCamelCase				(    lowerCAmelCase_   )		->						str:




       '''simple docstring'''






       _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 							UpperCamelCase				(    lowerCAmelCase_       ,					lowerCAmelCase_ = ""       ,					lowerCAmelCase_ = "."   )		->						str:




       '''simple docstring'''






       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 							UpperCamelCase				(    lowerCAmelCase_       ,					lowerCAmelCase_ = False   )		->						Dict:




       '''simple docstring'''






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

def 							UpperCamelCase				(    lowerCAmelCase_       ,					lowerCAmelCase_=None   )		->						int:




       '''simple docstring'''






       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 							UpperCamelCase				(    lowerCAmelCase_       ,					lowerCAmelCase_   )		->						List[str]:




       '''simple docstring'''






       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 							UpperCamelCase				(    lowerCAmelCase_       ,					lowerCAmelCase_=None   )		->						List[str]:




       '''simple docstring'''






       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 							UpperCamelCase				(    lowerCAmelCase_       ,					lowerCAmelCase_   )		->						Union[str, Any]:




       '''simple docstring'''






       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 							UpperCamelCase				(    lowerCAmelCase_   )		->						Dict:




       '''simple docstring'''






       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 							UpperCamelCase				(    lowerCAmelCase_       ,					lowerCAmelCase_   )		->						List[str]:




       '''simple docstring'''






       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 							UpperCamelCase				(    lowerCAmelCase_   )		->						str:




       '''simple docstring'''






       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 pickle
import unittest

import torch

from accelerate import Accelerator
from accelerate.state import AcceleratorState
from accelerate.test_utils import require_cpu





@require_cpu
class      lowerCAmelCase						(					unittest.TestCase			):



     def 			a__  (					self       ):
            _A=	torch.nn.Linear(10				,      10       )
            _A=	torch.optim.SGD(model.parameters()				,      0.1       )
            _A=	Accelerator()
            _A=	accelerator.prepare(lowerCAmelCase__       )
            try:
                   pickle.loads(pickle.dumps(lowerCAmelCase__       )       )
            except Exception as e:
                   self.fail(f"Accelerated optimizer pickling failed with {e}"       )
            AcceleratorState._reset_state()