



import copy
import os
from typing import Union

from ...configuration_utils import PretrainedConfig
from ...utils import logging


A__								=						logging.get_logger(__name__)

A__								=						{
    '''microsoft/git-base''': '''https://huggingface.co/microsoft/git-base/resolve/main/config.json''',
}


class       a							(			__lowerCamelCase				):
		__lowerCAmelCase	:    Optional[Any]											=					"""git_vision_model"""



		def __init__(     self     :Any   ,__lowercase     :Optional[int]=7_6_8   ,__lowercase     :List[Any]=3_0_7_2   ,__lowercase     :Dict=1_2   ,__lowercase     :Union[str, Any]=1_2   ,__lowercase     :Optional[int]=3   ,__lowercase     :str=2_2_4   ,__lowercase     :List[Any]=1_6   ,__lowercase     :Any="quick_gelu"   ,__lowercase     :List[Any]=1e-5   ,__lowercase     :List[str]=0.0   ,__lowercase     :str=0.02   ,**__lowercase     :Optional[int]   ,):
						super().__init__(**__lowercase  )

						snake_case__	:      int     		=	hidden_size
						snake_case__	:      Optional[int]     		=	intermediate_size
						snake_case__	:      str     		=	num_hidden_layers
						snake_case__	:      Tuple     		=	num_attention_heads
						snake_case__	:      Optional[int]     		=	num_channels
						snake_case__	:      Tuple     		=	patch_size
						snake_case__	:      Union[str, Any]     		=	image_size
						snake_case__	:      Union[str, Any]     		=	initializer_range
						snake_case__	:      Optional[int]     		=	attention_dropout
						snake_case__	:      Optional[int]     		=	layer_norm_eps
						snake_case__	:      Tuple     		=	hidden_act






		@classmethod
		def 	__lowerCamelCase			(     cls     :Optional[int]   ,__lowercase     :Union[str, os.PathLike]   ,**__lowercase     :Tuple  ):
						cls._set_token_in_kwargs(__lowercase  )

						snake_case__		, snake_case__	:      List[str]     		=	cls.get_config_dict(__lowercase   ,**__lowercase  )

						# get the vision config dict if we are loading from GITConfig
						if config_dict.get('''model_type'''  ) == "git":
										snake_case__	:      List[str]     		=	config_dict['''vision_config''']

						if "model_type" in config_dict and hasattr(cls   ,'''model_type'''  ) and config_dict["model_type"] != cls.model_type:
										logger.warning(
										    F"""You are using a model of type {config_dict['model_type']} to instantiate a model of type """
										    F"""{cls.model_type}. This is not supported for all configurations of models and can yield errors."""  )

						return cls.from_dict(__lowercase   ,**__lowercase  )


class       a							(			__lowerCamelCase				):
		__lowerCAmelCase	:    Optional[int]											=					"""git"""



		def __init__(     self     :int   ,__lowercase     :Optional[Any]=None   ,__lowercase     :Optional[Any]=3_0_5_2_2   ,__lowercase     :Union[str, Any]=7_6_8   ,__lowercase     :str=6   ,__lowercase     :Dict=1_2   ,__lowercase     :int=3_0_7_2   ,__lowercase     :Union[str, Any]="gelu"   ,__lowercase     :Optional[Any]=0.1   ,__lowercase     :Tuple=0.1   ,__lowercase     :Optional[Any]=1_0_2_4   ,__lowercase     :Optional[int]=0.02   ,__lowercase     :List[Any]=1e-1_2   ,__lowercase     :List[str]=0   ,__lowercase     :Union[str, Any]="absolute"   ,__lowercase     :str=True   ,__lowercase     :List[Any]=False   ,__lowercase     :List[Any]=1_0_1   ,__lowercase     :Optional[Any]=1_0_2   ,__lowercase     :List[Any]=None   ,**__lowercase     :str   ,):
						super().__init__(bos_token_id=__lowercase   ,eos_token_id=__lowercase   ,pad_token_id=__lowercase   ,**__lowercase  )

						if vision_config is None:
										snake_case__	:      str     		=	{}
										logger.info('''vision_config is None. initializing the GitVisionConfig with default values.'''  )

						snake_case__	:      List[str]     		=	GitVisionConfig(**__lowercase  )
						snake_case__	:      Any     		=	vocab_size
						snake_case__	:      Tuple     		=	hidden_size
						snake_case__	:      Union[str, Any]     		=	num_hidden_layers
						snake_case__	:      Optional[Any]     		=	num_attention_heads
						snake_case__	:      Union[str, Any]     		=	hidden_act
						snake_case__	:      Any     		=	intermediate_size
						snake_case__	:      Union[str, Any]     		=	hidden_dropout_prob
						snake_case__	:      Tuple     		=	attention_probs_dropout_prob
						snake_case__	:      Union[str, Any]     		=	max_position_embeddings
						snake_case__	:      Any     		=	initializer_range
						snake_case__	:      Union[str, Any]     		=	layer_norm_eps
						snake_case__	:      Dict     		=	position_embedding_type
						snake_case__	:      int     		=	use_cache
						snake_case__	:      Dict     		=	tie_word_embeddings
						snake_case__	:      Union[str, Any]     		=	num_image_with_embedding

						snake_case__	:      Tuple     		=	bos_token_id
						snake_case__	:      Optional[int]     		=	eos_token_id






		def 	__lowerCamelCase			(     self     :Union[str, Any]  ):
						snake_case__	:      List[Any]     		=	copy.deepcopy(self.__dict__  )
						snake_case__	:      Any     		=	self.vision_config.to_dict()
						snake_case__	:      str     		=	self.__class__.model_type
						return output






