


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


lowerCamelCase_       :       str      						=  logging.get_logger(__name__)

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






class 				__A    (	__snake_case      ):






 """simple docstring"""




 __lowerCAmelCase			 =  """blip_2_vision_model"""


 def __init__(		self			,   __A=1408			,   __A=6144			,   __A=39			,   __A=16			,   __A=224			,   __A=14			,   __A="gelu"			,   __A=0.00_001			,   __A=0.0			,   __A=1E-1_0			,   __A=True			,   **__A			,   ) ->					int:
     super().__init__(**UpperCamelCase__						)

     a					=hidden_size
     a					=intermediate_size
     a					=num_hidden_layers
     a					=num_attention_heads
     a					=patch_size
     a					=image_size
     a					=initializer_range
     a					=attention_dropout
     a					=layer_norm_eps
     a					=hidden_act
     a					=qkv_bias





 @classmethod
 def 				SCREAMING_SNAKE_CASE							(		cls			,   __A			,   **__A						) ->					"PretrainedConfig":
     cls._set_token_in_kwargs(UpperCamelCase__						)

     a					=cls.get_config_dict(UpperCamelCase__			,   **UpperCamelCase__						)

     # get the vision config dict if we are loading from Blip2Config
     if config_dict.get('''model_type'''						) == "blip-2":
         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(UpperCamelCase__			,   **UpperCamelCase__						)






class 				__A    (	__snake_case      ):






 """simple docstring"""




 __lowerCAmelCase			 =  """blip_2_qformer"""


 def __init__(		self			,   __A=3_0522			,   __A=768			,   __A=12			,   __A=12			,   __A=3072			,   __A="gelu"			,   __A=0.1			,   __A=0.1			,   __A=512			,   __A=0.02			,   __A=1E-1_2			,   __A=0			,   __A="absolute"			,   __A=2			,   __A=1408			,   **__A			,   ) ->					str:
     super().__init__(pad_token_id=UpperCamelCase__			,   **UpperCamelCase__						)

     a					=vocab_size
     a					=hidden_size
     a					=num_hidden_layers
     a					=num_attention_heads
     a					=hidden_act
     a					=intermediate_size
     a					=hidden_dropout_prob
     a					=attention_probs_dropout_prob
     a					=max_position_embeddings
     a					=initializer_range
     a					=layer_norm_eps
     a					=position_embedding_type
     a					=cross_attention_frequency
     a					=encoder_hidden_size





 @classmethod
 def 				SCREAMING_SNAKE_CASE							(		cls			,   __A			,   **__A						) ->					"PretrainedConfig":
     cls._set_token_in_kwargs(UpperCamelCase__						)

     a					=cls.get_config_dict(UpperCamelCase__			,   **UpperCamelCase__						)

     # get the qformer config dict if we are loading from Blip2Config
     if config_dict.get('''model_type'''						) == "blip-2":
         a					=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(UpperCamelCase__			,   **UpperCamelCase__						)






class 				__A    (	__snake_case      ):






 """simple docstring"""




 __lowerCAmelCase			 =  """blip-2"""
 __lowerCAmelCase			 =  True


 def __init__(		self			,   __A=None			,   __A=None			,   __A=None			,   __A=32			,   **__A						) ->					List[Any]:
     super().__init__(**UpperCamelCase__						)

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

     if qformer_config is None:
         a					={}
         logger.info('''qformer_config is None. Initializing the Blip2QFormerConfig with default values.'''						)

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

     a					=BlipaVisionConfig(**UpperCamelCase__						)
     a					=BlipaQFormerConfig(**UpperCamelCase__						)
     a					=text_config["model_type"] if "model_type" in text_config else "opt"
     a					=CONFIG_MAPPING[text_model_type](**UpperCamelCase__						)

     a					=self.text_config.tie_word_embeddings
     a					=self.text_config.is_encoder_decoder

     a					=num_query_tokens
     a					=self.vision_config.hidden_size
     a					=self.text_config.model_type in MODEL_FOR_CAUSAL_LM_MAPPING_NAMES
     a					=1.0
     a					=0.02


 @classmethod
 def 				SCREAMING_SNAKE_CASE							(		cls			,   __A			,   __A			,   __A			,   **__A			,   ) ->					Tuple:
     return cls(
         vision_config=vision_config.to_dict()			,   qformer_config=qformer_config.to_dict()			,   text_config=text_config.to_dict()			,   **UpperCamelCase__			,   )





 def 				SCREAMING_SNAKE_CASE							(		self						) ->					List[str]:
     a					=copy.deepcopy(self.__dict__						)
     a					=self.vision_config.to_dict()
     a					=self.qformer_config.to_dict()
     a					=self.text_config.to_dict()
     a					=self.__class__.model_type
     return output



