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


A_    							=					logging.get_logger(__name__)

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




class  __lowerCamelCase  ( lowerCAmelCase			):
				a__:      Optional[int]          =    'blip_2_vision_model'




				def __init__(				self							,						UpperCAmelCase=1408							,						UpperCAmelCase=6144							,						UpperCAmelCase=39							,						UpperCAmelCase=16							,						UpperCAmelCase=224							,						UpperCAmelCase=14							,						UpperCAmelCase="gelu"							,						UpperCAmelCase=0.0_0_0_0_1							,						UpperCAmelCase=0.0							,						UpperCAmelCase=1e-1_0							,						UpperCAmelCase=True							,						**UpperCAmelCase							,						):
							super().__init__(**UpperCAmelCase   )

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





				@classmethod
				def        UpperCAmelCase__						(				cls							,						UpperCAmelCase							,						**UpperCAmelCase   ):
							cls._set_token_in_kwargs(UpperCAmelCase   )

							lowerCamelCase_		, lowerCamelCase_					=  cls.get_config_dict(UpperCAmelCase							,						**UpperCAmelCase   )

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




class  __lowerCamelCase  ( lowerCAmelCase			):
				a__:      Optional[int]          =    'blip_2_qformer'




				def __init__(				self							,						UpperCAmelCase=3_0522							,						UpperCAmelCase=768							,						UpperCAmelCase=12							,						UpperCAmelCase=12							,						UpperCAmelCase=3072							,						UpperCAmelCase="gelu"							,						UpperCAmelCase=0.1							,						UpperCAmelCase=0.1							,						UpperCAmelCase=512							,						UpperCAmelCase=0.0_2							,						UpperCAmelCase=1e-1_2							,						UpperCAmelCase=0							,						UpperCAmelCase="absolute"							,						UpperCAmelCase=2							,						UpperCAmelCase=1408							,						**UpperCAmelCase							,						):
							super().__init__(pad_token_id=UpperCAmelCase							,						**UpperCAmelCase   )

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





				@classmethod
				def        UpperCAmelCase__						(				cls							,						UpperCAmelCase							,						**UpperCAmelCase   ):
							cls._set_token_in_kwargs(UpperCAmelCase   )

							lowerCamelCase_		, lowerCamelCase_					=  cls.get_config_dict(UpperCAmelCase							,						**UpperCAmelCase   )

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




class  __lowerCamelCase  ( lowerCAmelCase			):
				a__:      Union[str, Any]          =    'blip-2'
				a__:      str          =    True




				def __init__(				self							,						UpperCAmelCase=None							,						UpperCAmelCase=None							,						UpperCAmelCase=None							,						UpperCAmelCase=32							,						**UpperCAmelCase   ):
							super().__init__(**UpperCAmelCase   )

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

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

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

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

							lowerCamelCase_					=  self.text_config.tie_word_embeddings
							lowerCamelCase_					=  self.text_config.is_encoder_decoder

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




				@classmethod
				def        UpperCAmelCase__						(				cls							,						UpperCAmelCase							,						UpperCAmelCase							,						UpperCAmelCase							,						**UpperCAmelCase							,						):
							return cls(
							    vision_config=vision_config.to_dict()							,						qformer_config=qformer_config.to_dict()							,						text_config=text_config.to_dict()							,						**UpperCAmelCase							,						)





				def        UpperCAmelCase__						(				self   ):
							lowerCamelCase_					=  copy.deepcopy(self.__dict__   )
							lowerCamelCase_					=  self.vision_config.to_dict()
							lowerCamelCase_					=  self.qformer_config.to_dict()
							lowerCamelCase_					=  self.text_config.to_dict()
							lowerCamelCase_					=  self.__class__.model_type
							return output





"""simple docstring"""