from importlib import import_module

from .logging import get_logger


A__								=						get_logger(__name__)


class       a							:



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


class       a							:
		__lowerCAmelCase	:    Any											=					[]



		def __init__(     self     :List[str]   ,__lowercase     :Optional[Any]   ,__lowercase     :str   ,__lowercase     :Dict   ,__lowercase     :Any=None  ):
						snake_case__	:      Dict     		=	obj
						snake_case__	:      Dict     		=	target
						snake_case__	:      List[str]     		=	new
						snake_case__	:      int     		=	target.split('''.'''  )[0]
						snake_case__	:      List[str]     		=	{}
						snake_case__	:      Any     		=	attrs or []



		def __enter__(     self     :Tuple  ):
						*snake_case__		, snake_case__	:      str     		=	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(__lowercase  )  ):
										try:
														snake_case__	:      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__():
														snake_case__	:      Optional[int]     		=	getattr(self.obj   ,__lowercase  )
														# 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(__lowercase   ,_PatchedModuleObj  ) and obj_attr._original_module is submodule)
														):
																		snake_case__	:      List[Any]     		=	obj_attr
																		# patch at top level
																		setattr(self.obj   ,__lowercase   ,_PatchedModuleObj(__lowercase   ,attrs=self.attrs  )  )
																		snake_case__	:      List[Any]     		=	getattr(self.obj   ,__lowercase  )
																		# construct lower levels patches
																		for key in submodules[i + 1 :]:
																						setattr(__lowercase   ,__lowercase   ,_PatchedModuleObj(getattr(__lowercase   ,__lowercase   ,__lowercase  )   ,attrs=self.attrs  )  )
																						snake_case__	:      List[Any]     		=	getattr(__lowercase   ,__lowercase  )
																		# finally set the target attribute
																		setattr(__lowercase   ,__lowercase   ,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:
														snake_case__	:      int     		=	getattr(import_module('''.'''.join(__lowercase  )  )   ,__lowercase  )
										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   ,__lowercase  ) is attr_value:
																		snake_case__	:      str     		=	getattr(self.obj   ,__lowercase  )
																		setattr(self.obj   ,__lowercase   ,self.new  )
						elif target_attr in globals()["__builtins__"]:  # if it'a s builtin like "open"
										snake_case__	:      str     		=	globals()['''__builtins__'''][target_attr]
										setattr(self.obj   ,__lowercase   ,self.new  )
						else:
										raise RuntimeError(F"""Tried to patch attribute {target_attr} instead of a submodule."""  )



		def __exit__(     self     :Tuple   ,*__lowercase     :Optional[int]  ):
						for attr in list(self.original  ):
										setattr(self.obj   ,__lowercase   ,self.original.pop(__lowercase  )  )



		def 	__lowerCamelCase			(     self     :Tuple  ):
						self.__enter__()
						self._active_patches.append(self  )






		def 	__lowerCamelCase			(     self     :Dict  ):
						try:
										self._active_patches.remove(self  )
						except ValueError:
										# If the patch hasn't been started this will fail
										return None

						return self.__exit__()

