


'''simple docstring'''


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


  '''simple docstring'''







  def __get__(							self :       str	,_a :       Any	,_a :       Any=None ):

        '''simple docstring'''




        if obj is None:
              return self
        if self.fget is None:
              raise AttributeError("""unreadable attribute""" )
        A_						:  Dict          =				"""__cached_""" + self.fget.__name__
        A_						:  int          =				getattr(__lowerCAmelCase	,__lowerCAmelCase	,__lowerCAmelCase )
        if cached is None:
              A_						:  List[Any]          =				self.fget(__lowerCAmelCase )
              setattr(__lowerCAmelCase	,__lowerCAmelCase	,__lowerCAmelCase )
        return cached







def      lowerCamelCase					(      lowerCamelCase  :      Union[str, Any]):
      A_						:  Tuple          =				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      lowerCamelCase					(      lowerCamelCase  :      Optional[Any]):







      if is_torch_fx_proxy(__snake_case):
            return True
      if is_torch_available():
            import torch

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

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

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

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

      return isinstance(__snake_case							,						np.ndarray)




def      lowerCamelCase					(      lowerCamelCase  :      str):
      return isinstance(__snake_case							,						np.ndarray)




def      lowerCamelCase					(      lowerCamelCase  :      Union[str, Any]):
      return _is_numpy(__snake_case)




def      lowerCamelCase					(      lowerCamelCase  :      Any):
      import torch

      return isinstance(__snake_case							,						torch.Tensor)




def      lowerCamelCase					(      lowerCamelCase  :      List[Any]):
      return False if not is_torch_available() else _is_torch(__snake_case)




def      lowerCamelCase					(      lowerCamelCase  :      Any):
      import torch

      return isinstance(__snake_case							,						torch.device)




def      lowerCamelCase					(      lowerCamelCase  :      Tuple):
      return False if not is_torch_available() else _is_torch_device(__snake_case)




def      lowerCamelCase					(      lowerCamelCase  :      Tuple):
      import torch

      if isinstance(__snake_case							,						__snake_case):
            if hasattr(__snake_case							,						__snake_case):
                  A_						:  Optional[int]          =				getattr(__snake_case							,						__snake_case)
            else:
                  return False
      return isinstance(__snake_case							,						torch.dtype)




def      lowerCamelCase					(      lowerCamelCase  :      Tuple):
      return False if not is_torch_available() else _is_torch_dtype(__snake_case)




def      lowerCamelCase					(      lowerCamelCase  :      List[str]):
      import tensorflow as tf

      return isinstance(__snake_case							,						tf.Tensor)




def      lowerCamelCase					(      lowerCamelCase  :      Union[str, Any]):
      return False if not is_tf_available() else _is_tensorflow(__snake_case)




def      lowerCamelCase					(      lowerCamelCase  :      Optional[Any]):
      import tensorflow as tf

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




def      lowerCamelCase					(      lowerCamelCase  :      Tuple):
      return False if not is_tf_available() else _is_tf_symbolic_tensor(__snake_case)




def      lowerCamelCase					(      lowerCamelCase  :      int):
      import jax.numpy as jnp  # noqa: F811

      return isinstance(__snake_case							,						jnp.ndarray)




def      lowerCamelCase					(      lowerCamelCase  :      Optional[Any]):
      return False if not is_flax_available() else _is_jax(__snake_case)




def      lowerCamelCase					(      lowerCamelCase  :      Union[str, Any]):







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




def      lowerCamelCase					(      lowerCamelCase  :      List[str]):







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



class 	__lowerCAmelCase		(							__SCREAMING_SNAKE_CASE    ):


  '''simple docstring'''







  def        _a							(							self :       Dict ):

        '''simple docstring'''




        A_						:  int          =				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_						:  Optional[int]          =				getattr(self	,class_fields[0].name )
        A_						:  List[str]          =				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_						:  Dict          =				first_field.items()
                    A_						:  List[str]          =				True
              else:
                    try:
                          A_						:  Tuple          =				iter(__lowerCAmelCase )
                          A_						:  List[Any]          =				True
                    except TypeError:
                          A_						:  Optional[Any]          =				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_						:  str          =				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_						:  str          =				element[1]
              elif first_field is not None:
                    A_						:  Dict          =				first_field
        else:
              for field in class_fields:
                    A_						:  Union[str, Any]          =				getattr(self	,field.name )
                    if v is not None:
                          A_						:  Any          =				v






  def __delitem__(							self :       Any	,*_a :       Optional[int]	,**_a :       Tuple ):

        '''simple docstring'''




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






  def        _a							(							self :       List[str]	,*_a :       Optional[int]	,**_a :       Union[str, Any] ):

        '''simple docstring'''




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






  def        _a							(							self :       Dict	,*_a :       Union[str, Any]	,**_a :       Any ):

        '''simple docstring'''




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






  def        _a							(							self :       List[str]	,*_a :       Dict	,**_a :       Optional[Any] ):

        '''simple docstring'''




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






  def __getitem__(							self :       Tuple	,_a :       str ):

        '''simple docstring'''




        if isinstance(__lowerCAmelCase	,__lowerCAmelCase ):
              A_						:  Optional[Any]          =				dict(self.items() )
              return inner_dict[k]
        else:
              return self.to_tuple()[k]






  def __setattr__(							self :       Optional[Any]	,_a :       List[str]	,_a :       List[str] ):

        '''simple docstring'''




        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 :       int	,_a :       List[str]	,_a :       int ):

        '''simple docstring'''




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






  def        _a							(							self :       Union[str, Any] ):

        '''simple docstring'''




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







