'''simple docstring'''




import copy
import os
from typing import Union

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


__lowercase          =  logging.get_logger(__name__)

__lowercase          =  {
    'BAAI/AltCLIP': 'https://huggingface.co/BAAI/AltCLIP/resolve/main/config.json',
    # See all AltCLIP models at https://huggingface.co/models?filter=altclip
}






class 				a__(					lowerCAmelCase__	):


			'''simple docstring'''






			UpperCAmelCase_			:     List[str]      =       '''altclip_text_model'''



			def __init__(   self       ,    __lowerCAmelCase=250002       ,    __lowerCAmelCase=1024       ,    __lowerCAmelCase=24       ,    __lowerCAmelCase=16       ,    __lowerCAmelCase=4096       ,    __lowerCAmelCase="gelu"       ,    __lowerCAmelCase=0.1       ,    __lowerCAmelCase=0.1       ,    __lowerCAmelCase=514       ,    __lowerCAmelCase=1       ,    __lowerCAmelCase=0.02       ,    __lowerCAmelCase=0.02       ,    __lowerCAmelCase=1E-0_5       ,    __lowerCAmelCase=1       ,    __lowerCAmelCase=0       ,    __lowerCAmelCase=2       ,    __lowerCAmelCase="absolute"       ,    __lowerCAmelCase=True       ,    __lowerCAmelCase=768       ,    **__lowerCAmelCase       ,    ):




					"""simple docstring"""


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

					lowerCAmelCase   					=  vocab_size
					lowerCAmelCase   					=  hidden_size
					lowerCAmelCase   					=  num_hidden_layers
					lowerCAmelCase   					=  num_attention_heads
					lowerCAmelCase   					=  hidden_act
					lowerCAmelCase   					=  intermediate_size
					lowerCAmelCase   					=  hidden_dropout_prob
					lowerCAmelCase   					=  attention_probs_dropout_prob
					lowerCAmelCase   					=  max_position_embeddings
					lowerCAmelCase   					=  type_vocab_size
					lowerCAmelCase   					=  initializer_range
					lowerCAmelCase   					=  initializer_factor
					lowerCAmelCase   					=  layer_norm_eps
					lowerCAmelCase   					=  position_embedding_type
					lowerCAmelCase   					=  use_cache
					lowerCAmelCase   					=  project_dim







class 				a__(					lowerCAmelCase__	):


			'''simple docstring'''






			UpperCAmelCase_			:     Optional[Any]      =       '''altclip_vision_model'''



			def __init__(   self       ,    __lowerCAmelCase=768       ,    __lowerCAmelCase=3072       ,    __lowerCAmelCase=512       ,    __lowerCAmelCase=12       ,    __lowerCAmelCase=12       ,    __lowerCAmelCase=3       ,    __lowerCAmelCase=224       ,    __lowerCAmelCase=32       ,    __lowerCAmelCase="quick_gelu"       ,    __lowerCAmelCase=1E-5       ,    __lowerCAmelCase=0.0       ,    __lowerCAmelCase=0.02       ,    __lowerCAmelCase=1.0       ,    **__lowerCAmelCase       ,    ):




					"""simple docstring"""


					super().__init__(**__lowerCAmelCase)

					lowerCAmelCase   					=  hidden_size
					lowerCAmelCase   					=  intermediate_size
					lowerCAmelCase   					=  projection_dim
					lowerCAmelCase   					=  num_hidden_layers
					lowerCAmelCase   					=  num_attention_heads
					lowerCAmelCase   					=  num_channels
					lowerCAmelCase   					=  patch_size
					lowerCAmelCase   					=  image_size
					lowerCAmelCase   					=  initializer_range
					lowerCAmelCase   					=  initializer_factor
					lowerCAmelCase   					=  attention_dropout
					lowerCAmelCase   					=  layer_norm_eps
					lowerCAmelCase   					=  hidden_act







			@classmethod
			def 							a_       (   cls       ,    __lowerCAmelCase       ,    **__lowerCAmelCase):




					"""simple docstring"""


					cls._set_token_in_kwargs(__lowerCAmelCase)

					lowerCAmelCase   					=  cls.get_config_dict(__lowerCAmelCase       ,    **__lowerCAmelCase)

					# get the vision config dict if we are loading from AltCLIPConfig
					if config_dict.get("""model_type""") == "altclip":
							lowerCAmelCase   					=  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(__lowerCAmelCase       ,    **__lowerCAmelCase)







