



import copy
import os
from collections import OrderedDict
from typing import TYPE_CHECKING, Any, Dict, Mapping, Optional, Union


if TYPE_CHECKING:
				from ...processing_utils import ProcessorMixin
				from ...utils import TensorType

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


lowerCAmelCase__					  =  logging.get_logger(__name__)

lowerCAmelCase__					  =  {
    '''google/owlvit-base-patch32''': '''https://huggingface.co/google/owlvit-base-patch32/resolve/main/config.json''',
    '''google/owlvit-base-patch16''': '''https://huggingface.co/google/owlvit-base-patch16/resolve/main/config.json''',
    '''google/owlvit-large-patch14''': '''https://huggingface.co/google/owlvit-large-patch14/resolve/main/config.json''',
}

class 				snake_case__(_UpperCamelCase      ):

					"""simple docstring"""






					lowercase_								=		"""owlvit_text_model"""







					def __init__(							self :     Union[str, Any]				,       SCREAMING_SNAKE_CASE :     int=49_408				,       SCREAMING_SNAKE_CASE :     List[Any]=512				,       SCREAMING_SNAKE_CASE :     Tuple=2_048				,       SCREAMING_SNAKE_CASE :     Tuple=12				,       SCREAMING_SNAKE_CASE :     Optional[int]=8				,       SCREAMING_SNAKE_CASE :     List[str]=16				,       SCREAMING_SNAKE_CASE :     List[str]="quick_gelu"				,       SCREAMING_SNAKE_CASE :     Any=1E-5				,       SCREAMING_SNAKE_CASE :     Any=0.0				,       SCREAMING_SNAKE_CASE :     List[Any]=0.02				,       SCREAMING_SNAKE_CASE :     Optional[Any]=1.0				,       SCREAMING_SNAKE_CASE :     str=0				,       SCREAMING_SNAKE_CASE :     List[str]=49_406				,       SCREAMING_SNAKE_CASE :     str=49_407				,       **SCREAMING_SNAKE_CASE :     str				,       ):
									super().__init__(pad_token_id=SCREAMING_SNAKE_CASE				,       bos_token_id=SCREAMING_SNAKE_CASE				,       eos_token_id=SCREAMING_SNAKE_CASE				,       **SCREAMING_SNAKE_CASE					)

									lowercase__					:   Any													=					vocab_size
									lowercase__					:   Tuple													=					hidden_size
									lowercase__					:   List[Any]													=					intermediate_size
									lowercase__					:   List[Any]													=					num_hidden_layers
									lowercase__					:   Union[str, Any]													=					num_attention_heads
									lowercase__					:   List[str]													=					max_position_embeddings
									lowercase__					:   Tuple													=					hidden_act
									lowercase__					:   int													=					layer_norm_eps
									lowercase__					:   List[str]													=					attention_dropout
									lowercase__					:   str													=					initializer_range
									lowercase__					:   int													=					initializer_factor







					@classmethod
					def 			snake_case					(							cls :     Optional[int]				,       SCREAMING_SNAKE_CASE :     Union[str, os.PathLike]				,       **SCREAMING_SNAKE_CASE :     Dict					):
									cls._set_token_in_kwargs(SCREAMING_SNAKE_CASE					)

									lowercase__							,							lowercase__					:   List[Any]													=					cls.get_config_dict(SCREAMING_SNAKE_CASE				,       **SCREAMING_SNAKE_CASE					)

									# get the text config dict if we are loading from OwlViTConfig
									if config_dict.get("model_type"					) == "owlvit":
													lowercase__					:   Union[str, Any]													=					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(SCREAMING_SNAKE_CASE				,       **SCREAMING_SNAKE_CASE					)






class 				snake_case__(_UpperCamelCase      ):

					"""simple docstring"""






					lowercase_								=		"""owlvit_vision_model"""







					def __init__(							self :     List[Any]				,       SCREAMING_SNAKE_CASE :     str=768				,       SCREAMING_SNAKE_CASE :     Any=3_072				,       SCREAMING_SNAKE_CASE :     Optional[int]=12				,       SCREAMING_SNAKE_CASE :     List[Any]=12				,       SCREAMING_SNAKE_CASE :     List[str]=3				,       SCREAMING_SNAKE_CASE :     Union[str, Any]=768				,       SCREAMING_SNAKE_CASE :     Any=32				,       SCREAMING_SNAKE_CASE :     Optional[Any]="quick_gelu"				,       SCREAMING_SNAKE_CASE :     Tuple=1E-5				,       SCREAMING_SNAKE_CASE :     Any=0.0				,       SCREAMING_SNAKE_CASE :     Optional[int]=0.02				,       SCREAMING_SNAKE_CASE :     int=1.0				,       **SCREAMING_SNAKE_CASE :     Optional[int]				,       ):
									super().__init__(**SCREAMING_SNAKE_CASE					)

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







					@classmethod
					def 			snake_case					(							cls :     str				,       SCREAMING_SNAKE_CASE :     Union[str, os.PathLike]				,       **SCREAMING_SNAKE_CASE :     Optional[int]					):
									cls._set_token_in_kwargs(SCREAMING_SNAKE_CASE					)

									lowercase__							,							lowercase__					:   int													=					cls.get_config_dict(SCREAMING_SNAKE_CASE				,       **SCREAMING_SNAKE_CASE					)

									# get the vision config dict if we are loading from OwlViTConfig
									if config_dict.get("model_type"					) == "owlvit":
													lowercase__					:   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(SCREAMING_SNAKE_CASE				,       **SCREAMING_SNAKE_CASE					)