class 	__lowerCAmelCase		(							__SCREAMING_SNAKE_CASE  , __SCREAMING_SNAKE_CASE    ):


  '''simple docstring'''







  @classmethod
  def        _a							(							cls :       Optional[Any]	,_a :       Dict ):

        '''simple docstring'''




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







class 	__lowerCAmelCase		(							__SCREAMING_SNAKE_CASE    ):


  '''simple docstring'''







  a_  					=							"""longest"""
  a_  					=							"""max_length"""
  a_  					=							"""do_not_pad"""







class 	__lowerCAmelCase		(							__SCREAMING_SNAKE_CASE    ):


  '''simple docstring'''







  a_  					=							"""pt"""
  a_  					=							"""tf"""
  a_  					=							"""np"""
  a_  					=							"""jax"""







class 	__lowerCAmelCase		:


  '''simple docstring'''







  def __init__(							self :       Union[str, Any]	,_a :       List[Any] ):

        '''simple docstring'''




        A_						:  List[str]          =				context_managers
        A_						:  Dict          =				ExitStack()






  def __enter__(							self :       Dict ):

        '''simple docstring'''




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






  def __exit__(							self :       Any	,*_a :       List[Any]	,**_a :       List[str] ):

        '''simple docstring'''




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







def      lowerCamelCase					(      lowerCamelCase  :      Optional[int]):
      A_						:  str          =				infer_framework(__snake_case)
      if framework == "tf":
            A_						:  Union[str, Any]          =				inspect.signature(model_class.call)  # TensorFlow models
      elif framework == "pt":
            A_						:  Any          =				inspect.signature(model_class.forward)  # PyTorch models
      else:
            A_						:  Tuple          =				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      lowerCamelCase					(      lowerCamelCase  :      Tuple):
      A_						:  Optional[Any]          =				model_class.__name__
      A_						:  List[str]          =				infer_framework(__snake_case)
      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_						:  List[str]          =				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      lowerCamelCase					(      lowerCamelCase  :      Dict							,						lowerCamelCase  :      str = ""							,						lowerCamelCase  :      Tuple = "."):







      def _flatten_dict(lowerCamelCase  :      Dict							,						lowerCamelCase  :      List[Any]=""							,						lowerCamelCase  :      Dict="."):
            for k, v in d.items():
                  A_						:  Tuple          =				str(__snake_case) + delimiter + str(__snake_case) if parent_key else k
                  if v and isinstance(__snake_case							,						__snake_case):
                        yield from flatten_dict(__snake_case							,						__snake_case							,						delimiter=__snake_case).items()
                  else:
                        yield key, v

      return dict(_flatten_dict(__snake_case							,						__snake_case							,						__snake_case))




@contextmanager
def      lowerCamelCase					(      lowerCamelCase  :      Optional[int]							,						lowerCamelCase  :      Union[str, Any] = False):







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




def      lowerCamelCase					(      lowerCamelCase  :      Optional[Any]							,						lowerCamelCase  :      Dict=None):







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

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




def      lowerCamelCase					(      lowerCamelCase  :      Tuple							,						lowerCamelCase  :      Any):







      if is_numpy_array(__snake_case):
            return np.reshape(__snake_case							,						__snake_case)
      elif is_torch_tensor(__snake_case):
            return array.reshape(*__snake_case)
      elif is_tf_tensor(__snake_case):
            import tensorflow as tf

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




def      lowerCamelCase					(      lowerCamelCase  :      Tuple							,						lowerCamelCase  :      str=None):







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

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




def      lowerCamelCase					(      lowerCamelCase  :      Any							,						lowerCamelCase  :      int):







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

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




def      lowerCamelCase					(      lowerCamelCase  :      Tuple):







      if is_numpy_array(__snake_case):
            return np.size(__snake_case)
      elif is_torch_tensor(__snake_case):
            return array.numel()
      elif is_tf_tensor(__snake_case):
            import tensorflow as tf

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




def      lowerCamelCase					(      lowerCamelCase  :      Tuple							,						lowerCamelCase  :      Optional[Any]):







      for key, value in auto_map.items():
            if isinstance(__snake_case							,						(tuple, list)):
                  A_						:  Optional[int]          =				[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_						:  Tuple          =				F'{repo_id}--{value}'

      return auto_map






def      lowerCamelCase					(      lowerCamelCase  :      Tuple):







      for base_class in inspect.getmro(__snake_case):
            A_						:  str          =				base_class.__module__
            A_						:  Tuple          =				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}.')