class 				a__(					lowerCAmelCase__	):


			'''simple docstring'''






			UpperCAmelCase_			:     Optional[Any]      =       '''altclip'''
			UpperCAmelCase_			:     Any      =       True



			def __init__(   self       ,    __lowerCAmelCase=None       ,    __lowerCAmelCase=None       ,    __lowerCAmelCase=768       ,    __lowerCAmelCase=2.6592       ,    **__lowerCAmelCase):




					"""simple docstring"""


					lowerCAmelCase   					=  kwargs.pop("""text_config_dict"""       ,    __lowerCAmelCase)
					lowerCAmelCase   					=  kwargs.pop("""vision_config_dict"""       ,    __lowerCAmelCase)

					super().__init__(**__lowerCAmelCase)

					# Instead of simply assigning `[text|vision]_config_dict` to `[text|vision]_config`, we use the values in
					# `[text|vision]_config_dict` to update the values in `[text|vision]_config`. The values should be same in most
					# cases, but we don't want to break anything regarding `_config_dict` that existed before commit `8827e1b2`.
					if text_config_dict is not None:
							if text_config is None:
									lowerCAmelCase   					=  {}

							# This is the complete result when using `text_config_dict`.
							lowerCAmelCase   					=  AltCLIPTextConfig(**__lowerCAmelCase).to_dict()

							# Give a warning if the values exist in both `_text_config_dict` and `text_config` but being different.
							for key, value in _text_config_dict.items():
									if key in text_config and value != text_config[key] and key not in ["transformers_version"]:
											# If specified in `text_config_dict`
											if key in text_config_dict:
													lowerCAmelCase   					=  (
													    f"`{key}` is found in both `text_config_dict` and `text_config` but with different values. "
													    f"The value `text_config_dict[\"{key}\"]` will be used instead."
													)
											# If inferred from default argument values (just to be super careful)
											else:
													lowerCAmelCase   					=  (
													    f"`text_config_dict` is provided which will be used to initialize `AltCLIPTextConfig`. The "
													    f"value `text_config[\"{key}\"]` will be overriden."
													)
											logger.warning(__lowerCAmelCase)

            # Update all values in `text_config` with the ones in `_text_config_dict`.
							text_config.update(_text_config_dict)

					if vision_config_dict is not None:
							if vision_config is None:
									lowerCAmelCase   					=  {}

							# This is the complete result when using `vision_config_dict`.
							lowerCAmelCase   					=  AltCLIPVisionConfig(**__lowerCAmelCase).to_dict()
							# convert keys to string instead of integer
							if "id2label" in _vision_config_dict:
									lowerCAmelCase   					=  {
									    str(__lowerCAmelCase): value for key, value in _vision_config_dict["""id2label"""].items()
									}

							# Give a warning if the values exist in both `_vision_config_dict` and `vision_config` but being different.
							for key, value in _vision_config_dict.items():
									if key in vision_config and value != vision_config[key] and key not in ["transformers_version"]:
											# If specified in `vision_config_dict`
											if key in vision_config_dict:
													lowerCAmelCase   					=  (
													    f"`{key}` is found in both `vision_config_dict` and `vision_config` but with different "
													    f"values. The value `vision_config_dict[\"{key}\"]` will be used instead."
													)
											# If inferred from default argument values (just to be super careful)
											else:
													lowerCAmelCase   					=  (
													    f"`vision_config_dict` is provided which will be used to initialize `AltCLIPVisionConfig`. "
													    f"The value `vision_config[\"{key}\"]` will be overriden."
													)
											logger.warning(__lowerCAmelCase)

            # Update all values in `vision_config` with the ones in `_vision_config_dict`.
							vision_config.update(_vision_config_dict)

					if text_config is None:
							lowerCAmelCase   					=  {}
							logger.info("""`text_config` is `None`. Initializing the `AltCLIPTextConfig` with default values.""")

					if vision_config is None:
							lowerCAmelCase   					=  {}
							logger.info("""`vision_config` is `None`. initializing the `AltCLIPVisionConfig` with default values.""")

					lowerCAmelCase   					=  AltCLIPTextConfig(**__lowerCAmelCase)
					lowerCAmelCase   					=  AltCLIPVisionConfig(**__lowerCAmelCase)

					lowerCAmelCase   					=  projection_dim
					lowerCAmelCase   					=  logit_scale_init_value
					lowerCAmelCase   					=  1.0



			@classmethod
			def 							a_       (   cls       ,    __lowerCAmelCase       ,    __lowerCAmelCase       ,    **__lowerCAmelCase):




					"""simple docstring"""


					return cls(text_config=text_config.to_dict()       ,    vision_config=vision_config.to_dict()       ,    **__lowerCAmelCase)







			def 							a_       (   self):




					"""simple docstring"""


					lowerCAmelCase   					=  copy.deepcopy(self.__dict__)
					lowerCAmelCase   					=  self.text_config.to_dict()
					lowerCAmelCase   					=  self.vision_config.to_dict()
					lowerCAmelCase   					=  self.__class__.model_type
					return output








