
"""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


__SCREAMING_SNAKE_CASE							=     logging.get_logger(__name__)

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





class 				a__					(						A__       ):
     UpperCAmelCase__         =      '''instructblip_vision_model'''



     def __init__(							self :int      ,  _lowerCamelCase :Optional[int]=1_408      ,  _lowerCamelCase :int=6_144      ,  _lowerCamelCase :str=39      ,  _lowerCamelCase :Tuple=16      ,  _lowerCamelCase :List[Any]=224      ,  _lowerCamelCase :int=14      ,  _lowerCamelCase :int="gelu"      ,  _lowerCamelCase :Optional[Any]=1E-6      ,  _lowerCamelCase :str=0.0      ,  _lowerCamelCase :Optional[Any]=1E-1_0      ,  _lowerCamelCase :str=True      ,  **_lowerCamelCase :Optional[Any]      ,  ):







      '''simple docstring'''



      super().__init__(**_lowerCamelCase   )

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




     @classmethod
     def  lowerCamelCase_						(							cls :Optional[Any]      ,  _lowerCamelCase :Union[str, os.PathLike]      ,  **_lowerCamelCase :Any   ):







      '''simple docstring'''



      cls._set_token_in_kwargs(_lowerCamelCase   )

      UpperCamelCase_	,     UpperCamelCase_     :					List[str]   	=cls.get_config_dict(_lowerCamelCase      ,  **_lowerCamelCase   )

      # get the vision config dict if we are loading from InstructBlipConfig
      if config_dict.get('model_type'   ) == "instructblip":
       UpperCamelCase_     :					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 				a__					(						A__       ):
     UpperCAmelCase__         =      '''instructblip_qformer'''



     def __init__(							self :Dict      ,  _lowerCamelCase :List[Any]=30_522      ,  _lowerCamelCase :Optional[int]=768      ,  _lowerCamelCase :Tuple=12      ,  _lowerCamelCase :List[str]=12      ,  _lowerCamelCase :int=3_072      ,  _lowerCamelCase :Tuple="gelu"      ,  _lowerCamelCase :Dict=0.1      ,  _lowerCamelCase :List[Any]=0.1      ,  _lowerCamelCase :Optional[int]=512      ,  _lowerCamelCase :List[Any]=0.02      ,  _lowerCamelCase :int=1E-1_2      ,  _lowerCamelCase :str=0      ,  _lowerCamelCase :Dict="absolute"      ,  _lowerCamelCase :Optional[int]=2      ,  _lowerCamelCase :Union[str, Any]=1_408      ,  **_lowerCamelCase :Tuple      ,  ):







      '''simple docstring'''



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

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




     @classmethod
     def  lowerCamelCase_						(							cls :Optional[Any]      ,  _lowerCamelCase :Union[str, os.PathLike]      ,  **_lowerCamelCase :List[Any]   ):







      '''simple docstring'''



      cls._set_token_in_kwargs(_lowerCamelCase   )

      UpperCamelCase_	,     UpperCamelCase_     :					Optional[Any]   	=cls.get_config_dict(_lowerCamelCase      ,  **_lowerCamelCase   )

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





class 				a__					(						A__       ):
     UpperCAmelCase__         =      '''instructblip'''
     UpperCAmelCase__         =      True



     def __init__(							self :str      ,  _lowerCamelCase :Optional[Any]=None      ,  _lowerCamelCase :List[str]=None      ,  _lowerCamelCase :List[Any]=None      ,  _lowerCamelCase :Union[str, Any]=32      ,  **_lowerCamelCase :Tuple   ):







      '''simple docstring'''



      super().__init__(**_lowerCamelCase   )

      if vision_config is None:
       UpperCamelCase_     :					Optional[int]   	={}
       logger.info('vision_config is None. initializing the InstructBlipVisionConfig with default values.'   )

      if qformer_config is None:
       UpperCamelCase_     :					Union[str, Any]   	={}
       logger.info('qformer_config is None. Initializing the InstructBlipQFormerConfig with default values.'   )

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

      UpperCamelCase_     :					Any   	=InstructBlipVisionConfig(**_lowerCamelCase   )
      UpperCamelCase_     :					Optional[Any]   	=InstructBlipQFormerConfig(**_lowerCamelCase   )
      UpperCamelCase_     :					str   	=text_config['model_type'] if 'model_type' in text_config else 'opt'
      UpperCamelCase_     :					int   	=CONFIG_MAPPING[text_model_type](**_lowerCamelCase   )

      UpperCamelCase_     :					Tuple   	=self.text_config.tie_word_embeddings
      UpperCamelCase_     :					Any   	=self.text_config.is_encoder_decoder

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



     @classmethod
     def  lowerCamelCase_						(							cls :Optional[Any]      ,  _lowerCamelCase :InstructBlipVisionConfig      ,  _lowerCamelCase :InstructBlipQFormerConfig      ,  _lowerCamelCase :PretrainedConfig      ,  **_lowerCamelCase :Dict      ,  ):







      '''simple docstring'''



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




     def  lowerCamelCase_						(							self :Optional[Any]   ):







      '''simple docstring'''



      UpperCamelCase_     :					str   	=copy.deepcopy(self.__dict__   )
      UpperCamelCase_     :					Dict   	=self.vision_config.to_dict()
      UpperCamelCase_     :					Tuple   	=self.qformer_config.to_dict()
      UpperCamelCase_     :					List[str]   	=self.text_config.to_dict()
      UpperCamelCase_     :					List[str]   	=self.__class__.model_type
      return output


"""simple docstring"""






import copy
import tempfile
import unittest

from huggingface_hub import HfFolder, delete_repo
from parameterized import parameterized
from requests.exceptions import HTTPError

from transformers import AutoConfig, GenerationConfig
from transformers.testing_utils import TOKEN, USER, is_staging_test





class 				a__					(						unittest.TestCase       ):



     @parameterized.expand([(None,), ('foo.json',)]   )
     def  lowerCamelCase_						(							self :Union[str, Any]      ,  _lowerCamelCase :Any   ):







      '''simple docstring'''



      UpperCamelCase_     :					str   	=GenerationConfig(
          do_sample=_lowerCamelCase      ,  temperature=0.7      ,  length_penalty=1.0      ,  bad_words_ids=[[1, 2, 3], [4, 5]]      ,  )
      with tempfile.TemporaryDirectory() as tmp_dir:
       config.save_pretrained(_lowerCamelCase      ,  config_name=_lowerCamelCase   )
       UpperCamelCase_     :					Union[str, Any]   	=GenerationConfig.from_pretrained(_lowerCamelCase      ,  config_name=_lowerCamelCase   )

      # Checks parameters that were specified
      self.assertEqual(loaded_config.do_sample      ,  _lowerCamelCase   )
      self.assertEqual(loaded_config.temperature      ,  0.7   )
      self.assertEqual(loaded_config.length_penalty      ,  1.0   )
      self.assertEqual(loaded_config.bad_words_ids      ,  [[1, 2, 3], [4, 5]]   )

      # Checks parameters that were not specified (defaults)
      self.assertEqual(loaded_config.top_k      ,  50   )
      self.assertEqual(loaded_config.max_length      ,  20   )
      self.assertEqual(loaded_config.max_time      ,  _lowerCamelCase   )



     def  lowerCamelCase_						(							self :Optional[Any]   ):







      '''simple docstring'''



      UpperCamelCase_     :					Optional[int]   	=AutoConfig.from_pretrained('gpt2'   )
      UpperCamelCase_     :					Tuple   	=GenerationConfig.from_model_config(_lowerCamelCase   )
      UpperCamelCase_     :					Optional[int]   	=GenerationConfig()

      # The generation config has loaded a few non-default parameters from the model config
      self.assertNotEqual(_lowerCamelCase      ,  _lowerCamelCase   )

      # One of those parameters is eos_token_id -- check if it matches
      self.assertNotEqual(generation_config_from_model.eos_token_id      ,  default_generation_config.eos_token_id   )
      self.assertEqual(generation_config_from_model.eos_token_id      ,  model_config.eos_token_id   )



     def  lowerCamelCase_						(							self :Tuple   ):







      '''simple docstring'''



      UpperCamelCase_     :					str   	=GenerationConfig()
      UpperCamelCase_     :					Optional[Any]   	={
          'max_new_tokens': 1_024,
          'foo': 'bar',
      }
      UpperCamelCase_     :					Optional[Any]   	=copy.deepcopy(_lowerCamelCase   )
      UpperCamelCase_     :					Optional[int]   	=generation_config.update(**_lowerCamelCase   )

      # update_kwargs was not modified (no side effects)
      self.assertEqual(_lowerCamelCase      ,  _lowerCamelCase   )

      # update_kwargs was used to update the config on valid attributes
      self.assertEqual(generation_config.max_new_tokens      ,  1_024   )

      # `.update()` returns a dictionary of unused kwargs
      self.assertEqual(_lowerCamelCase      ,  {'foo': 'bar'}   )



     def  lowerCamelCase_						(							self :Union[str, Any]   ):







      '''simple docstring'''



      UpperCamelCase_     :					Union[str, Any]   	=GenerationConfig()
      UpperCamelCase_     :					Union[str, Any]   	='bar'

      with tempfile.TemporaryDirectory('test-generation-config'   ) as tmp_dir:
       generation_config.save_pretrained(_lowerCamelCase   )

       UpperCamelCase_     :					Dict   	=GenerationConfig.from_pretrained(_lowerCamelCase   )
      # update_kwargs was used to update the config on valid attributes
      self.assertEqual(new_config.foo      ,  'bar'   )

      UpperCamelCase_     :					List[str]   	=GenerationConfig.from_model_config(_lowerCamelCase   )
      assert not hasattr(_lowerCamelCase      ,  'foo'   )  # no new kwargs should be initialized if from config




     def  lowerCamelCase_						(							self :Optional[Any]   ):







      '''simple docstring'''



      UpperCamelCase_     :					List[str]   	=GenerationConfig()
      self.assertEqual(default_config.temperature      ,  1.0   )
      self.assertEqual(default_config.do_sample      ,  _lowerCamelCase   )
      self.assertEqual(default_config.num_beams      ,  1   )

      UpperCamelCase_     :					Tuple   	=GenerationConfig(
          do_sample=_lowerCamelCase      ,  temperature=0.7      ,  length_penalty=1.0      ,  bad_words_ids=[[1, 2, 3], [4, 5]]      ,  )
      self.assertEqual(config.temperature      ,  0.7   )
      self.assertEqual(config.do_sample      ,  _lowerCamelCase   )
      self.assertEqual(config.num_beams      ,  1   )

      with tempfile.TemporaryDirectory() as tmp_dir:
       config.save_pretrained(_lowerCamelCase   )
       UpperCamelCase_     :					str   	=GenerationConfig.from_pretrained(_lowerCamelCase      ,  temperature=1.0   )

      self.assertEqual(loaded_config.temperature      ,  1.0   )
      self.assertEqual(loaded_config.do_sample      ,  _lowerCamelCase   )
      self.assertEqual(loaded_config.num_beams      ,  1   )  # default value





@is_staging_test
class 				a__					(						unittest.TestCase       ):



     @classmethod
     def  lowerCamelCase_						(							cls :Optional[Any]   ):







      '''simple docstring'''



      UpperCamelCase_     :					Dict   	=TOKEN
      HfFolder.save_token(_lowerCamelCase   )



     @classmethod
     def  lowerCamelCase_						(							cls :List[Any]   ):







      '''simple docstring'''



      try:
       delete_repo(token=cls._token      ,  repo_id='test-generation-config'   )
      except HTTPError:
       pass

      try:
       delete_repo(token=cls._token      ,  repo_id='valid_org/test-generation-config-org'   )
      except HTTPError:
       pass



     def  lowerCamelCase_						(							self :List[Any]   ):







      '''simple docstring'''



      UpperCamelCase_     :					List[str]   	=GenerationConfig(
          do_sample=_lowerCamelCase      ,  temperature=0.7      ,  length_penalty=1.0      ,  )
      config.push_to_hub('test-generation-config'      ,  use_auth_token=self._token   )

      UpperCamelCase_     :					List[Any]   	=GenerationConfig.from_pretrained(f'''{USER}/test-generation-config'''   )
      for k, v in config.to_dict().items():
       if k != "transformers_version":
        self.assertEqual(_lowerCamelCase      ,  getattr(_lowerCamelCase      ,  _lowerCamelCase   )   )

        # Reset repo
      delete_repo(token=self._token      ,  repo_id='test-generation-config'   )

      # Push to hub via save_pretrained
      with tempfile.TemporaryDirectory() as tmp_dir:
       config.save_pretrained(
           _lowerCamelCase      ,  repo_id='test-generation-config'      ,  push_to_hub=_lowerCamelCase      ,  use_auth_token=self._token   )

      UpperCamelCase_     :					Any   	=GenerationConfig.from_pretrained(f'''{USER}/test-generation-config'''   )
      for k, v in config.to_dict().items():
       if k != "transformers_version":
        self.assertEqual(_lowerCamelCase      ,  getattr(_lowerCamelCase      ,  _lowerCamelCase   )   )




     def  lowerCamelCase_						(							self :Union[str, Any]   ):







      '''simple docstring'''



      UpperCamelCase_     :					Union[str, Any]   	=GenerationConfig(
          do_sample=_lowerCamelCase      ,  temperature=0.7      ,  length_penalty=1.0      ,  )
      config.push_to_hub('valid_org/test-generation-config-org'      ,  use_auth_token=self._token   )

      UpperCamelCase_     :					int   	=GenerationConfig.from_pretrained('valid_org/test-generation-config-org'   )
      for k, v in config.to_dict().items():
       if k != "transformers_version":
        self.assertEqual(_lowerCamelCase      ,  getattr(_lowerCamelCase      ,  _lowerCamelCase   )   )

        # Reset repo
      delete_repo(token=self._token      ,  repo_id='valid_org/test-generation-config-org'   )

      # Push to hub via save_pretrained
      with tempfile.TemporaryDirectory() as tmp_dir:
       config.save_pretrained(
           _lowerCamelCase      ,  repo_id='valid_org/test-generation-config-org'      ,  push_to_hub=_lowerCamelCase      ,  use_auth_token=self._token   )

      UpperCamelCase_     :					Optional[Any]   	=GenerationConfig.from_pretrained('valid_org/test-generation-config-org'   )
      for k, v in config.to_dict().items():
       if k != "transformers_version":
        self.assertEqual(_lowerCamelCase      ,  getattr(_lowerCamelCase      ,  _lowerCamelCase   )   )
