



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


A__  :  Tuple								=					logging.get_logger(__name__)

A__  :  List[str]								=					{
    '''salesforce/blip2-opt-2.7b''': '''https://huggingface.co/salesforce/blip2-opt-2.7b/resolve/main/config.json''',
}



class 				__snake_case						(     UpperCamelCase_						):
							_a			      = '''blip_2_vision_model'''




							def __init__(       self     :       Tuple				,				A_     :       Optional[int]=1_4_0_8				,				A_     :       Tuple=6_1_4_4				,				A_     :       Tuple=3_9				,				A_     :       Dict=1_6				,				A_     :       Tuple=2_2_4				,				A_     :       Any=1_4				,				A_     :       Dict="gelu"				,				A_     :       Any=0.0_0001				,				A_     :       int=0.0				,				A_     :       Dict=1e-10				,				A_     :       Optional[Any]=True				,				**A_     :       Tuple				,				):
									super().__init__(**A_)

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







							@classmethod
							def    UpperCAmelCase__			(       cls     :       str				,				A_     :       Union[str, os.PathLike]				,				**A_     :       List[str]):
									cls._set_token_in_kwargs(A_)

									lowerCAmelCase_					,  lowerCAmelCase_			:     Optional[Any]									= cls.get_config_dict(A_				,				**A_)

									# get the vision config dict if we are loading from Blip2Config
									if config_dict.get('''model_type''') == "blip-2":
											lowerCAmelCase_			:     Optional[Any]									= 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 				__snake_case						(     UpperCamelCase_						):
							_a			      = '''blip_2_qformer'''




							def __init__(       self     :       List[str]				,				A_     :       List[str]=3_0_5_2_2				,				A_     :       Union[str, Any]=7_6_8				,				A_     :       Optional[int]=1_2				,				A_     :       Optional[Any]=1_2				,				A_     :       str=3_0_7_2				,				A_     :       Tuple="gelu"				,				A_     :       Union[str, Any]=0.1				,				A_     :       Optional[Any]=0.1				,				A_     :       Any=5_1_2				,				A_     :       Optional[Any]=0.02				,				A_     :       List[Any]=1e-12				,				A_     :       Optional[int]=0				,				A_     :       Dict="absolute"				,				A_     :       List[Any]=2				,				A_     :       Union[str, Any]=1_4_0_8				,				**A_     :       Optional[int]				,				):
									super().__init__(pad_token_id=A_				,				**A_)

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







							@classmethod
							def    UpperCAmelCase__			(       cls     :       Dict				,				A_     :       Union[str, os.PathLike]				,				**A_     :       Tuple):
									cls._set_token_in_kwargs(A_)

									lowerCAmelCase_					,  lowerCAmelCase_			:     str									= cls.get_config_dict(A_				,				**A_)

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





class 				__snake_case						(     UpperCamelCase_						):
							_a			      = '''blip-2'''
							_a			      = True




							def __init__(       self     :       str				,				A_     :       str=None				,				A_     :       Dict=None				,				A_     :       List[str]=None				,				A_     :       str=3_2				,				**A_     :       Any):
									super().__init__(**A_)

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

									if qformer_config is None:
											lowerCAmelCase_			:     List[str]									= {}
											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_			:     Union[str, Any]									= BlipaVisionConfig(**A_)
									lowerCAmelCase_			:     int									= BlipaQFormerConfig(**A_)
									lowerCAmelCase_			:     Any									= text_config['''model_type'''] if '''model_type''' in text_config else '''opt'''
									lowerCAmelCase_			:     Dict									= CONFIG_MAPPING[text_model_type](**A_)

									lowerCAmelCase_			:     List[str]									= self.text_config.tie_word_embeddings
									lowerCAmelCase_			:     Optional[Any]									= self.text_config.is_encoder_decoder

									lowerCAmelCase_			:     Tuple									= num_query_tokens
									lowerCAmelCase_			:     Tuple									= self.vision_config.hidden_size
									lowerCAmelCase_			:     str									= self.text_config.model_type in MODEL_FOR_CAUSAL_LM_MAPPING_NAMES
									lowerCAmelCase_			:     List[Any]									= 1.0
									lowerCAmelCase_			:     List[Any]									= 0.02




							@classmethod
							def    UpperCAmelCase__			(       cls     :       Dict				,				A_     :       BlipaVisionConfig				,				A_     :       BlipaQFormerConfig				,				A_     :       PretrainedConfig				,				**A_     :       List[Any]				,				):
									return cls(
									    vision_config=vision_config.to_dict()				,				qformer_config=qformer_config.to_dict()				,				text_config=text_config.to_dict()				,				**A_				,				)







							def    UpperCAmelCase__			(       self     :       Tuple):
									lowerCAmelCase_			:     List[Any]									= copy.deepcopy(self.__dict__)
									lowerCAmelCase_			:     Union[str, Any]									= self.vision_config.to_dict()
									lowerCAmelCase_			:     List[Any]									= self.qformer_config.to_dict()
									lowerCAmelCase_			:     Any									= self.text_config.to_dict()
									lowerCAmelCase_			:     Any									= self.__class__.model_type
									return output