class 				snake_case__(_UpperCamelCase      ):

					"""simple docstring"""






					lowercase_								=		"""owlvit"""
					lowercase_								=		True







					def __init__(							self :     Any				,       SCREAMING_SNAKE_CASE :     int=None				,       SCREAMING_SNAKE_CASE :     List[str]=None				,       SCREAMING_SNAKE_CASE :     Dict=512				,       SCREAMING_SNAKE_CASE :     int=2.6_592				,       SCREAMING_SNAKE_CASE :     Any=True				,       **SCREAMING_SNAKE_CASE :     List[Any]				,       ):
									super().__init__(**SCREAMING_SNAKE_CASE					)

									if text_config is None:
													lowercase__					:   Dict													=					{}
													logger.info("text_config is None. Initializing the OwlViTTextConfig with default values."					)

									if vision_config is None:
													lowercase__					:   Optional[int]													=					{}
													logger.info("vision_config is None. initializing the OwlViTVisionConfig with default values."					)

									lowercase__					:   Any													=					OwlViTTextConfig(**SCREAMING_SNAKE_CASE					)
									lowercase__					:   str													=					OwlViTVisionConfig(**SCREAMING_SNAKE_CASE					)

									lowercase__					:   Dict													=					projection_dim
									lowercase__					:   Union[str, Any]													=					logit_scale_init_value
									lowercase__					:   Union[str, Any]													=					return_dict
									lowercase__					:   List[str]													=					1.0







					@classmethod
					def 			snake_case					(							cls :     Any				,       SCREAMING_SNAKE_CASE :     Union[str, os.PathLike]				,       **SCREAMING_SNAKE_CASE :     Union[str, Any]					):
									cls._set_token_in_kwargs(SCREAMING_SNAKE_CASE					)

									lowercase__							,							lowercase__					:   int													=					cls.get_config_dict(SCREAMING_SNAKE_CASE				,       **SCREAMING_SNAKE_CASE					)

									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(SCREAMING_SNAKE_CASE				,       **SCREAMING_SNAKE_CASE					)







					@classmethod
					def 			snake_case					(							cls :     int				,       SCREAMING_SNAKE_CASE :     Dict				,       SCREAMING_SNAKE_CASE :     Dict				,       **SCREAMING_SNAKE_CASE :     Tuple					):
									lowercase__					:   str													=					{}
									lowercase__					:   List[Any]													=					text_config
									lowercase__					:   Any													=					vision_config

									return cls.from_dict(SCREAMING_SNAKE_CASE				,       **SCREAMING_SNAKE_CASE					)







					def 			snake_case					(							self :     Dict					):
									lowercase__					:   Union[str, Any]													=					copy.deepcopy(self.__dict__					)
									lowercase__					:   Optional[int]													=					self.text_config.to_dict()
									lowercase__					:   Dict													=					self.vision_config.to_dict()
									lowercase__					:   Dict													=					self.__class__.model_type
									return output






class 				snake_case__(_UpperCamelCase      ):

					"""simple docstring"""






					@property
					def 			snake_case					(							self :     Dict					):
									return OrderedDict(
									    [
									        ("input_ids", {0: "batch", 1: "sequence"}),
									        ("pixel_values", {0: "batch", 1: "num_channels", 2: "height", 3: "width"}),
									        ("attention_mask", {0: "batch", 1: "sequence"}),
									    ]					)







					@property
					def 			snake_case					(							self :     Dict					):
									return OrderedDict(
									    [
									        ("logits_per_image", {0: "batch"}),
									        ("logits_per_text", {0: "batch"}),
									        ("text_embeds", {0: "batch"}),
									        ("image_embeds", {0: "batch"}),
									    ]					)







					@property
					def 			snake_case					(							self :     List[str]					):
									return 1E-4







					def 			snake_case					(							self :     str				,       SCREAMING_SNAKE_CASE :     "ProcessorMixin"				,       SCREAMING_SNAKE_CASE :     int = -1				,       SCREAMING_SNAKE_CASE :     int = -1				,       SCREAMING_SNAKE_CASE :     Optional["TensorType"] = None				,       ):
									lowercase__					:   List[Any]													=					super().generate_dummy_inputs(
									    processor.tokenizer				,       batch_size=SCREAMING_SNAKE_CASE				,       seq_length=SCREAMING_SNAKE_CASE				,       framework=SCREAMING_SNAKE_CASE					)
									lowercase__					:   Union[str, Any]													=					super().generate_dummy_inputs(
									    processor.image_processor				,       batch_size=SCREAMING_SNAKE_CASE				,       framework=SCREAMING_SNAKE_CASE					)
									return {**text_input_dict, **image_input_dict}







					@property
					def 			snake_case					(							self :     Any					):
									return 14









from typing import Union

import fire
import torch
from tqdm import tqdm


def  __lowerCamelCase (       lowerCamelCase__					,			lowerCamelCase__ = "cpu"					,			lowerCamelCase__ = None						):

				"""simple docstring"""


				lowercase__					:   Any													=					torch.load(lowerCamelCase__					,			map_location=lowerCamelCase__						)
				for k, v in tqdm(state_dict.items()						):
								if not isinstance(lowerCamelCase__					,			torch.Tensor						):
												raise TypeError("FP16 conversion only works on paths that are saved state dicts, like pytorch_model.bin"						)
								lowercase__					:   int													=					v.half()
				if save_path is None:  # overwrite src_path
								lowercase__					:   Optional[Any]													=					src_path
				torch.save(lowerCamelCase__					,			lowerCamelCase__						)


if __name__ == "__main__":
				fire.Fire(convert)




