



"""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/blip2-opt-2.7b': 'https://huggingface.co/salesforce/blip2-opt-2.7b/resolve/main/config.json',
}
class        __A       (	A_    ):







		'''simple docstring'''





		lowerCAmelCase			:					str   	=				"blip_2_vision_model"







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






				"""simple docstring"""



				super().__init__(**_snake_case						)

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







		@classmethod
		def 					UpperCAmelCase    (	cls						:  List[str]			,_snake_case						:  Union[str, os.PathLike]			,**_snake_case						:  Optional[int]						)					->		"PretrainedConfig":






				"""simple docstring"""



				cls._set_token_in_kwargs(_snake_case						)

				lowercase__		,			lowercase__   :    Dict				=			cls.get_config_dict(_snake_case			,**_snake_case						)

				# get the vision config dict if we are loading from Blip2Config
				if config_dict.get('''model_type'''						) == "blip-2":
						lowercase__   :    str				=			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(_snake_case			,**_snake_case						)





class        __A       (	A_    ):







		'''simple docstring'''





		lowerCAmelCase			:					Union[str, Any]   	=				"blip_2_qformer"







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






				"""simple docstring"""



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

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







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






				"""simple docstring"""



				cls._set_token_in_kwargs(_snake_case						)

				lowercase__		,			lowercase__   :    Dict				=			cls.get_config_dict(_snake_case			,**_snake_case						)

				# get the qformer config dict if we are loading from Blip2Config
				if config_dict.get('''model_type'''						) == "blip-2":
						lowercase__   :    Tuple				=			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(_snake_case			,**_snake_case						)





class        __A       (	A_    ):







		'''simple docstring'''





		lowerCAmelCase			:					Dict   	=				"blip-2"
		lowerCAmelCase			:					Tuple   	=				True







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






				"""simple docstring"""



				super().__init__(**_snake_case						)

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

				if qformer_config is None:
						lowercase__   :    Optional[Any]				=			{}
						logger.info('''qformer_config is None. Initializing the Blip2QFormerConfig with default values.'''						)

				if text_config is None:
						lowercase__   :    Optional[Any]				=			{}
						logger.info('''text_config is None. Initializing the text config with default values (`OPTConfig`).'''						)

				lowercase__   :    List[str]				=			BlipaVisionConfig(**_snake_case						)
				lowercase__   :    Union[str, Any]				=			BlipaQFormerConfig(**_snake_case						)
				lowercase__   :    Tuple				=			text_config['''model_type'''] if '''model_type''' in text_config else '''opt'''
				lowercase__   :    List[str]				=			CONFIG_MAPPING[text_model_type](**_snake_case						)

				lowercase__   :    int				=			self.text_config.tie_word_embeddings
				lowercase__   :    Any				=			self.text_config.is_encoder_decoder

				lowercase__   :    Union[str, Any]				=			num_query_tokens
				lowercase__   :    Union[str, Any]				=			self.vision_config.hidden_size
				lowercase__   :    Optional[Any]				=			self.text_config.model_type in MODEL_FOR_CAUSAL_LM_MAPPING_NAMES
				lowercase__   :    List[str]				=			1.0
				lowercase__   :    Any				=			0.02







		@classmethod
		def 					UpperCAmelCase    (	cls						:  Tuple			,_snake_case						:  BlipaVisionConfig			,_snake_case						:  BlipaQFormerConfig			,_snake_case						:  PretrainedConfig			,**_snake_case						:  int			,)					->		List[str]:






				"""simple docstring"""



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







		def 					UpperCAmelCase    (	self						:  int						)					->		Union[str, Any]:






				"""simple docstring"""



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





"""simple docstring"""







from dataclasses import dataclass, field
from typing import TYPE_CHECKING, Any, ClassVar, Dict, List, Optional, Union

import pyarrow as pa


if TYPE_CHECKING:
							from .features import FeatureType
@dataclass
class        __A       :







		'''simple docstring'''





		lowerCAmelCase			:					List[str]
		lowerCAmelCase			:					Optional[str]   	=				None
		# Automatically constructed
		lowerCAmelCase			:					ClassVar[str]   	=				"dict"
		lowerCAmelCase			:					ClassVar[Any]   	=				None
		lowerCAmelCase			:					str   	=				field(default="Translation"     ,init=A_     ,repr=A_    )







		def __call__(	self						:  List[str]						)					->		Any:






				"""simple docstring"""



				return pa.struct({lang: pa.string() for lang in sorted(self.languages						)}						)







		def 					UpperCAmelCase    (	self						:  List[str]						)					->		Union["FeatureType", Dict[str, "FeatureType"]]:






				"""simple docstring"""



				from .features import Value

				return {k: Value('''string'''						) for k in sorted(self.languages						)}





@dataclass
class        __A       :







		'''simple docstring'''





		lowerCAmelCase			:					Optional[List]   	=				None
		lowerCAmelCase			:					Optional[int]   	=				None
		lowerCAmelCase			:					Optional[str]   	=				None
		# Automatically constructed
		lowerCAmelCase			:					ClassVar[str]   	=				"dict"
		lowerCAmelCase			:					ClassVar[Any]   	=				None
		lowerCAmelCase			:					str   	=				field(default="TranslationVariableLanguages"     ,init=A_     ,repr=A_    )







		def 					UpperCAmelCase    (	self						:  List[Any]						)					->		Optional[int]:






				"""simple docstring"""



				lowercase__   :    Optional[int]				=			sorted(set(self.languages						)						) if self.languages else None
				lowercase__   :    Dict				=			len(self.languages						) if self.languages else None







		def __call__(	self						:  List[Any]						)					->		List[Any]:






				"""simple docstring"""



				return pa.struct({'''language''': pa.list_(pa.string()						), '''translation''': pa.list_(pa.string()						)}						)







		def 					UpperCAmelCase    (	self						:  Dict			,_snake_case						:  Tuple						)					->		int:






				"""simple docstring"""



				lowercase__   :    List[Any]				=			set(self.languages						)
				if self.languages and set(_snake_case						) - lang_set:
						raise ValueError(
						    f"""Some languages in example ({", ".join(sorted(set(_snake_case						) - lang_set						)						)}) are not in valid set ({", ".join(_snake_case						)})."""						)

				# Convert dictionary into tuples, splitting out cases where there are
				# multiple translations for a single language.
				lowercase__   :    str				=			[]
				for lang, text in translation_dict.items():
						if isinstance(_snake_case			,_snake_case						):
								translation_tuples.append((lang, text)						)
						else:
								translation_tuples.extend([(lang, el) for el in text]						)

        # Ensure translations are in ascending order by language code.
				lowercase__		,			lowercase__   :    Optional[Any]				=			zip(*sorted(_snake_case						)						)

				return {"language": languages, "translation": translations}







		def 					UpperCAmelCase    (	self						:  List[Any]						)					->		Union["FeatureType", Dict[str, "FeatureType"]]:






				"""simple docstring"""



				from .features import Sequence, Value

				return {
				    "language": Sequence(Value('''string'''						)						),
				    "translation": Sequence(Value('''string'''						)						),
				}
