






"""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__       (    UpperCAmelCase__				):






      '''simple docstring'''

      def __get__(		self  :						List[str]		,			lowercase_  :						Optional[int]		,			lowercase_  :						int=None):




          '''simple docstring'''


          if obj is None:
              return self
          if self.fget is None:
              raise AttributeError('''unreadable attribute''')
          SCREAMING_SNAKE_CASE_   :						Any							=	'''__cached_''' + self.fget.__name__
          SCREAMING_SNAKE_CASE_   :						List[Any]							=	getattr(lowercase_		,			lowercase_		,			lowercase_)
          if cached is None:
              SCREAMING_SNAKE_CASE_   :						Any							=	self.fget(lowercase_)
              setattr(lowercase_		,			lowercase_		,			lowercase_)
          return cached



def       _A    (__a							)				-> List[str]:
    """simple docstring"""






    SCREAMING_SNAKE_CASE_   :						str							=	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							)				-> List[str]:
    """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							)				-> Any:
    """simple docstring"""






    return isinstance(__a					,       np.ndarray							)



def       _A    (__a							)				-> List[str]:
    """simple docstring"""






    return _is_numpy(__a							)



def       _A    (__a							)				-> int:
    """simple docstring"""






    import torch

    return isinstance(__a					,       torch.Tensor							)



def       _A    (__a							)				-> int:
    """simple docstring"""






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



def       _A    (__a							)				-> List[str]:
    """simple docstring"""






    import torch

    return isinstance(__a					,       torch.device							)



def       _A    (__a							)				-> List[str]:
    """simple docstring"""






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



def       _A    (__a							)				-> int:
    """simple docstring"""






    import torch

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



def       _A    (__a							)				-> str:
    """simple docstring"""






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



def       _A    (__a							)				-> Optional[Any]:
    """simple docstring"""






    import tensorflow as tf

    return isinstance(__a					,       tf.Tensor							)



def       _A    (__a							)				-> Dict:
    """simple docstring"""






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



def       _A    (__a							)				-> Optional[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							)				-> Tuple:
    """simple docstring"""






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



def       _A    (__a							)				-> Dict:
    """simple docstring"""






    import jax.numpy as jnp  # noqa: F811

    return isinstance(__a					,       jnp.ndarray							)



def       _A    (__a							)				-> List[Any]:
    """simple docstring"""






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



def       _A    (__a							)				-> List[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							)				-> str:
    """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 							lowerCAmelCase__       (    UpperCAmelCase__				):






      '''simple docstring'''

      def _SCREAMING_SNAKE_CASE				(		self  :						str):




          '''simple docstring'''


          SCREAMING_SNAKE_CASE_   :						Optional[Any]							=	fields(self)

          # Safety and consistency checks
          if not len(lowercase_):
              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.')

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

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




          '''simple docstring'''


          raise Exception(F'You cannot use ``__delitem__`` on a {self.__class__.__name__} instance.')
      def _SCREAMING_SNAKE_CASE				(		self  :						Tuple		,			*lowercase_  :						Optional[Any]		,			**lowercase_  :						Dict):




          '''simple docstring'''


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




          '''simple docstring'''


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




          '''simple docstring'''


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




          '''simple docstring'''


          if isinstance(lowercase_		,			lowercase_):
              SCREAMING_SNAKE_CASE_   :						Optional[int]							=	dict(self.items())
              return inner_dict[k]
          else:
              return self.to_tuple()[k]
      def __setattr__(		self  :						List[str]		,			lowercase_  :						Optional[Any]		,			lowercase_  :						Dict):




          '''simple docstring'''


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




          '''simple docstring'''


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



      def _SCREAMING_SNAKE_CASE				(		self  :						int):




          '''simple docstring'''


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




class 							lowerCAmelCase__       (    UpperCAmelCase__       ,	UpperCAmelCase__				):






      '''simple docstring'''

      @classmethod
      def _SCREAMING_SNAKE_CASE				(		cls  :						Tuple		,			lowercase_  :						List[Any]):




          '''simple docstring'''


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




class 							lowerCAmelCase__       (    UpperCAmelCase__				):






      '''simple docstring'''

      __UpperCamelCase							=						"longest"
      __UpperCamelCase							=						"max_length"
      __UpperCamelCase							=						"do_not_pad"




class 							lowerCAmelCase__       (    UpperCAmelCase__				):






      '''simple docstring'''

      __UpperCamelCase							=						"pt"
      __UpperCamelCase							=						"tf"
      __UpperCamelCase							=						"np"
      __UpperCamelCase							=						"jax"




class 							lowerCAmelCase__       :






      '''simple docstring'''

      def __init__(		self  :						int		,			lowercase_  :						List[ContextManager]):




          '''simple docstring'''


          SCREAMING_SNAKE_CASE_   :						str							=	context_managers
          SCREAMING_SNAKE_CASE_   :						Optional[int]							=	ExitStack()
      def __enter__(		self  :						Tuple):




          '''simple docstring'''


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



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




          '''simple docstring'''


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



def       _A    (__a							)				-> Optional[Any]:
    """simple docstring"""






    SCREAMING_SNAKE_CASE_   :						int							=	infer_framework(__a							)
    if framework == "tf":
        SCREAMING_SNAKE_CASE_   :						Union[str, Any]							=	inspect.signature(model_class.call							)  # TensorFlow models
    elif framework == "pt":
        SCREAMING_SNAKE_CASE_   :						Optional[int]							=	inspect.signature(model_class.forward							)  # PyTorch models
    else:
        SCREAMING_SNAKE_CASE_   :						int							=	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							)				-> int:
    """simple docstring"""






    SCREAMING_SNAKE_CASE_   :						Optional[int]							=	model_class.__name__
    SCREAMING_SNAKE_CASE_   :						Optional[Any]							=	infer_framework(__a							)
    if framework == "tf":
        SCREAMING_SNAKE_CASE_   :						int							=	inspect.signature(model_class.call							)  # TensorFlow models
    elif framework == "pt":
        SCREAMING_SNAKE_CASE_   :						Any							=	inspect.signature(model_class.forward							)  # PyTorch models
    else:
        SCREAMING_SNAKE_CASE_   :						Dict							=	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 = "."							)				-> Tuple:
    """simple docstring"""






    def _flatten_dict(__a					,       __a=""					,       __a="."							):
        for k, v in d.items():
            SCREAMING_SNAKE_CASE_   :						List[str]							=	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							)				-> List[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							)				-> Optional[int]:
    """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							)				-> int:
    """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							)				-> Optional[int]:
    """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							)				-> Dict:
    """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							)				-> List[str]:
    """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							)				-> Optional[int]:
    """simple docstring"""






    for key, value in auto_map.items():
        if isinstance(__a					,       (tuple, list)							):
            SCREAMING_SNAKE_CASE_   :						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:
            SCREAMING_SNAKE_CASE_   :						Any							=	f'{repo_id}--{value}'

    return auto_map





