
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		     =    logging.get_logger(__name__)

_A		     =    {
    '''salesforce/blip2-opt-2.7b''': '''https://huggingface.co/salesforce/blip2-opt-2.7b/resolve/main/config.json''',
}

class 						lowercase_				(				lowercase__ ):
 A__  : Dict      					=			'''blip_2_vision_model'''

 def __init__(					self   ,		__UpperCamelCase=1_4_0_8   ,		__UpperCamelCase=6_1_4_4   ,		__UpperCamelCase=3_9   ,		__UpperCamelCase=1_6   ,		__UpperCamelCase=2_2_4   ,		__UpperCamelCase=1_4   ,		__UpperCamelCase="gelu"   ,		__UpperCamelCase=0.00_001   ,		__UpperCamelCase=0.0   ,		__UpperCamelCase=1e-10   ,		__UpperCamelCase=True   ,		**__UpperCamelCase   ,		):




        """simple docstring"""


        super().__init__(**_a   )

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

 @classmethod
 def lowerCamelCase_ (					cls   ,		__UpperCamelCase   ,		**__UpperCamelCase   ):




        """simple docstring"""


        cls._set_token_in_kwargs(_a   )

        UpperCamelCase_											=				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":
               UpperCamelCase_											=				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 						lowercase_				(				lowercase__ ):
 A__  : Any      					=			'''blip_2_qformer'''

 def __init__(					self   ,		__UpperCamelCase=3_0_5_2_2   ,		__UpperCamelCase=7_6_8   ,		__UpperCamelCase=1_2   ,		__UpperCamelCase=1_2   ,		__UpperCamelCase=3_0_7_2   ,		__UpperCamelCase="gelu"   ,		__UpperCamelCase=0.1   ,		__UpperCamelCase=0.1   ,		__UpperCamelCase=5_1_2   ,		__UpperCamelCase=0.02   ,		__UpperCamelCase=1e-12   ,		__UpperCamelCase=0   ,		__UpperCamelCase="absolute"   ,		__UpperCamelCase=2   ,		__UpperCamelCase=1_4_0_8   ,		**__UpperCamelCase   ,		):




        """simple docstring"""


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

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

 @classmethod
 def lowerCamelCase_ (					cls   ,		__UpperCamelCase   ,		**__UpperCamelCase   ):




        """simple docstring"""


        cls._set_token_in_kwargs(_a   )

        UpperCamelCase_											=				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":
               UpperCamelCase_											=				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 						lowercase_				(				lowercase__ ):
 A__  : Optional[Any]      					=			'''blip-2'''
 A__  : Dict      					=			True

 def __init__(					self   ,		__UpperCamelCase=None   ,		__UpperCamelCase=None   ,		__UpperCamelCase=None   ,		__UpperCamelCase=3_2   ,		**__UpperCamelCase   ):




        """simple docstring"""


        super().__init__(**_a   )

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

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

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

        UpperCamelCase_											=				BlipaVisionConfig(**_a   )
        UpperCamelCase_											=				BlipaQFormerConfig(**_a   )
        UpperCamelCase_											=				text_config['model_type'] if 'model_type' in text_config else 'opt'
        UpperCamelCase_											=				CONFIG_MAPPING[text_model_type](**_a   )

        UpperCamelCase_											=				self.text_config.tie_word_embeddings
        UpperCamelCase_											=				self.text_config.is_encoder_decoder

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

 @classmethod
 def lowerCamelCase_ (					cls   ,		__UpperCamelCase   ,		__UpperCamelCase   ,		__UpperCamelCase   ,		**__UpperCamelCase   ,		):




        """simple docstring"""


        return cls(
            vision_config=vision_config.to_dict()   ,		qformer_config=qformer_config.to_dict()   ,		text_config=text_config.to_dict()   ,		**_a   ,		)

 def lowerCamelCase_ (					self   ):




        """simple docstring"""


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





'''simple docstring'''







import doctest
import logging
import os
import unittest
from pathlib import Path
from typing import List, Union

import transformers
from transformers.testing_utils import require_tf, require_torch, slow


__lowerCAmelCase         =    logging.getLogger()







@unittest.skip('''Temporarily disable the doc tests.'''	)
@require_torch
@require_tf
@slow
class UpperCAmelCase__	( unittest.TestCase	):





  """simple docstring"""

  def   __lowercase		(		self      :     str							,_a      :     Path							,_a      :     Union[str, None] = None							,_a      :     Union[List[str], None] = None							,_a      :     Union[str, List[str], None] = None							,_a      :     bool = True							,):


     '''simple docstring'''






     _a				:	Optional[int]			=   [file for file in os.listdir(_a       ) if os.path.isfile(os.path.join(_a							,_a       )       )]

     if identifier is not None:
        _a				:	List[str]			=   [file for file in files if identifier in file]

     if n_identifier is not None:
        if isinstance(_a							,_a       ):
           for n_ in n_identifier:
              _a				:	Tuple			=   [file for file in files if n_ not in file]
        else:
           _a				:	Optional[Any]			=   [file for file in files if n_identifier not in file]

     _a				:	List[str]			=   ignore_files or []
     ignore_files.append('__init__.py'       )
     _a				:	Tuple			=   [file for file in files if file not in ignore_files]

     for file in files:
        # Open all files
        print('Testing'							,_a       )

        if only_modules:
           _a				:	Any			=   file.split('.'       )[0]
           try:
              _a				:	List[str]			=   getattr(_a							,_a       )
              _a				:	int			=   doctest.DocTestSuite(_a       )
              _a				:	Any			=   unittest.TextTestRunner().run(_a       )
              self.assertIs(len(result.failures       )							,0       )
           except AttributeError:
              logger.info(F"""{module_identifier} is not a module."""       )
        else:
           _a				:	Union[str, Any]			=   doctest.testfile(str('..' / directory / file       )							,optionflags=doctest.ELLIPSIS       )
           self.assertIs(result.failed							,0       )


  def   __lowercase		(		self      :     Any       ):


     '''simple docstring'''






     _a				:	int			=   Path('src/transformers'       )
     _a				:	List[Any]			=   'modeling'
     _a				:	Optional[Any]			=   [
         'modeling_ctrl.py',
         'modeling_tf_ctrl.py',
     ]
     self.analyze_directory(_a							,identifier=_a							,ignore_files=_a       )


  def   __lowercase		(		self      :     Optional[int]       ):


     '''simple docstring'''






     _a				:	Optional[Any]			=   Path('src/transformers'       )
     _a				:	Optional[Any]			=   'tokenization'
     self.analyze_directory(_a							,identifier=_a       )


  def   __lowercase		(		self      :     List[str]       ):


     '''simple docstring'''






     _a				:	Dict			=   Path('src/transformers'       )
     _a				:	str			=   'configuration'
     self.analyze_directory(_a							,identifier=_a       )


  def   __lowercase		(		self      :     Any       ):


     '''simple docstring'''






     _a				:	Tuple			=   Path('src/transformers'       )
     _a				:	List[Any]			=   ['configuration', 'modeling', 'tokenization']
     self.analyze_directory(_a							,n_identifier=_a       )


  def   __lowercase		(		self      :     Tuple       ):


     '''simple docstring'''






     _a				:	List[Any]			=   Path('docs/source'       )
     _a				:	List[str]			=   ['favicon.ico']
     self.analyze_directory(_a							,ignore_files=_a							,only_modules=_a       )



