


from importlib import import_module

from .logging import get_logger


lowercase_	   =     get_logger(__name__)


class 	A_ :




      '''simple docstring'''


      def __init__(    self:	str						,				a:	Optional[int]						,				a:	List[Any]=None    ):
       __lowerCamelCase		:							int		 =						attrs or []
       if module is not None:
        for key in module.__dict__:
         if key in attrs or not key.startswith('__'    ):
          setattr(self						,				a						,				getattr(a						,				a    )    )
       __lowerCamelCase		:							Union[str, Any]		 =						module._original_module if isinstance(a						,				_PatchedModuleObj    ) else module



class 	A_ :




      '''simple docstring'''


      __snake_case 	=       []




      def __init__(    self:	List[str]						,				a:	Dict						,				a:	str						,				a:	List[str]						,				a:	Dict=None    ):
       __lowerCamelCase		:							str		 =						obj
       __lowerCamelCase		:							Union[str, Any]		 =						target
       __lowerCamelCase		:							Any		 =						new
       __lowerCamelCase		:							Any		 =						target.split('.'    )[0]
       __lowerCamelCase		:							Any		 =						{}
       __lowerCamelCase		:							List[str]		 =						attrs or []




      def __enter__(    self:	List[Any]    ):
       *__lowerCamelCase ,					__lowerCamelCase		:							Any		 =						self.target.split('.'    )

       # Patch modules:
       # it's used to patch attributes of submodules like "os.path.join";
       # in this case we need to patch "os" and "os.path"

       for i in range(len(a    )    ):
        try:
         __lowerCamelCase		:							Union[str, Any]		 =						import_module('.'.join(submodules[: i + 1]    )    )
        except ModuleNotFoundError:
         continue
        # We iterate over all the globals in self.obj in case we find "os" or "os.path"
        for attr in self.obj.__dir__():
         __lowerCamelCase		:							Any		 =						getattr(self.obj						,				a    )
         # We don't check for the name of the global, but rather if its value *is* "os" or "os.path".
         # This allows to patch renamed modules like "from os import path as ospath".
         if obj_attr is submodule or (
             (isinstance(a						,				_PatchedModuleObj    ) and obj_attr._original_module is submodule)
         ):
          __lowerCamelCase		:							str		 =						obj_attr
          # patch at top level
          setattr(self.obj						,				a						,				_PatchedModuleObj(a						,				attrs=self.attrs    )    )
          __lowerCamelCase		:							int		 =						getattr(self.obj						,				a    )
          # construct lower levels patches
          for key in submodules[i + 1 :]:
           setattr(a						,				a						,				_PatchedModuleObj(getattr(a						,				a						,				a    )						,				attrs=self.attrs    )    )
           __lowerCamelCase		:							Union[str, Any]		 =						getattr(a						,				a    )
          # finally set the target attribute
          setattr(a						,				a						,				self.new    )

        # Patch attribute itself:
        # it's used for builtins like "open",
        # and also to patch "os.path.join" we may also need to patch "join"
        # itself if it was imported as "from os.path import join".

       if submodules:  # if it's an attribute of a submodule like "os.path.join"
        try:
         __lowerCamelCase		:							Union[str, Any]		 =						getattr(import_module('.'.join(a    )    )						,				a    )
        except (AttributeError, ModuleNotFoundError):
         return
        # We iterate over all the globals in self.obj in case we find "os.path.join"
        for attr in self.obj.__dir__():
         # We don't check for the name of the global, but rather if its value *is* "os.path.join".
         # This allows to patch renamed attributes like "from os.path import join as pjoin".
         if getattr(self.obj						,				a    ) is attr_value:
          __lowerCamelCase		:							int		 =						getattr(self.obj						,				a    )
          setattr(self.obj						,				a						,				self.new    )
       elif target_attr in globals()["__builtins__"]:  # if it'a s builtin like "open"
        __lowerCamelCase		:							List[Any]		 =						globals()['__builtins__'][target_attr]
        setattr(self.obj						,				a						,				self.new    )
       else:
        raise RuntimeError(F'Tried to patch attribute {target_attr} instead of a submodule.'    )




      def __exit__(    self:	int						,				*a:	List[str]    ):
       for attr in list(self.original    ):
        setattr(self.obj						,				a						,				self.original.pop(a    )    )




      def 					_snake_case     (    self:	Optional[int]    ):
       self.__enter__()
       self._active_patches.append(self    )




      def 					_snake_case     (    self:	List[str]    ):
       try:
        self._active_patches.remove(self    )
       except ValueError:
        # If the patch hasn't been started this will fail
        return None

       return self.__exit__()





import copy
from typing import TYPE_CHECKING, Any, Mapping, Optional, OrderedDict

from packaging import version

from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig
from ...utils import logging
from ..auto.configuration_auto import AutoConfig


if TYPE_CHECKING:
       from ... import PreTrainedTokenizerBase, TensorType

lowercase_	   =     logging.get_logger(__name__)