"""simple docstring"""







import os
import sys
import unittest


lowerCamelCase_       :       Tuple      						=  os.path.abspath(os.path.dirname(os.path.dirname(os.path.dirname(__file__))))
sys.path.append(os.path.join(git_repo_path, """utils"""))

import get_test_info  # noqa: E402
from get_test_info import (  # noqa: E402
    get_model_to_test_mapping,
    get_model_to_tester_mapping,
    get_test_to_tester_mapping,
)


lowerCamelCase_       :       Dict      						=  os.path.join("""tests""", """models""", """bert""", """test_modeling_bert.py""")
lowerCamelCase_       :       Dict      						=  os.path.join("""tests""", """models""", """blip""", """test_modeling_blip.py""")






class 				__A    (	unittest.TestCase      ):






 """simple docstring"""




 def 				SCREAMING_SNAKE_CASE							(		self						) ->					Any:
     a					=get_test_to_tester_mapping(__A						)
     a					=get_test_to_tester_mapping(__A						)

     a					={'''BertModelTest''': '''BertModelTester'''}

     a					={
         '''BlipModelTest''': '''BlipModelTester''',
         '''BlipTextImageModelTest''': '''BlipTextImageModelsModelTester''',
         '''BlipTextModelTest''': '''BlipTextModelTester''',
         '''BlipTextRetrievalModelTest''': '''BlipTextRetrievalModelTester''',
         '''BlipVQAModelTest''': '''BlipVQAModelTester''',
         '''BlipVisionModelTest''': '''BlipVisionModelTester''',
     }

     self.assertEqual(get_test_info.to_json(__A						)			,   __A						)
     self.assertEqual(get_test_info.to_json(__A						)			,   __A						)


 def 				SCREAMING_SNAKE_CASE							(		self						) ->					List[str]:
     a					=get_model_to_test_mapping(__A						)
     a					=get_model_to_test_mapping(__A						)

     a					={
         '''BertForMaskedLM''': ['''BertModelTest'''],
         '''BertForMultipleChoice''': ['''BertModelTest'''],
         '''BertForNextSentencePrediction''': ['''BertModelTest'''],
         '''BertForPreTraining''': ['''BertModelTest'''],
         '''BertForQuestionAnswering''': ['''BertModelTest'''],
         '''BertForSequenceClassification''': ['''BertModelTest'''],
         '''BertForTokenClassification''': ['''BertModelTest'''],
         '''BertLMHeadModel''': ['''BertModelTest'''],
         '''BertModel''': ['''BertModelTest'''],
     }

     a					={
         '''BlipForConditionalGeneration''': ['''BlipTextImageModelTest'''],
         '''BlipForImageTextRetrieval''': ['''BlipTextRetrievalModelTest'''],
         '''BlipForQuestionAnswering''': ['''BlipVQAModelTest'''],
         '''BlipModel''': ['''BlipModelTest'''],
         '''BlipTextModel''': ['''BlipTextModelTest'''],
         '''BlipVisionModel''': ['''BlipVisionModelTest'''],
     }

     self.assertEqual(get_test_info.to_json(__A						)			,   __A						)
     self.assertEqual(get_test_info.to_json(__A						)			,   __A						)





 def 				SCREAMING_SNAKE_CASE							(		self						) ->					List[Any]:
     a					=get_model_to_tester_mapping(__A						)
     a					=get_model_to_tester_mapping(__A						)

     a					={
         '''BertForMaskedLM''': ['''BertModelTester'''],
         '''BertForMultipleChoice''': ['''BertModelTester'''],
         '''BertForNextSentencePrediction''': ['''BertModelTester'''],
         '''BertForPreTraining''': ['''BertModelTester'''],
         '''BertForQuestionAnswering''': ['''BertModelTester'''],
         '''BertForSequenceClassification''': ['''BertModelTester'''],
         '''BertForTokenClassification''': ['''BertModelTester'''],
         '''BertLMHeadModel''': ['''BertModelTester'''],
         '''BertModel''': ['''BertModelTester'''],
     }

     a					={
         '''BlipForConditionalGeneration''': ['''BlipTextImageModelsModelTester'''],
         '''BlipForImageTextRetrieval''': ['''BlipTextRetrievalModelTester'''],
         '''BlipForQuestionAnswering''': ['''BlipVQAModelTester'''],
         '''BlipModel''': ['''BlipModelTester'''],
         '''BlipTextModel''': ['''BlipTextModelTester'''],
         '''BlipVisionModel''': ['''BlipVisionModelTester'''],
     }

     self.assertEqual(get_test_info.to_json(__A						)			,   __A						)
     self.assertEqual(get_test_info.to_json(__A						)			,   __A						)