




import copy
import os
from typing import Union

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


__A						:							int							=  logging.get_logger(__name__)

__A						:							List[str]							=  {
    """BridgeTower/bridgetower-base""": """https://huggingface.co/BridgeTower/bridgetower-base/blob/main/config.json""",
    """BridgeTower/bridgetower-base-itm-mlm""": (
        """https://huggingface.co/BridgeTower/bridgetower-base-itm-mlm/blob/main/config.json"""
    ),
}




class 			UpperCAmelCase_      (   __lowercase       ):




							'''simple docstring'''



							a__						  =			'bridgetower_vision_model'





							def __init__(					self       :	Union[str, Any]       ,     a       :	List[str]=768       ,     a       :	Tuple=12       ,     a       :	List[str]=3       ,     a       :	Tuple=16       ,     a       :	Union[str, Any]=288       ,     a       :	int=1       ,     a       :	Any=1E-0_5       ,     a       :	int=False       ,     a       :	Optional[Any]=True       ,     a       :	Union[str, Any]=False       ,     **a       :	List[str]       ,     )			->					Optional[int]:
										super().__init__(**__A			)
										SCREAMING_SNAKE_CASE           =					hidden_size
										SCREAMING_SNAKE_CASE           =					num_hidden_layers
										SCREAMING_SNAKE_CASE           =					num_channels
										SCREAMING_SNAKE_CASE           =					patch_size
										SCREAMING_SNAKE_CASE           =					image_size
										SCREAMING_SNAKE_CASE           =					initializer_factor
										SCREAMING_SNAKE_CASE           =					layer_norm_eps
										SCREAMING_SNAKE_CASE           =					stop_gradient
										SCREAMING_SNAKE_CASE           =					share_layernorm
										SCREAMING_SNAKE_CASE           =					remove_last_layer







							@classmethod
							def    _UpperCAmelCase     (					cls       :	Optional[Any]       ,     a       :	Dict       ,     **a       :	Any			)			->					"PretrainedConfig":
										SCREAMING_SNAKE_CASE     ,  SCREAMING_SNAKE_CASE           =					cls.get_config_dict(__A       ,     **__A			)

										if config_dict.get("""model_type"""			) == "bridgetower":
													SCREAMING_SNAKE_CASE           =					config_dict["""text_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(__A       ,     **__A			)





class 			UpperCAmelCase_      (   __lowercase       ):




							'''simple docstring'''



							a__						  =			'bridgetower_text_model'





							def __init__(					self       :	Union[str, Any]       ,     a       :	Optional[Any]=50_265       ,     a       :	Union[str, Any]=768       ,     a       :	Dict=12       ,     a       :	Dict=12       ,     a       :	Union[str, Any]=1       ,     a       :	Union[str, Any]=3_072       ,     a       :	List[str]="gelu"       ,     a       :	Union[str, Any]=0.1       ,     a       :	Union[str, Any]=0.1       ,     a       :	Optional[Any]=514       ,     a       :	Tuple=1       ,     a       :	Union[str, Any]=1E-0_5       ,     a       :	Optional[Any]=1       ,     a       :	str=0       ,     a       :	List[Any]=2       ,     a       :	Union[str, Any]="absolute"       ,     a       :	str=True       ,     **a       :	Union[str, Any]       ,     )			->					Dict:
										super().__init__(**__A			)

										SCREAMING_SNAKE_CASE           =					vocab_size
										SCREAMING_SNAKE_CASE           =					hidden_size
										SCREAMING_SNAKE_CASE           =					num_hidden_layers
										SCREAMING_SNAKE_CASE           =					num_attention_heads
										SCREAMING_SNAKE_CASE           =					hidden_act
										SCREAMING_SNAKE_CASE           =					initializer_factor
										SCREAMING_SNAKE_CASE           =					intermediate_size
										SCREAMING_SNAKE_CASE           =					hidden_dropout_prob
										SCREAMING_SNAKE_CASE           =					attention_probs_dropout_prob
										SCREAMING_SNAKE_CASE           =					max_position_embeddings
										SCREAMING_SNAKE_CASE           =					type_vocab_size
										SCREAMING_SNAKE_CASE           =					layer_norm_eps
										SCREAMING_SNAKE_CASE           =					position_embedding_type
										SCREAMING_SNAKE_CASE           =					use_cache
										SCREAMING_SNAKE_CASE           =					pad_token_id
										SCREAMING_SNAKE_CASE           =					bos_token_id
										SCREAMING_SNAKE_CASE           =					eos_token_id







							@classmethod
							def    _UpperCAmelCase     (					cls       :	Dict       ,     a       :	Dict       ,     **a       :	List[str]			)			->					"PretrainedConfig":
										SCREAMING_SNAKE_CASE     ,  SCREAMING_SNAKE_CASE           =					cls.get_config_dict(__A       ,     **__A			)

										if config_dict.get("""model_type"""			) == "bridgetower":
													SCREAMING_SNAKE_CASE           =					config_dict["""text_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(__A       ,     **__A			)





class 			UpperCAmelCase_      (   __lowercase       ):




							'''simple docstring'''



							a__						  =			'bridgetower'





							def __init__(					self       :	Dict       ,     a       :	Optional[Any]=True       ,     a       :	Optional[Any]="gelu"       ,     a       :	List[Any]=768       ,     a       :	Dict=1       ,     a       :	Union[str, Any]=1E-0_5       ,     a       :	int=False       ,     a       :	Optional[int]="add"       ,     a       :	Dict=12       ,     a       :	str=6       ,     a       :	int=False       ,     a       :	Any=False       ,     a       :	int=None       ,     a       :	Dict=None       ,     **a       :	Dict       ,     )			->					Any:
										# TODO: remove this once the Hub files are updated.
										SCREAMING_SNAKE_CASE           =					kwargs.pop("""text_config_dict"""       ,     __A			)
										SCREAMING_SNAKE_CASE           =					kwargs.pop("""vision_config_dict"""       ,     __A			)

										super().__init__(**__A			)
										SCREAMING_SNAKE_CASE           =					share_cross_modal_transformer_layers
										SCREAMING_SNAKE_CASE           =					hidden_act
										SCREAMING_SNAKE_CASE           =					hidden_size
										SCREAMING_SNAKE_CASE           =					initializer_factor
										SCREAMING_SNAKE_CASE           =					layer_norm_eps
										SCREAMING_SNAKE_CASE           =					share_link_tower_layers
										SCREAMING_SNAKE_CASE           =					link_tower_type
										SCREAMING_SNAKE_CASE           =					num_attention_heads
										SCREAMING_SNAKE_CASE           =					num_hidden_layers
										SCREAMING_SNAKE_CASE           =					tie_word_embeddings
										SCREAMING_SNAKE_CASE           =					init_layernorm_from_vision_encoder

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

										if vision_config is None:
													SCREAMING_SNAKE_CASE           =					{}
													logger.info("""`vision_config` is `None`. Initializing the `BridgeTowerVisionConfig` with default values."""			)

										SCREAMING_SNAKE_CASE           =					BridgeTowerTextConfig(**__A			)
										SCREAMING_SNAKE_CASE           =					BridgeTowerVisionConfig(**__A			)





							@classmethod
							def    _UpperCAmelCase     (					cls       :	int       ,     a       :	Tuple       ,     a       :	Dict       ,     **a       :	Optional[Any]			)			->					List[Any]:
										return cls(text_config=text_config.to_dict()       ,     vision_config=vision_config.to_dict()       ,     **__A			)







							def    _UpperCAmelCase     (					self       :	Dict			)			->					Optional[Any]:
										SCREAMING_SNAKE_CASE           =					copy.deepcopy(self.__dict__			)
										SCREAMING_SNAKE_CASE           =					self.text_config.to_dict()
										SCREAMING_SNAKE_CASE           =					self.vision_config.to_dict()
										SCREAMING_SNAKE_CASE           =					self.__class__.model_type
										return output












import os
import shutil
from pathlib import Path
from typing import Optional, Union

import numpy as np
from huggingface_hub import hf_hub_download

from ..utils import ONNX_EXTERNAL_WEIGHTS_NAME, ONNX_WEIGHTS_NAME, is_onnx_available, logging


if is_onnx_available():
		import onnxruntime as ort


__A						:							str							=  logging.get_logger(__name__)

__A						:							str							=  {
    """tensor(bool)""": np.bool_,
    """tensor(int8)""": np.inta,
    """tensor(uint8)""": np.uinta,
    """tensor(int16)""": np.intaa,
    """tensor(uint16)""": np.uintaa,
    """tensor(int32)""": np.intaa,
    """tensor(uint32)""": np.uintaa,
    """tensor(int64)""": np.intaa,
    """tensor(uint64)""": np.uintaa,
    """tensor(float16)""": np.floataa,
    """tensor(float)""": np.floataa,
    """tensor(double)""": np.floataa,
}




class 			UpperCAmelCase_      :




							'''simple docstring'''



							def __init__(					self       :	List[str]       ,     a       :	Tuple=None       ,     **a       :	Any			)			->					List[str]:
										logger.info("""`diffusers.OnnxRuntimeModel` is experimental and might change in the future."""			)
										SCREAMING_SNAKE_CASE           =					model
										SCREAMING_SNAKE_CASE           =					kwargs.get("""model_save_dir"""       ,     a			)
										SCREAMING_SNAKE_CASE           =					kwargs.get("""latest_model_name"""       ,     a			)





							def __call__(					self       :	List[str]       ,     **a       :	Any			)			->					List[Any]:
										SCREAMING_SNAKE_CASE           =					{k: np.array(a			) for k, v in kwargs.items()}
										return self.model.run(a       ,     a			)





							@staticmethod
							def    _UpperCAmelCase     (					a       :	Union[str, Path]       ,     a       :	Any=None       ,     a       :	Optional[int]=None			)			->					Optional[Any]:
										if provider is None:
													logger.info("""No onnxruntime provider specified, using CPUExecutionProvider"""			)
													SCREAMING_SNAKE_CASE           =					"""CPUExecutionProvider"""

										return ort.InferenceSession(a       ,     providers=[provider]       ,     sess_options=a			)





							def    _UpperCAmelCase     (					self       :	str       ,     a       :	Union[str, Path]       ,     a       :	Optional[str] = None       ,     **a       :	str			)			->					Tuple:
										SCREAMING_SNAKE_CASE           =					file_name if file_name is not None else ONNX_WEIGHTS_NAME

										SCREAMING_SNAKE_CASE           =					self.model_save_dir.joinpath(self.latest_model_name			)
										SCREAMING_SNAKE_CASE           =					Path(a			).joinpath(a			)
										try:
													shutil.copyfile(a       ,     a			)
										except shutil.SameFileError:
													pass

										# copy external weights (for models >2GB)
										SCREAMING_SNAKE_CASE           =					self.model_save_dir.joinpath(a			)
										if src_path.exists():
													SCREAMING_SNAKE_CASE           =					Path(a			).joinpath(a			)
													try:
																shutil.copyfile(a       ,     a			)
													except shutil.SameFileError:
																pass





							def    _UpperCAmelCase     (					self       :	Dict       ,     a       :	Union[str, os.PathLike]       ,     **a       :	Tuple       ,     )			->					str:
										if os.path.isfile(a			):
													logger.error(f"""Provided path ({save_directory}) should be a directory, not a file"""			)
													return

										os.makedirs(a       ,     exist_ok=a			)

										# saving model weights/files
										self._save_pretrained(a       ,     **a			)





							@classmethod
							def    _UpperCAmelCase     (					cls       :	List[Any]       ,     a       :	Union[str, Path]       ,     a       :	Optional[Union[bool, str, None]] = None       ,     a       :	Optional[Union[str, None]] = None       ,     a       :	bool = False       ,     a       :	Optional[str] = None       ,     a       :	Optional[str] = None       ,     a       :	Optional[str] = None       ,     a       :	Optional["ort.SessionOptions"] = None       ,     **a       :	Union[str, Any]       ,     )			->					List[str]:
										SCREAMING_SNAKE_CASE           =					file_name if file_name is not None else ONNX_WEIGHTS_NAME
										# load model from local directory
										if os.path.isdir(a			):
													SCREAMING_SNAKE_CASE           =					OnnxRuntimeModel.load_model(
													    os.path.join(a       ,     a			)       ,     provider=a       ,     sess_options=a			)
													SCREAMING_SNAKE_CASE           =					Path(a			)
										# load model from hub
										else:
													# download model
													SCREAMING_SNAKE_CASE           =					hf_hub_download(
													    repo_id=a       ,     filename=a       ,     use_auth_token=a       ,     revision=a       ,     cache_dir=a       ,     force_download=a       ,     )
													SCREAMING_SNAKE_CASE           =					Path(a			).parent
													SCREAMING_SNAKE_CASE           =					Path(a			).name
													SCREAMING_SNAKE_CASE           =					OnnxRuntimeModel.load_model(a       ,     provider=a       ,     sess_options=a			)
										return cls(model=a       ,     **a			)







							@classmethod
							def    _UpperCAmelCase     (					cls       :	List[Any]       ,     a       :	Union[str, Path]       ,     a       :	bool = True       ,     a       :	Optional[str] = None       ,     a       :	Optional[str] = None       ,     **a       :	Union[str, Any]       ,     )			->					Any:
										SCREAMING_SNAKE_CASE           =					None
										if len(str(a			).split("""@"""			)			) == 2:
													SCREAMING_SNAKE_CASE     ,  SCREAMING_SNAKE_CASE           =					model_id.split("""@"""			)

										return cls._from_pretrained(
										    model_id=a       ,     revision=a       ,     cache_dir=a       ,     force_download=a       ,     use_auth_token=a       ,     **a       ,     )






