

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


lowercase_       		=  logging.get_logger(__name__)

lowercase_       		=  {
    """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  A						(							UpperCAmelCase__ ):







    """simple docstring"""





    lowerCamelCase			=							'owlvit_text_model'


    def __init__(      self :       str,lowercase_ :       int=4_9_4_0_8,lowercase_ :       List[Any]=5_1_2,lowercase_ :       Union[str, Any]=2_0_4_8,lowercase_ :       str=1_2,lowercase_ :       int=8,lowercase_ :       str=1_6,lowercase_ :       Any="quick_gelu",lowercase_ :       List[Any]=1E-5,lowercase_ :       Tuple=0.0,lowercase_ :       Dict=0.02,lowercase_ :       Any=1.0,lowercase_ :       Optional[Any]=0,lowercase_ :       Any=4_9_4_0_6,lowercase_ :       str=4_9_4_0_7,**lowercase_ :       Dict,)->    List[Any]:





        '''simple docstring'''







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

        A__          =   vocab_size
        A__          =   hidden_size
        A__          =   intermediate_size
        A__          =   num_hidden_layers
        A__          =   num_attention_heads
        A__          =   max_position_embeddings
        A__          =   hidden_act
        A__          =   layer_norm_eps
        A__          =   attention_dropout
        A__          =   initializer_range
        A__          =   initializer_factor


    @classmethod
    def 						snake_case__     (      cls :       Tuple,lowercase_ :       List[Any],**lowercase_ :       Optional[Any]		)->    List[str]:





        '''simple docstring'''







        cls._set_token_in_kwargs(_a		)

        A__      ,						A__          =   cls.get_config_dict(_a,**_a		)

        # get the text config dict if we are loading from OwlViTConfig
        if config_dict.get('model_type'		) == "owlvit":
            A__          =   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  A						(							UpperCAmelCase__ ):







    """simple docstring"""





    lowerCamelCase			=							'owlvit_vision_model'


    def __init__(      self :       Optional[int],lowercase_ :       Any=7_6_8,lowercase_ :       Tuple=3_0_7_2,lowercase_ :       List[str]=1_2,lowercase_ :       Optional[int]=1_2,lowercase_ :       Optional[Any]=3,lowercase_ :       List[str]=7_6_8,lowercase_ :       List[Any]=3_2,lowercase_ :       Dict="quick_gelu",lowercase_ :       Optional[int]=1E-5,lowercase_ :       List[str]=0.0,lowercase_ :       Dict=0.02,lowercase_ :       Optional[Any]=1.0,**lowercase_ :       Any,)->    Dict:





        '''simple docstring'''







        super().__init__(**_a		)

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


    @classmethod
    def 						snake_case__     (      cls :       str,lowercase_ :       str,**lowercase_ :       int		)->    List[str]:





        '''simple docstring'''







        cls._set_token_in_kwargs(_a		)

        A__      ,						A__          =   cls.get_config_dict(_a,**_a		)

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




class  A						(							UpperCAmelCase__ ):







    """simple docstring"""





    lowerCamelCase			=							'owlvit'
    lowerCamelCase			=							True


    def __init__(      self :       int,lowercase_ :       List[Any]=None,lowercase_ :       Optional[int]=None,lowercase_ :       Dict=5_1_2,lowercase_ :       Any=2.6_592,lowercase_ :       Optional[Any]=True,**lowercase_ :       Dict,)->    Dict:





        '''simple docstring'''







        super().__init__(**_a		)

        if text_config is None:
            A__          =   {}
            logger.info('text_config is None. Initializing the OwlViTTextConfig with default values.'		)

        if vision_config is None:
            A__          =   {}
            logger.info('vision_config is None. initializing the OwlViTVisionConfig with default values.'		)

        A__          =   OwlViTTextConfig(**_a		)
        A__          =   OwlViTVisionConfig(**_a		)

        A__          =   projection_dim
        A__          =   logit_scale_init_value
        A__          =   return_dict
        A__          =   1.0


    @classmethod
    def 						snake_case__     (      cls :       Union[str, Any],lowercase_ :       Any,**lowercase_ :       Tuple		)->    Dict:





        '''simple docstring'''







        cls._set_token_in_kwargs(_a		)

        A__      ,						A__          =   cls.get_config_dict(_a,**_a		)

        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		)


    @classmethod
    def 						snake_case__     (      cls :       Optional[Any],lowercase_ :       List[str],lowercase_ :       Optional[int],**lowercase_ :       Union[str, Any]		)->    List[Any]:





        '''simple docstring'''







        A__          =   {}
        A__          =   text_config
        A__          =   vision_config

        return cls.from_dict(_a,**_a		)


    def 						snake_case__     (      self :       Optional[int]		)->    Optional[int]:





        '''simple docstring'''







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




class  A						(							UpperCAmelCase__ ):







    """simple docstring"""





    @property
    def 						snake_case__     (      self :       Union[str, Any]		)->    List[Any]:





        '''simple docstring'''







        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 :       Optional[int]		)->    Dict:





        '''simple docstring'''







        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 :       Union[str, Any]		)->    Any:





        '''simple docstring'''







        return 1E-4


    def 						snake_case__     (      self :       str,lowercase_ :       List[Any],lowercase_ :       Tuple = -1,lowercase_ :       List[Any] = -1,lowercase_ :       List[str] = None,)->    Any:





        '''simple docstring'''







        A__          =   super().generate_dummy_inputs(
            processor.tokenizer,batch_size=_a,seq_length=_a,framework=_a		)
        A__          =   super().generate_dummy_inputs(
            processor.image_processor,batch_size=_a,framework=_a		)
        return {**text_input_dict, **image_input_dict}


    @property
    def 						snake_case__     (      self :       Union[str, Any]		)->    List[Any]:





        '''simple docstring'''







        return 1_4







"""simple docstring"""




from math import ceil



def     a__ (				snake_case__       , snake_case__				)						->					Optional[int]:
			lowerCamelCase			      =					list(range(0       , snake_case__				)				)

			lowerCamelCase			      =					[item for sublist in list(device_map.values()				) for item in sublist]

			# Duplicate check
			lowerCamelCase			      =					[]
			for i in device_map_blocks:
						if device_map_blocks.count(snake_case__				) > 1 and i not in duplicate_blocks:
									duplicate_blocks.append(snake_case__				)
    # Missing blocks
			lowerCamelCase			      =					[i for i in blocks if i not in device_map_blocks]
			lowerCamelCase			      =					[i for i in device_map_blocks if i not in blocks]

			if len(snake_case__				) != 0:
						raise ValueError(
						    """Duplicate attention blocks specified in device_map. Attention blocks must be specified to one device."""
						    """ These attention blocks were specified more than once: """ + str(snake_case__				)				)
			if len(snake_case__				) != 0:
						raise ValueError(
						    """There are attention blocks for this model that are not specified in the device_map. Add these attention """
						    """blocks to a device on the device_map: """ + str(snake_case__				)				)
			if len(snake_case__				) != 0:
						raise ValueError(
						    """The device_map contains more attention blocks than this model has. Remove these from the device_map:"""
						    + str(snake_case__				)				)



def     a__ (				snake_case__       , snake_case__				)						->					List[Any]:
			lowerCamelCase			      =					list(range(snake_case__				)				)
			lowerCamelCase			      =					int(ceil(n_layers / len(snake_case__				)				)				)
			lowerCamelCase			      =					[layers[i : i + n_blocks] for i in range(0       , snake_case__       , snake_case__				)]

			return dict(zip(snake_case__       , snake_case__				)				)