'''simple docstring'''

import unittest

from transformers import MPNetConfig, is_torch_available
from transformers.testing_utils import require_torch, slow, torch_device

from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
							import torch

							from transformers import (
							    MPNetForMaskedLM,
							    MPNetForMultipleChoice,
							    MPNetForQuestionAnswering,
							    MPNetForSequenceClassification,
							    MPNetForTokenClassification,
							    MPNetModel,
							)






class 						a				:


				def __init__(		self    :					List[Any]       ,				lowercase_    :					Optional[Any]       ,				lowercase_    :					Any=13       ,				lowercase_    :					Optional[Any]=7       ,				lowercase_    :					Optional[Any]=True       ,				lowercase_    :					Dict=True       ,				lowercase_    :					Tuple=False       ,				lowercase_    :					Optional[Any]=True       ,				lowercase_    :					Any=99       ,				lowercase_    :					Union[str, Any]=64       ,				lowercase_    :					str=5       ,				lowercase_    :					int=4       ,				lowercase_    :					List[Any]=64       ,				lowercase_    :					Dict="gelu"       ,				lowercase_    :					Optional[int]=0.1       ,				lowercase_    :					Optional[Any]=0.1       ,				lowercase_    :					Tuple=512       ,				lowercase_    :					List[Any]=16       ,				lowercase_    :					str=2       ,				lowercase_    :					List[str]=0.02       ,				lowercase_    :					Optional[Any]=3       ,				lowercase_    :					Optional[Any]=4       ,				lowercase_    :					List[Any]=None       ,				):
									snake_case_									=				parent
									snake_case_									=				batch_size
									snake_case_									=				seq_length
									snake_case_									=				is_training
									snake_case_									=				use_input_mask
									snake_case_									=				use_token_type_ids
									snake_case_									=				use_labels
									snake_case_									=				vocab_size
									snake_case_									=				hidden_size
									snake_case_									=				num_hidden_layers
									snake_case_									=				num_attention_heads
									snake_case_									=				intermediate_size
									snake_case_									=				hidden_act
									snake_case_									=				hidden_dropout_prob
									snake_case_									=				attention_probs_dropout_prob
									snake_case_									=				max_position_embeddings
									snake_case_									=				type_vocab_size
									snake_case_									=				type_sequence_label_size
									snake_case_									=				initializer_range
									snake_case_									=				num_labels
									snake_case_									=				num_choices
									snake_case_									=				scope


				def   A_ (		self    :					List[str]					):
									return MPNetConfig.from_pretrained('''microsoft/mpnet-base'''					)


				def   A_ (		self    :					str					):
									snake_case_									=				ids_tensor([self.batch_size, self.seq_length]       ,				self.vocab_size					)

									snake_case_									=				None
									if self.use_input_mask:
														snake_case_									=				random_attention_mask([self.batch_size, self.seq_length]					)

									snake_case_									=				None
									snake_case_									=				None
									snake_case_									=				None
									if self.use_labels:
														snake_case_									=				ids_tensor([self.batch_size]       ,				self.type_sequence_label_size					)
														snake_case_									=				ids_tensor([self.batch_size, self.seq_length]       ,				self.num_labels					)
														snake_case_									=				ids_tensor([self.batch_size]       ,				self.num_choices					)

									snake_case_									=				self.get_config()
									return config, input_ids, input_mask, sequence_labels, token_labels, choice_labels


				def   A_ (		self    :					Tuple					):
									return MPNetConfig(
									    vocab_size=self.vocab_size       ,				hidden_size=self.hidden_size       ,				num_hidden_layers=self.num_hidden_layers       ,				num_attention_heads=self.num_attention_heads       ,				intermediate_size=self.intermediate_size       ,				hidden_act=self.hidden_act       ,				hidden_dropout_prob=self.hidden_dropout_prob       ,				attention_probs_dropout_prob=self.attention_probs_dropout_prob       ,				max_position_embeddings=self.max_position_embeddings       ,				initializer_range=self.initializer_range       ,				)


				def   A_ (		self    :					Any       ,				lowercase_    :					Dict       ,				lowercase_    :					str       ,				lowercase_    :					Optional[Any]       ,				lowercase_    :					Union[str, Any]       ,				lowercase_    :					Dict       ,				lowercase_    :					Optional[int]					):
									snake_case_									=				MPNetModel(config=lowercase_					)
									model.to(lowercase_					)
									model.eval()
									snake_case_									=				model(lowercase_       ,				lowercase_					)
									snake_case_									=				model(lowercase_					)
									self.parent.assertEqual(result.last_hidden_state.shape       ,				(self.batch_size, self.seq_length, self.hidden_size)					)
									self.parent.assertEqual(result.pooler_output.shape       ,				(self.batch_size, self.hidden_size)					)


				def   A_ (		self    :					str       ,				lowercase_    :					Optional[Any]       ,				lowercase_    :					Any       ,				lowercase_    :					str       ,				lowercase_    :					Tuple       ,				lowercase_    :					Tuple       ,				lowercase_    :					Optional[int]					):
									snake_case_									=				MPNetForQuestionAnswering(config=lowercase_					)
									model.to(lowercase_					)
									model.eval()
									snake_case_									=				model(
									    lowercase_       ,				attention_mask=lowercase_       ,				start_positions=lowercase_       ,				end_positions=lowercase_       ,				)
									self.parent.assertEqual(result.start_logits.shape       ,				(self.batch_size, self.seq_length)					)
									self.parent.assertEqual(result.end_logits.shape       ,				(self.batch_size, self.seq_length)					)


				def   A_ (		self    :					Tuple       ,				lowercase_    :					Tuple       ,				lowercase_    :					List[str]       ,				lowercase_    :					str       ,				lowercase_    :					Optional[int]       ,				lowercase_    :					Optional[Any]       ,				lowercase_    :					Any					):
									snake_case_									=				self.num_labels
									snake_case_									=				MPNetForSequenceClassification(lowercase_					)
									model.to(lowercase_					)
									model.eval()
									snake_case_									=				model(lowercase_       ,				attention_mask=lowercase_       ,				labels=lowercase_					)
									self.parent.assertEqual(result.logits.shape       ,				(self.batch_size, self.num_labels)					)


				def   A_ (		self    :					Any       ,				lowercase_    :					Any       ,				lowercase_    :					str       ,				lowercase_    :					Tuple       ,				lowercase_    :					List[str]       ,				lowercase_    :					Union[str, Any]       ,				lowercase_    :					Dict					):
									snake_case_									=				self.num_choices
									snake_case_									=				MPNetForMultipleChoice(config=lowercase_					)
									model.to(lowercase_					)
									model.eval()
									snake_case_									=				input_ids.unsqueeze(1					).expand(-1       ,				self.num_choices       ,				-1					).contiguous()
									snake_case_									=				input_mask.unsqueeze(1					).expand(-1       ,				self.num_choices       ,				-1					).contiguous()
									snake_case_									=				model(
									    lowercase_       ,				attention_mask=lowercase_       ,				labels=lowercase_       ,				)
									self.parent.assertEqual(result.logits.shape       ,				(self.batch_size, self.num_choices)					)


				def   A_ (		self    :					Union[str, Any]       ,				lowercase_    :					List[Any]       ,				lowercase_    :					Optional[Any]       ,				lowercase_    :					Optional[int]       ,				lowercase_    :					str       ,				lowercase_    :					int       ,				lowercase_    :					List[str]					):
									snake_case_									=				self.num_labels
									snake_case_									=				MPNetForTokenClassification(config=lowercase_					)
									model.to(lowercase_					)
									model.eval()
									snake_case_									=				model(lowercase_       ,				attention_mask=lowercase_       ,				labels=lowercase_					)
									self.parent.assertEqual(result.logits.shape       ,				(self.batch_size, self.seq_length, self.num_labels)					)


				def   A_ (		self    :					Union[str, Any]					):
									snake_case_									=				self.prepare_config_and_inputs()
									((snake_case_)			,(snake_case_)			,(snake_case_)			,(snake_case_)			,(snake_case_)			,(snake_case_))									=				config_and_inputs
									snake_case_									=				{'''input_ids''': input_ids, '''attention_mask''': input_mask}
									return config, inputs_dict