'''simple docstring'''


from collections import OrderedDict
from typing import TYPE_CHECKING, Any, Mapping, Optional, Union

from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig
from ...utils import logging


if TYPE_CHECKING:
     from ... import FeatureExtractionMixin, PreTrainedTokenizerBase, TensorType


__magic_name__			=      logging.get_logger(__name__)

__magic_name__			=      {
    'microsoft/deberta-v2-xlarge': 'https://huggingface.co/microsoft/deberta-v2-xlarge/resolve/main/config.json',
    'microsoft/deberta-v2-xxlarge': 'https://huggingface.co/microsoft/deberta-v2-xxlarge/resolve/main/config.json',
    'microsoft/deberta-v2-xlarge-mnli': (
        'https://huggingface.co/microsoft/deberta-v2-xlarge-mnli/resolve/main/config.json'
    ),
    'microsoft/deberta-v2-xxlarge-mnli': (
        'https://huggingface.co/microsoft/deberta-v2-xxlarge-mnli/resolve/main/config.json'
    ),
}



class 	__lowerCAmelCase		(							__SCREAMING_SNAKE_CASE    ):


  '''simple docstring'''







  a_  					=							"""deberta-v2"""






  def __init__(							self :       Optional[Any]	,_a :       Union[str, Any]=128100	,_a :       Optional[int]=1536	,_a :       Dict=24	,_a :       int=24	,_a :       Tuple=6144	,_a :       Union[str, Any]="gelu"	,_a :       List[Any]=0.1	,_a :       Dict=0.1	,_a :       int=512	,_a :       int=0	,_a :       int=0.02	,_a :       int=1e-7	,_a :       List[str]=False	,_a :       Union[str, Any]=-1	,_a :       List[Any]=0	,_a :       Optional[Any]=True	,_a :       Tuple=None	,_a :       Any=0	,_a :       int="gelu"	,**_a :       Any	,):

        '''simple docstring'''




        super().__init__(**_a )

        A_						:  Union[str, Any]          =				hidden_size
        A_						:  Dict          =				num_hidden_layers
        A_						:  Union[str, Any]          =				num_attention_heads
        A_						:  List[Any]          =				intermediate_size
        A_						:  List[Any]          =				hidden_act
        A_						:  Optional[int]          =				hidden_dropout_prob
        A_						:  Dict          =				attention_probs_dropout_prob
        A_						:  int          =				max_position_embeddings
        A_						:  Any          =				type_vocab_size
        A_						:  List[Any]          =				initializer_range
        A_						:  int          =				relative_attention
        A_						:  Tuple          =				max_relative_positions
        A_						:  int          =				pad_token_id
        A_						:  Tuple          =				position_biased_input

        # Backwards compatibility
        if type(_a ) == str:
              A_						:  str          =				[x.strip() for x in pos_att_type.lower().split("""|""" )]

        A_						:  Any          =				pos_att_type
        A_						:  Optional[int]          =				vocab_size
        A_						:  Tuple          =				layer_norm_eps

        A_						:  Any          =				kwargs.get("""pooler_hidden_size"""	,_a )
        A_						:  Union[str, Any]          =				pooler_dropout
        A_						:  List[Any]          =				pooler_hidden_act







class 	__lowerCAmelCase		(							__SCREAMING_SNAKE_CASE    ):


  '''simple docstring'''







  @property
  def        _a							(							self :       Any ):

        '''simple docstring'''




        if self.task == "multiple-choice":
              A_						:  Any          =				{0: """batch""", 1: """choice""", 2: """sequence"""}
        else:
              A_						:  Any          =				{0: """batch""", 1: """sequence"""}
        if self._config.type_vocab_size > 0:
              return OrderedDict(
                  [("""input_ids""", dynamic_axis), ("""attention_mask""", dynamic_axis), ("""token_type_ids""", dynamic_axis)] )
        else:
              return OrderedDict([("""input_ids""", dynamic_axis), ("""attention_mask""", dynamic_axis)] )






  @property
  def        _a							(							self :       Optional[int] ):

        '''simple docstring'''




        return 12






  def        _a							(							self :       int	,_a :       Union["PreTrainedTokenizerBase", "FeatureExtractionMixin"]	,_a :       int = -1	,_a :       int = -1	,_a :       int = -1	,_a :       bool = False	,_a :       Optional["TensorType"] = None	,_a :       int = 3	,_a :       int = 40	,_a :       int = 40	,_a :       "PreTrainedTokenizerBase" = None	,):

        '''simple docstring'''




        A_						:  Any          =				super().generate_dummy_inputs(preprocessor=_a	,framework=_a )
        if self._config.type_vocab_size == 0 and "token_type_ids" in dummy_inputs:
              del dummy_inputs["token_type_ids"]
        return dummy_inputs
