'''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_	:		Union[str, Any]			=     logging.get_logger(__name__)

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




class 		SCREAMING_SNAKE_CASE     (					SCREAMING_SNAKE_CASE	):







				'''simple docstring'''
				UpperCAmelCase__							=							'''instructblip_vision_model'''





				def __init__(						self					:						Optional[Any]       ,		lowercase__					:						int=1_408       ,		lowercase__					:						Dict=6_144       ,		lowercase__					:						Dict=39       ,		lowercase__					:						Optional[Any]=16       ,		lowercase__					:						Union[str, Any]=224       ,		lowercase__					:						Optional[int]=14       ,		lowercase__					:						Tuple="gelu"       ,		lowercase__					:						Any=1e-6       ,		lowercase__					:						List[str]=0.0       ,		lowercase__					:						Optional[int]=1e-10       ,		lowercase__					:						int=True       ,		**lowercase__					:						Optional[Any]       ,		)							->List[Any]:


										'''simple docstring'''




										super().__init__(**lowercase__					)

										_UpperCamelCase			:			Optional[Any]   			=						hidden_size
										_UpperCamelCase			:			Optional[Any]   			=						intermediate_size
										_UpperCamelCase			:			str   			=						num_hidden_layers
										_UpperCamelCase			:			List[str]   			=						num_attention_heads
										_UpperCamelCase			:			int   			=						patch_size
										_UpperCamelCase			:			int   			=						image_size
										_UpperCamelCase			:			int   			=						initializer_range
										_UpperCamelCase			:			Optional[int]   			=						attention_dropout
										_UpperCamelCase			:			Optional[int]   			=						layer_norm_eps
										_UpperCamelCase			:			str   			=						hidden_act
										_UpperCamelCase			:			Optional[Any]   			=						qkv_bias







				@classmethod
				def  snake_case__				(						cls					:						Dict       ,		lowercase__					:						Union[str, os.PathLike]       ,		**lowercase__					:						int					)							->"PretrainedConfig":


										'''simple docstring'''




										cls._set_token_in_kwargs(lowercase__					)

										_UpperCamelCase			,       _UpperCamelCase			:			Tuple   			=						cls.get_config_dict(lowercase__       ,		**lowercase__					)

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





class 		SCREAMING_SNAKE_CASE     (					SCREAMING_SNAKE_CASE	):







				'''simple docstring'''
				UpperCAmelCase__							=							'''instructblip_qformer'''





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


										'''simple docstring'''




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

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







				@classmethod
				def  snake_case__				(						cls					:						Any       ,		lowercase__					:						Union[str, os.PathLike]       ,		**lowercase__					:						str					)							->"PretrainedConfig":


										'''simple docstring'''




										cls._set_token_in_kwargs(lowercase__					)

										_UpperCamelCase			,       _UpperCamelCase			:			Optional[Any]   			=						cls.get_config_dict(lowercase__       ,		**lowercase__					)

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





class 		SCREAMING_SNAKE_CASE     (					SCREAMING_SNAKE_CASE	):







				'''simple docstring'''
				UpperCAmelCase__							=							'''instructblip'''
				UpperCAmelCase__							=							True





				def __init__(						self					:						Tuple       ,		lowercase__					:						Tuple=None       ,		lowercase__					:						Any=None       ,		lowercase__					:						List[str]=None       ,		lowercase__					:						Any=32       ,		**lowercase__					:						int					)							->Optional[int]:


										'''simple docstring'''




										super().__init__(**lowercase__					)

										if vision_config is None:
																_UpperCamelCase			:			Any   			=						{}
																logger.info("vision_config is None. initializing the InstructBlipVisionConfig with default values."					)

										if qformer_config is None:
																_UpperCamelCase			:			Optional[Any]   			=						{}
																logger.info("qformer_config is None. Initializing the InstructBlipQFormerConfig with default values."					)

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

										_UpperCamelCase			:			Optional[Any]   			=						InstructBlipVisionConfig(**lowercase__					)
										_UpperCamelCase			:			Optional[Any]   			=						InstructBlipQFormerConfig(**lowercase__					)
										_UpperCamelCase			:			Optional[Any]   			=						text_config["model_type"] if "model_type" in text_config else "opt"
										_UpperCamelCase			:			Optional[Any]   			=						CONFIG_MAPPING[text_model_type](**lowercase__					)

										_UpperCamelCase			:			str   			=						self.text_config.tie_word_embeddings
										_UpperCamelCase			:			List[str]   			=						self.text_config.is_encoder_decoder

										_UpperCamelCase			:			List[Any]   			=						num_query_tokens
										_UpperCamelCase			:			str   			=						self.vision_config.hidden_size
										_UpperCamelCase			:			Optional[int]   			=						self.text_config.model_type in MODEL_FOR_CAUSAL_LM_MAPPING_NAMES
										_UpperCamelCase			:			List[Any]   			=						1.0
										_UpperCamelCase			:			Any   			=						0.0_2





				@classmethod
				def  snake_case__				(						cls					:						Any       ,		lowercase__					:						InstructBlipVisionConfig       ,		lowercase__					:						InstructBlipQFormerConfig       ,		lowercase__					:						PretrainedConfig       ,		**lowercase__					:						Tuple       ,		)							->str:


										'''simple docstring'''




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







				def  snake_case__				(						self					:						int					)							->Any:


										'''simple docstring'''




										_UpperCamelCase			:			Dict   			=						copy.deepcopy(self.__dict__					)
										_UpperCamelCase			:			Optional[Any]   			=						self.vision_config.to_dict()
										_UpperCamelCase			:			int   			=						self.qformer_config.to_dict()
										_UpperCamelCase			:			Union[str, Any]   			=						self.text_config.to_dict()
										_UpperCamelCase			:			List[str]   			=						self.__class__.model_type
										return output



'''simple docstring'''





import time
import warnings
from abc import ABC
from copy import deepcopy
from typing import Optional

import torch

from ..utils import add_start_docstrings, logging


lowerCAmelCase_	:		Optional[int]			=     logging.get_logger(__name__)


lowerCAmelCase_	:		int			=     r"""
    Args:
        input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
            Indices of input sequence tokens in the vocabulary.

            Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
            [`PreTrainedTokenizer.__call__`] for details.

            [What are input IDs?](../glossary#input-ids)
        scores (`torch.FloatTensor` of shape `(batch_size, config.vocab_size)`):
            Prediction scores of a language modeling head. These can be scores for each vocabulary token before SoftMax
            or scores for each vocabulary token after SoftMax.
        kwargs (`Dict[str, Any]`, *optional*):
            Additional stopping criteria specific kwargs.

    Return:
        `bool`. `False` indicates we should continue, `True` indicates we should stop.

"""




class 		SCREAMING_SNAKE_CASE     (					SCREAMING_SNAKE_CASE	):







				'''simple docstring'''





				@add_start_docstrings(lowercase__					)
				def __call__(						self					:						str       ,		lowercase__					:						torch.LongTensor       ,		lowercase__					:						torch.FloatTensor       ,		**lowercase__					:						Tuple					)							->bool:


										'''simple docstring'''




										raise NotImplementedError("StoppingCriteria needs to be subclassed"					)





class 		SCREAMING_SNAKE_CASE     (					SCREAMING_SNAKE_CASE	):







				'''simple docstring'''





				def __init__(						self					:						Union[str, Any]       ,		lowercase__					:						int       ,		lowercase__					:						Optional[int] = None					)							->Union[str, Any]:


										'''simple docstring'''




										_UpperCamelCase			:			Optional[Any]   			=						max_length
										_UpperCamelCase			:			str   			=						max_position_embeddings







				@add_start_docstrings(lowercase__					)
				def __call__(						self					:						Optional[int]       ,		lowercase__					:						torch.LongTensor       ,		lowercase__					:						torch.FloatTensor       ,		**lowercase__					:						Optional[Any]					)							->bool:


										'''simple docstring'''




										_UpperCamelCase			:			List[Any]   			=						input_ids.shape[-1]
										_UpperCamelCase			:			Optional[int]   			=						cur_len >= self.max_length
										if self.max_position_embeddings is not None and not is_done and cur_len >= self.max_position_embeddings:
																logger.warning_once(
																    "This is a friendly reminder - the current text generation call will exceed the model's predefined "
																    f'''maximum length ({self.max_position_embeddings}). Depending on the model, you may observe '''
																    "exceptions, performance degradation, or nothing at all."					)
										return is_done





class 		SCREAMING_SNAKE_CASE     (					SCREAMING_SNAKE_CASE	):







				'''simple docstring'''





				def __init__(						self					:						List[Any]       ,		lowercase__					:						int       ,		lowercase__					:						int					)							->int:


										'''simple docstring'''




										warnings.warn(
										    "The class `MaxNewTokensCriteria` is deprecated. "
										    f'''Please use `MaxLengthCriteria(max_length={start_length + max_new_tokens})` '''
										    "with `max_length = start_length + max_new_tokens` instead."       ,		lowercase__       ,		)
										_UpperCamelCase			:			Dict   			=						start_length
										_UpperCamelCase			:			Optional[Any]   			=						max_new_tokens
										_UpperCamelCase			:			List[Any]   			=						start_length + max_new_tokens







				@add_start_docstrings(lowercase__					)
				def __call__(						self					:						Dict       ,		lowercase__					:						torch.LongTensor       ,		lowercase__					:						torch.FloatTensor       ,		**lowercase__					:						Dict					)							->bool:


										'''simple docstring'''




										return input_ids.shape[-1] >= self.max_length





class 		SCREAMING_SNAKE_CASE     (					SCREAMING_SNAKE_CASE	):







				'''simple docstring'''





				def __init__(						self					:						Union[str, Any]       ,		lowercase__					:						float       ,		lowercase__					:						Optional[float] = None					)							->Dict:


										'''simple docstring'''




										_UpperCamelCase			:			Dict   			=						max_time
										_UpperCamelCase			:			int   			=						time.time() if initial_timestamp is None else initial_timestamp







				@add_start_docstrings(lowercase__					)
				def __call__(						self					:						Dict       ,		lowercase__					:						torch.LongTensor       ,		lowercase__					:						torch.FloatTensor       ,		**lowercase__					:						Tuple					)							->bool:


										'''simple docstring'''




										return time.time() - self.initial_timestamp > self.max_time





class 		SCREAMING_SNAKE_CASE     (					SCREAMING_SNAKE_CASE	):







				'''simple docstring'''





				@add_start_docstrings(lowercase__					)
				def __call__(						self					:						Optional[int]       ,		lowercase__					:						torch.LongTensor       ,		lowercase__					:						torch.FloatTensor       ,		**lowercase__					:						List[Any]					)							->bool:


										'''simple docstring'''




										return any(criteria(lowercase__       ,		lowercase__					) for criteria in self					)







				@property
				def  snake_case__				(						self					:						Tuple					)							->Optional[int]:


										'''simple docstring'''




										for stopping_criterium in self:
																if isinstance(lowercase__       ,		lowercase__					):
																						return stopping_criterium.max_length
																elif isinstance(lowercase__       ,		lowercase__					):
																						return stopping_criterium.max_length
										return None





def 						__A							(     UpperCAmelCase     ,UpperCAmelCase					)     ->			StoppingCriteriaList:




						'''simple docstring'''
						_UpperCamelCase			:			Optional[int]   			=						stopping_criteria.max_length
						_UpperCamelCase			:			Optional[Any]   			=						deepcopy(UpperCAmelCase					)
						if stopping_max_length is not None and stopping_max_length != max_length:
												warnings.warn("You set different `max_length` for stopping criteria and `max_length` parameter"     ,UpperCAmelCase					)
						elif stopping_max_length is None:
												new_stopping_criteria.append(MaxLengthCriteria(max_length=UpperCAmelCase					)					)
						return new_stopping_criteria