class 	A_ (	__UpperCamelCase   ):




      '''simple docstring'''


      __snake_case 	=       """vision-encoder-decoder"""
      __snake_case 	=       True




      def __init__(    self:	Union[str, Any]						,				**a:	Optional[Any]    ):
       super().__init__(**a    )
       if "encoder" not in kwargs or "decoder" not in kwargs:
        raise ValueError(
            F'A configuraton of type {self.model_type} cannot be instantiated because '
            F'not both `encoder` and `decoder` sub-configurations are passed, but only {kwargs}'    )

       __lowerCamelCase		:							Dict		 =						kwargs.pop('encoder'    )
       __lowerCamelCase		:							int		 =						encoder_config.pop('model_type'    )
       __lowerCamelCase		:							Any		 =						kwargs.pop('decoder'    )
       __lowerCamelCase		:							Union[str, Any]		 =						decoder_config.pop('model_type'    )

       __lowerCamelCase		:							Optional[Any]		 =						AutoConfig.for_model(a						,				**a    )
       __lowerCamelCase		:							List[Any]		 =						AutoConfig.for_model(a						,				**a    )
       __lowerCamelCase		:							Tuple		 =						True




      @classmethod
      def 					_snake_case     (    cls:	Optional[Any]						,				a:	PretrainedConfig						,				a:	PretrainedConfig						,				**a:	Dict    ):
       logger.info('Setting `config.is_decoder=True` and `config.add_cross_attention=True` for decoder_config'    )
       __lowerCamelCase		:							Optional[Any]		 =						True
       __lowerCamelCase		:							Optional[Any]		 =						True

       return cls(encoder=encoder_config.to_dict()						,				decoder=decoder_config.to_dict()						,				**a    )




      def 					_snake_case     (    self:	str    ):
       __lowerCamelCase		:							int		 =						copy.deepcopy(self.__dict__    )
       __lowerCamelCase		:							Dict		 =						self.encoder.to_dict()
       __lowerCamelCase		:							Union[str, Any]		 =						self.decoder.to_dict()
       __lowerCamelCase		:							Optional[int]		 =						self.__class__.model_type
       return output



class 	A_ (	__UpperCamelCase   ):




      '''simple docstring'''


      __snake_case 	=       version.parse("""1.11"""   )




      @property
      def 					_snake_case     (    self:	Union[str, Any]    ):
       return OrderedDict(
           [
               ('pixel_values', {0: 'batch', 1: 'num_channels', 2: 'height', 3: 'width'}),
           ]    )




      @property
      def 					_snake_case     (    self:	Optional[Any]    ):
       return 1e-4




      @property
      def 					_snake_case     (    self:	List[str]    ):
       return OrderedDict({'last_hidden_state': {0: 'batch', 1: 'encoder_sequence'}}    )



class 	A_ (	__UpperCamelCase   ):




      '''simple docstring'''


      @property
      def 					_snake_case     (    self:	Tuple    ):
       __lowerCamelCase		:							Union[str, Any]		 =						OrderedDict()
       __lowerCamelCase		:							Union[str, Any]		 =						{0: 'batch', 1: 'past_decoder_sequence + sequence'}
       __lowerCamelCase		:							Optional[Any]		 =						{0: 'batch', 1: 'past_decoder_sequence + sequence'}
       __lowerCamelCase		:							Dict		 =						{0: 'batch', 1: 'encoder_sequence'}

       return common_inputs




      def 					_snake_case     (    self:	List[Any]						,				a:	"PreTrainedTokenizerBase"						,				a:	int = -1						,				a:	int = -1						,				a:	bool = False						,				a:	Optional["TensorType"] = None						,				):
       import torch

       __lowerCamelCase		:							str		 =						OrderedDict()

       __lowerCamelCase		:							List[Any]		 =						super().generate_dummy_inputs(
           a						,				batch_size=a						,				seq_length=a						,				is_pair=a						,				framework=a    )

       __lowerCamelCase ,					__lowerCamelCase		:							Dict		 =						dummy_input['input_ids'].shape
       __lowerCamelCase		:							str		 =						(batch, encoder_sequence, self._config.encoder_hidden_size)
       __lowerCamelCase		:							str		 =						dummy_input.pop('input_ids'    )
       __lowerCamelCase		:							Union[str, Any]		 =						dummy_input.pop('attention_mask'    )
       __lowerCamelCase		:							str		 =						torch.zeros(a    )

       return common_inputs



class 	A_ (	__UpperCamelCase   ):




      '''simple docstring'''


      @property
      def 					_snake_case     (    self:	List[Any]    ):
       pass




      def 					_snake_case     (    self:	List[str]						,				a:	PretrainedConfig    ):
       return VisionEncoderDecoderEncoderOnnxConfig(a    )




      def 					_snake_case     (    self:	Optional[int]						,				a:	PretrainedConfig						,				a:	PretrainedConfig						,				a:	str = "default"    ):
       __lowerCamelCase		:							List[Any]		 =						encoder_config.hidden_size
       return VisionEncoderDecoderDecoderOnnxConfig(a						,				a    )