def       _A    (__a							)				-> str:
    """simple docstring"""






    for base_class in inspect.getmro(__a							):
        SCREAMING_SNAKE_CASE_   :						Optional[Any]							=	base_class.__module__
        SCREAMING_SNAKE_CASE_   :						List[Any]							=	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 Mapping

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


UpperCAmelCase_     :				List[str]         =				logging.get_logger(__name__)

UpperCAmelCase_     :				Dict         =				{
    """facebook/data2vec-text-base""": """https://huggingface.co/data2vec/resolve/main/config.json""",
}




class 							lowerCAmelCase__       (    UpperCAmelCase__				):






      '''simple docstring'''

      __UpperCamelCase							=						"data2vec-text"
      def __init__(		self  :						Any		,			lowercase_  :						Any=30522		,			lowercase_  :						Any=768		,			lowercase_  :						Union[str, Any]=12		,			lowercase_  :						Dict=12		,			lowercase_  :						List[Any]=3072		,			lowercase_  :						str="gelu"		,			lowercase_  :						int=0.1		,			lowercase_  :						Dict=0.1		,			lowercase_  :						str=512		,			lowercase_  :						Optional[int]=2		,			lowercase_  :						int=0.02		,			lowercase_  :						int=1e-12		,			lowercase_  :						Any=1		,			lowercase_  :						Any=0		,			lowercase_  :						List[Any]=2		,			lowercase_  :						Tuple="absolute"		,			lowercase_  :						Optional[int]=True		,			lowercase_  :						int=None		,			**lowercase_  :						Tuple		,			):




          '''simple docstring'''


          super().__init__(pad_token_id=lowercase_		,			bos_token_id=lowercase_		,			eos_token_id=lowercase_		,			**lowercase_)

          SCREAMING_SNAKE_CASE_   :						List[Any]							=	vocab_size
          SCREAMING_SNAKE_CASE_   :						Tuple							=	hidden_size
          SCREAMING_SNAKE_CASE_   :						Optional[Any]							=	num_hidden_layers
          SCREAMING_SNAKE_CASE_   :						List[Any]							=	num_attention_heads
          SCREAMING_SNAKE_CASE_   :						Optional[Any]							=	hidden_act
          SCREAMING_SNAKE_CASE_   :						Any							=	intermediate_size
          SCREAMING_SNAKE_CASE_   :						Tuple							=	hidden_dropout_prob
          SCREAMING_SNAKE_CASE_   :						Tuple							=	attention_probs_dropout_prob
          SCREAMING_SNAKE_CASE_   :						Optional[int]							=	max_position_embeddings
          SCREAMING_SNAKE_CASE_   :						Union[str, Any]							=	type_vocab_size
          SCREAMING_SNAKE_CASE_   :						Optional[Any]							=	initializer_range
          SCREAMING_SNAKE_CASE_   :						List[Any]							=	layer_norm_eps
          SCREAMING_SNAKE_CASE_   :						str							=	position_embedding_type
          SCREAMING_SNAKE_CASE_   :						Optional[int]							=	use_cache
          SCREAMING_SNAKE_CASE_   :						str							=	classifier_dropout




class 							lowerCAmelCase__       (    UpperCAmelCase__				):






      '''simple docstring'''

      @property
      def _SCREAMING_SNAKE_CASE				(		self  :						int):




          '''simple docstring'''


          if self.task == "multiple-choice":
              SCREAMING_SNAKE_CASE_   :						List[Any]							=	{0: '''batch''', 1: '''choice''', 2: '''sequence'''}
          else:
              SCREAMING_SNAKE_CASE_   :						Any							=	{0: '''batch''', 1: '''sequence'''}
          return OrderedDict(
              [
                  ('''input_ids''', dynamic_axis),
                  ('''attention_mask''', dynamic_axis),
              ])