@require_torch
class 						a				(   _lowerCamelCase   ,     _lowerCamelCase   ,     unittest.TestCase     ):
				snake_case_      =		(
				    (
				        MPNetForMaskedLM,
				        MPNetForMultipleChoice,
				        MPNetForQuestionAnswering,
				        MPNetForSequenceClassification,
				        MPNetForTokenClassification,
				        MPNetModel,
				    )
				    if is_torch_available()
				    else ()
				)
				snake_case_      =		(
				    {
				        "feature-extraction": MPNetModel,
				        "fill-mask": MPNetForMaskedLM,
				        "question-answering": MPNetForQuestionAnswering,
				        "text-classification": MPNetForSequenceClassification,
				        "token-classification": MPNetForTokenClassification,
				        "zero-shot": MPNetForSequenceClassification,
				    }
				    if is_torch_available()
				    else {}
				)
				snake_case_      =		False
				snake_case_      =		True


				def   A_ (		self    :					Tuple					):
									snake_case_									=				MPNetModelTester(self					)
									snake_case_									=				ConfigTester(self       ,				config_class=lowercase_       ,				hidden_size=37					)


				def   A_ (		self    :					Union[str, Any]					):
									self.config_tester.run_common_tests()


				def   A_ (		self    :					Tuple					):
									snake_case_									=				self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_mpnet_model(*lowercase_					)


				def   A_ (		self    :					List[Any]					):
									snake_case_									=				self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_mpnet_for_sequence_classification(*lowercase_					)


				def   A_ (		self    :					List[Any]					):
									snake_case_									=				self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_mpnet_for_multiple_choice(*lowercase_					)


				def   A_ (		self    :					Union[str, Any]					):
									snake_case_									=				self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_mpnet_for_token_classification(*lowercase_					)


				def   A_ (		self    :					Tuple					):
									snake_case_									=				self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_mpnet_for_question_answering(*lowercase_					)







@require_torch
class 						a				(   unittest.TestCase     ):


				@slow
				def   A_ (		self    :					List[Any]					):
									snake_case_									=				MPNetModel.from_pretrained('''microsoft/mpnet-base'''					)
									snake_case_									=				torch.tensor([[0, 345, 232, 328, 740, 140, 1695, 69, 6078, 1588, 2]]					)
									snake_case_									=				model(lowercase_					)[0]
									snake_case_									=				torch.Size((1, 11, 768)					)
									self.assertEqual(output.shape       ,				lowercase_					)
									snake_case_									=				torch.tensor(
									    [[[-0.0550, 0.1943, -0.0740], [-0.0562, 0.2211, -0.0579], [-0.0437, 0.3337, -0.0641]]]					)
									# compare the actual values for a slice.
									self.assertTrue(torch.allclose(output[:, :3, :3]       ,				lowercase_       ,				atol=1e-4					)					)

