

'''simple docstring'''






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

lowerCAmelCase__											=	{
    '''Salesforce/instruct-blip-flan-t5''': '''https://huggingface.co/Salesforce/instruct-blip-flan-t5/resolve/main/config.json''',
}






class 			lowercase_	(A_      ):




  """simple docstring"""




  SCREAMING_SNAKE_CASE    :  Tuple							=			'''instructblip_vision_model'''






  def __init__(      self   :     Tuple					,lowercase__   :     Tuple=1_4_0_8					,lowercase__   :     Any=6_1_4_4					,lowercase__   :     List[Any]=3_9					,lowercase__   :     Optional[int]=1_6					,lowercase__   :     str=2_2_4					,lowercase__   :     List[str]=1_4					,lowercase__   :     Union[str, Any]="gelu"					,lowercase__   :     int=1e-6					,lowercase__   :     str=0.0					,lowercase__   :     List[Any]=1e-1_0					,lowercase__   :     Tuple=True					,**lowercase__   :     int					,):
   super().__init__(**lowercase__			)

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






  @classmethod
  def 					SCREAMING_SNAKE_CASE      (      cls   :     Union[str, Any]					,lowercase__   :     List[str]					,**lowercase__   :     Union[str, Any]			):
   cls._set_token_in_kwargs(lowercase__			)

   __lowercase  ,	__lowercase							  = cls.get_config_dict(lowercase__					,**lowercase__			)

   # get the vision config dict if we are loading from InstructBlipConfig
   if config_dict.get('''model_type'''			) == "instructblip":
    __lowercase							  = 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(lowercase__					,**lowercase__			)






class 			lowercase_	(A_      ):




  """simple docstring"""




  SCREAMING_SNAKE_CASE    :  Union[str, Any]							=			'''instructblip_qformer'''






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

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






  @classmethod
  def 					SCREAMING_SNAKE_CASE      (      cls   :     str					,lowercase__   :     List[Any]					,**lowercase__   :     Tuple			):
   cls._set_token_in_kwargs(lowercase__			)

   __lowercase  ,	__lowercase							  = cls.get_config_dict(lowercase__					,**lowercase__			)

   # get the qformer config dict if we are loading from InstructBlipConfig
   if config_dict.get('''model_type'''			) == "instructblip":
    __lowercase							  = 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(lowercase__					,**lowercase__			)






class 			lowercase_	(A_      ):




  """simple docstring"""




  SCREAMING_SNAKE_CASE    :  str							=			'''instructblip'''
  SCREAMING_SNAKE_CASE    :  Optional[int]							=			True






  def __init__(      self   :     int					,lowercase__   :     Any=None					,lowercase__   :     List[Any]=None					,lowercase__   :     Optional[int]=None					,lowercase__   :     str=3_2					,**lowercase__   :     Optional[Any]			):
   super().__init__(**lowercase__			)

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

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

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

   __lowercase							  = InstructBlipVisionConfig(**lowercase__			)
   __lowercase							  = InstructBlipQFormerConfig(**lowercase__			)
   __lowercase							  = text_config['''model_type'''] if '''model_type''' in text_config else '''opt'''
   __lowercase							  = CONFIG_MAPPING[text_model_type](**lowercase__			)

   __lowercase							  = self.text_config.tie_word_embeddings
   __lowercase							  = self.text_config.is_encoder_decoder

   __lowercase							  = num_query_tokens
   __lowercase							  = self.vision_config.hidden_size
   __lowercase							  = self.text_config.model_type in MODEL_FOR_CAUSAL_LM_MAPPING_NAMES
   __lowercase							  = 1.0
   __lowercase							  = 0.0_2






  @classmethod
  def 					SCREAMING_SNAKE_CASE      (      cls   :     Optional[Any]					,lowercase__   :     Dict					,lowercase__   :     List[str]					,lowercase__   :     str					,**lowercase__   :     str					,):
   return cls(
       vision_config=vision_config.to_dict()					,qformer_config=qformer_config.to_dict()					,text_config=text_config.to_dict()					,**lowercase__					,)






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





import os
import unittest

from huggingface_hub.utils import are_progress_bars_disabled

import transformers.models.bart.tokenization_bart
from transformers import logging
from transformers.testing_utils import CaptureLogger, mockenv, mockenv_context
from transformers.utils.logging import disable_progress_bar, enable_progress_bar





