





import copy
import os
from typing import Union

from ...configuration_utils import PretrainedConfig
from ...models.auto.modeling_auto import MODEL_FOR_CAUSAL_LM_MAPPING_NAMES
from ...utils import logging
from ..auto import CONFIG_MAPPING


UpperCAmelCase_					:   Union[str, Any] 							=						logging.get_logger(__name__)

UpperCAmelCase_					:   Union[str, Any] 							=						{
    """salesforce/blip2-opt-2.7b""": """https://huggingface.co/salesforce/blip2-opt-2.7b/resolve/main/config.json""",
}





class 							lowercase__    (							_A  ):
  __UpperCamelCase	     =  """blip_2_vision_model"""







  def __init__(	self    ,						_lowercase=1_408    ,						_lowercase=6_144    ,						_lowercase=39    ,						_lowercase=16    ,						_lowercase=224    ,						_lowercase=14    ,						_lowercase="gelu"    ,						_lowercase=0.0_0001    ,						_lowercase=0.0    ,						_lowercase=1e-10    ,						_lowercase=True    ,						**_lowercase    ,						):
       super().__init__(**__lowerCamelCase						)

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







  @classmethod
  def 	UpperCAmelCase__		(	cls    ,						_lowercase    ,						**_lowercase						):
       cls._set_token_in_kwargs(__lowerCamelCase						)

       lowerCAmelCase_					:       int    =		cls.get_config_dict(__lowerCamelCase    ,						**__lowerCamelCase						)

       # get the vision config dict if we are loading from Blip2Config
       if config_dict.get("""model_type"""						) == "blip-2":
            lowerCAmelCase_					:       Tuple    =		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 							lowercase__    (							_A  ):
  __UpperCamelCase	     =  """blip_2_qformer"""







  def __init__(	self    ,						_lowercase=30_522    ,						_lowercase=768    ,						_lowercase=12    ,						_lowercase=12    ,						_lowercase=3_072    ,						_lowercase="gelu"    ,						_lowercase=0.1    ,						_lowercase=0.1    ,						_lowercase=512    ,						_lowercase=0.02    ,						_lowercase=1e-12    ,						_lowercase=0    ,						_lowercase="absolute"    ,						_lowercase=2    ,						_lowercase=1_408    ,						**_lowercase    ,						):
       super().__init__(pad_token_id=__lowerCamelCase    ,						**__lowerCamelCase						)

       lowerCAmelCase_					:       List[Any]    =		vocab_size
       lowerCAmelCase_					:       Optional[int]    =		hidden_size
       lowerCAmelCase_					:       Dict    =		num_hidden_layers
       lowerCAmelCase_					:       int    =		num_attention_heads
       lowerCAmelCase_					:       Optional[Any]    =		hidden_act
       lowerCAmelCase_					:       List[str]    =		intermediate_size
       lowerCAmelCase_					:       Optional[Any]    =		hidden_dropout_prob
       lowerCAmelCase_					:       Optional[Any]    =		attention_probs_dropout_prob
       lowerCAmelCase_					:       Tuple    =		max_position_embeddings
       lowerCAmelCase_					:       Optional[int]    =		initializer_range
       lowerCAmelCase_					:       Optional[Any]    =		layer_norm_eps
       lowerCAmelCase_					:       Optional[int]    =		position_embedding_type
       lowerCAmelCase_					:       List[str]    =		cross_attention_frequency
       lowerCAmelCase_					:       Union[str, Any]    =		encoder_hidden_size







  @classmethod
  def 	UpperCAmelCase__		(	cls    ,						_lowercase    ,						**_lowercase						):
       cls._set_token_in_kwargs(__lowerCamelCase						)

       lowerCAmelCase_					:       Union[str, Any]    =		cls.get_config_dict(__lowerCamelCase    ,						**__lowerCamelCase						)

       # get the qformer config dict if we are loading from Blip2Config
       if config_dict.get("""model_type"""						) == "blip-2":
            lowerCAmelCase_					:       Optional[int]    =		config_dict["qformer_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 							lowercase__    (							_A  ):
  __UpperCamelCase	     =  """blip-2"""
  __UpperCamelCase	     =  True







  def __init__(	self    ,						_lowercase=None    ,						_lowercase=None    ,						_lowercase=None    ,						_lowercase=32    ,						**_lowercase						):
       super().__init__(**__lowerCamelCase						)

       if vision_config is None:
            lowerCAmelCase_					:       List[str]    =		{}
            logger.info("""vision_config is None. initializing the Blip2VisionConfig with default values."""						)

       if qformer_config is None:
            lowerCAmelCase_					:       Dict    =		{}
            logger.info("""qformer_config is None. Initializing the Blip2QFormerConfig with default values."""						)

       if text_config is None:
            lowerCAmelCase_					:       Any    =		{}
            logger.info("""text_config is None. Initializing the text config with default values (`OPTConfig`)."""						)

       lowerCAmelCase_					:       List[Any]    =		BlipaVisionConfig(**__lowerCamelCase						)
       lowerCAmelCase_					:       List[Any]    =		BlipaQFormerConfig(**__lowerCamelCase						)
       lowerCAmelCase_					:       Union[str, Any]    =		text_config["model_type"] if "model_type" in text_config else "opt"
       lowerCAmelCase_					:       Tuple    =		CONFIG_MAPPING[text_model_type](**__lowerCamelCase						)

       lowerCAmelCase_					:       Tuple    =		self.text_config.tie_word_embeddings
       lowerCAmelCase_					:       Union[str, Any]    =		self.text_config.is_encoder_decoder

       lowerCAmelCase_					:       Union[str, Any]    =		num_query_tokens
       lowerCAmelCase_					:       str    =		self.vision_config.hidden_size
       lowerCAmelCase_					:       int    =		self.text_config.model_type in MODEL_FOR_CAUSAL_LM_MAPPING_NAMES
       lowerCAmelCase_					:       Any    =		1.0
       lowerCAmelCase_					:       Optional[int]    =		0.02







  @classmethod
  def 	UpperCAmelCase__		(	cls    ,						_lowercase    ,						_lowercase    ,						_lowercase    ,						**_lowercase    ,						):
       return cls(
           vision_config=vision_config.to_dict()    ,						qformer_config=qformer_config.to_dict()    ,						text_config=text_config.to_dict()    ,						**__lowerCamelCase    ,						)







  def 	UpperCAmelCase__		(	self						):
       lowerCAmelCase_					:       str    =		copy.deepcopy(self.__dict__						)
       lowerCAmelCase_					:       List[str]    =		self.vision_config.to_dict()
       lowerCAmelCase_					:       int    =		self.qformer_config.to_dict()
       lowerCAmelCase_					:       Dict    =		self.text_config.to_dict()
       lowerCAmelCase_					:       Optional[int]    =		self.__class__.model_type
       return output







from collections import namedtuple

UpperCAmelCase_					:   Union[str, Any] 							=						namedtuple("""from_to""", """from_ to""")

UpperCAmelCase_					:   int 							=						{
    """cubicmeter""": from_to(1, 1),
    """litre""": from_to(0.0_01, 10_00),
    """kilolitre""": from_to(1, 1),
    """gallon""": from_to(0.0_04_54, 2_64.1_72),
    """cubicyard""": from_to(0.7_64_55, 1.3_07_95),
    """cubicfoot""": from_to(0.0_28, 35.31_47),
    """cup""": from_to(0.0_00_23_65_88, 42_26.75),
}






def 							_lowerCAmelCase (  _a   :					float					,   _a   :					str					,   _a   :					str			)	->			float:
     if from_type not in METRIC_CONVERSION:
          raise ValueError(
              F'Invalid \'from_type\' value: {from_type!r}  Supported values are:\n'
              + """, """.join(_a			)			)
     if to_type not in METRIC_CONVERSION:
          raise ValueError(
              F'Invalid \'to_type\' value: {to_type!r}.  Supported values are:\n'
              + """, """.join(_a			)			)
     return value * METRIC_CONVERSION[from_type].from_ * METRIC_CONVERSION[to_type].to


if __name__ == "__main__":
      import doctest

      doctest.testmod()