"""simple docstring"""






from importlib import import_module

from .logging import get_logger


UpperCAmelCase    :     Any   						=		get_logger(__name__)





class      lowerCamelCase__   :







					"""simple docstring"""


					def __init__(       self    : Optional[int] ,       UpperCamelCase    : List[Any] ,       UpperCamelCase    : int=None  ):
												'''simple docstring'''






												__UpperCAmelCase   :						Tuple      							=					attrs or []
												if module is not None:
																			for key in module.__dict__:
																										if key in attrs or not key.startswith("""__"""  ):
																																	setattr(self ,       UpperCamelCase ,       getattr(UpperCamelCase ,       UpperCamelCase  )  )
												__UpperCAmelCase   :						Any      							=					module._original_module if isinstance(UpperCamelCase ,       _PatchedModuleObj  ) else module






class      lowerCamelCase__   :







					"""simple docstring"""


					__a	       =							[]






					def __init__(       self    : str ,       UpperCamelCase    : Tuple ,       UpperCamelCase    : str ,       UpperCamelCase    : List[str] ,       UpperCamelCase    : Optional[Any]=None  ):
												'''simple docstring'''






												__UpperCAmelCase   :						int      							=					obj
												__UpperCAmelCase   :						Union[str, Any]      							=					target
												__UpperCAmelCase   :						List[str]      							=					new
												__UpperCAmelCase   :						Optional[int]      							=					target.split("""."""  )[0]
												__UpperCAmelCase   :						Tuple      							=					{}
												__UpperCAmelCase   :						Union[str, Any]      							=					attrs or []






					def __enter__(       self    : Dict  ):
												'''simple docstring'''






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






					def __exit__(       self    : str ,       *UpperCamelCase    : Optional[int]  ):
												'''simple docstring'''






												for attr in list(self.original  ):
																			setattr(self.obj ,       UpperCamelCase ,       self.original.pop(UpperCamelCase  )  )






					def lowerCamelCase__							(       self    : int  ):
												'''simple docstring'''






												self.__enter__()
												self._active_patches.append(self  )






					def lowerCamelCase__							(       self    : List[Any]  ):
												'''simple docstring'''






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

												return self.__exit__()