class       A    (   unittest.TestCase ):


							def 			_A       (self					):
									__lowercase=			logging.get_logger()

									# the current default level is logging.WARNING
									__lowercase=			logging.get_verbosity()

									logging.set_verbosity_error()
									self.assertEqual(logger.getEffectiveLevel()      ,				logging.get_verbosity()					)

									logging.set_verbosity_warning()
									self.assertEqual(logger.getEffectiveLevel()      ,				logging.get_verbosity()					)

									logging.set_verbosity_info()
									self.assertEqual(logger.getEffectiveLevel()      ,				logging.get_verbosity()					)

									logging.set_verbosity_debug()
									self.assertEqual(logger.getEffectiveLevel()      ,				logging.get_verbosity()					)

									# restore to the original level
									logging.set_verbosity(lowerCAmelCase					)


							def 			_A       (self					):
									__lowercase=			logging.get_verbosity()

									__lowercase=			logging.get_logger('transformers.models.bart.tokenization_bart'					)
									__lowercase=			'Testing 1, 2, 3'

									# should be able to log warnings (if default settings weren't overridden by `pytest --log-level-all`)
									if level_origin <= logging.WARNING:
											with CaptureLogger(lowerCAmelCase					) as cl:
													logger.warning(lowerCAmelCase					)
											self.assertEqual(cl.out      ,				msg + '\n'					)

									# this is setting the level for all of `transformers.*` loggers
									logging.set_verbosity_error()

									# should not be able to log warnings
									with CaptureLogger(lowerCAmelCase					) as cl:
											logger.warning(lowerCAmelCase					)
									self.assertEqual(cl.out      ,				''					)

									# should be able to log warnings again
									logging.set_verbosity_warning()
									with CaptureLogger(lowerCAmelCase					) as cl:
											logger.warning(lowerCAmelCase					)
									self.assertEqual(cl.out      ,				msg + '\n'					)

									# restore to the original level
									logging.set_verbosity(lowerCAmelCase					)


							@mockenv(TRANSFORMERS_VERBOSITY='error'					)
							def 			_A       (self					):
									# reset for the env var to take effect, next time some logger call is made
									transformers.utils.logging._reset_library_root_logger()
									# this action activates the env var
									__lowercase=			logging.get_logger('transformers.models.bart.tokenization_bart'					)

									__lowercase=			os.getenv('TRANSFORMERS_VERBOSITY'      ,				lowerCAmelCase					)
									__lowercase=			logging.log_levels[env_level_str]

									__lowercase=			logging.get_verbosity()
									self.assertEqual(
									    lowerCAmelCase      ,				lowerCAmelCase      ,				f'TRANSFORMERS_VERBOSITY={env_level_str}/{env_level}, but internal verbosity is {current_level}'      ,				)

									# restore to the original level
									__lowercase=			''
									transformers.utils.logging._reset_library_root_logger()


							@mockenv(TRANSFORMERS_VERBOSITY='super-error'					)
							def 			_A       (self					):
									# reset for the env var to take effect, next time some logger call is made
									transformers.utils.logging._reset_library_root_logger()
									__lowercase=			logging.logging.getLogger()
									with CaptureLogger(lowerCAmelCase					) as cl:
											# this action activates the env var
											logging.get_logger('transformers.models.bart.tokenization_bart'					)
									self.assertIn('Unknown option TRANSFORMERS_VERBOSITY=super-error'      ,				cl.out					)

									# no need to restore as nothing was changed







							def 			_A       (self					):
									# testing `logger.warning_advice()`
									transformers.utils.logging._reset_library_root_logger()

									__lowercase=			logging.get_logger('transformers.models.bart.tokenization_bart'					)
									__lowercase=			'Testing 1, 2, 3'

									with mockenv_context(TRANSFORMERS_NO_ADVISORY_WARNINGS='1'					):
											# nothing should be logged as env var disables this method
											with CaptureLogger(lowerCAmelCase					) as cl:
													logger.warning_advice(lowerCAmelCase					)
											self.assertEqual(cl.out      ,				''					)

									with mockenv_context(TRANSFORMERS_NO_ADVISORY_WARNINGS=''					):
											# should log normally as TRANSFORMERS_NO_ADVISORY_WARNINGS is unset
											with CaptureLogger(lowerCAmelCase					) as cl:
													logger.warning_advice(lowerCAmelCase					)
											self.assertEqual(cl.out      ,				msg + '\n'					)







def        _lowerCamelCase(	)						->	Optional[int]:

		'''simple docstring'''







		disable_progress_bar()
		assert are_progress_bars_disabled()

		enable_progress_bar()
		assert not are_progress_bars_disabled()