def  lowercase						(	lowerCAmelCase__						):
			lowerCamelCase_					=  generate_pascal_triangle(lowerCAmelCase__						)
			for row_idx in range(lowerCAmelCase__						):
						# Print left spaces
						for _ in range(num_rows - row_idx - 1						):
									print(end=''' '''						)
						# Print row values
						for col_idx in range(row_idx + 1						):
									if col_idx != row_idx:
												print(triangle[row_idx][col_idx]	,end=''' '''						)
									else:
												print(triangle[row_idx][col_idx]	,end=''''''						)
						print()






def  lowercase						(	lowerCAmelCase__						):

			if not isinstance(lowerCAmelCase__	,lowerCAmelCase__						):
						raise TypeError('''The input value of \'num_rows\' should be \'int\''''						)

			if num_rows == 0:
						return []
			elif num_rows < 0:
						raise ValueError(
						    '''The input value of \'num_rows\' should be greater than or equal to 0'''						)

			lowerCamelCase_					=  []
			for current_row_idx in range(lowerCAmelCase__						):
						lowerCamelCase_					=  populate_current_row(lowerCAmelCase__	,lowerCAmelCase__						)
						triangle.append(lowerCAmelCase__						)
			return triangle






def  lowercase						(	lowerCAmelCase__	,lowerCAmelCase__						):
			lowerCamelCase_					=  [-1] * (current_row_idx + 1)
			# first and last elements of current row are equal to 1
			lowerCamelCase_		, lowerCamelCase_					=  1, 1
			for current_col_idx in range(1	,lowerCAmelCase__						):
						calculate_current_element(
						    lowerCAmelCase__	,lowerCAmelCase__	,lowerCAmelCase__	,lowerCAmelCase__						)
			return current_row






def  lowercase						(	lowerCAmelCase__	,lowerCAmelCase__	,lowerCAmelCase__	,lowerCAmelCase__	,):
			lowerCamelCase_					=  triangle[current_row_idx - 1][current_col_idx - 1]
			lowerCamelCase_					=  triangle[current_row_idx - 1][current_col_idx]
			lowerCamelCase_					=  above_to_left_elt + above_to_right_elt






def  lowercase						(	lowerCAmelCase__						):

			if not isinstance(lowerCAmelCase__	,lowerCAmelCase__						):
						raise TypeError('''The input value of \'num_rows\' should be \'int\''''						)

			if num_rows == 0:
						return []
			elif num_rows < 0:
						raise ValueError(
						    '''The input value of \'num_rows\' should be greater than or equal to 0'''						)

			lowerCamelCase_					=  [[1]]

			for row_index in range(1	,lowerCAmelCase__						):
						lowerCamelCase_					=  [0] + result[-1] + [0]
						lowerCamelCase_					=  row_index + 1
						# Calculate the number of distinct elements in a row
						lowerCamelCase_					=  sum(divmod(lowerCAmelCase__	,2						)						)
						lowerCamelCase_					=  [
						    temp_row[i - 1] + temp_row[i] for i in range(1	,distinct_elements + 1						)
						]
						lowerCamelCase_					=  row_first_half[: (row_index + 1) // 2]
						row_second_half.reverse()
						lowerCamelCase_					=  row_first_half + row_second_half
						result.append(lowerCAmelCase__						)

			return result






def  lowercase						(	):
			from collections.abc import Callable
			from timeit import timeit

			def benchmark_a_function(lowerCAmelCase__	,lowerCAmelCase__						) -> None:
						lowerCamelCase_					=  f"{func.__name__}({value})"
						lowerCamelCase_					=  timeit(f"__main__.{call}"	,setup='''import __main__'''						)
						# print(f"{call:38} = {func(value)} -- {timing:.4f} seconds")
						print(f"{call:38} -- {timing:.4f} seconds"						)

			for value in range(15						):  # (1, 7, 14):
						for func in (generate_pascal_triangle, generate_pascal_triangle_optimized):
									benchmark_a_function(lowerCAmelCase__	,lowerCAmelCase__						)
						print()


if __name__ == "__main__":
						import doctest

						doctest.testmod()
						benchmark()



