
import copy
import os
from typing import Union

from ...configuration_utils import PretrainedConfig
from ...utils import logging


__lowerCAmelCase			:     Any           =   logging.get_logger(__name__)

__lowerCAmelCase			:     List[str]           =   {
    'BridgeTower/bridgetower-base': 'https://huggingface.co/BridgeTower/bridgetower-base/blob/main/config.json',
    'BridgeTower/bridgetower-base-itm-mlm': (
        'https://huggingface.co/BridgeTower/bridgetower-base-itm-mlm/blob/main/config.json'
    ),
}




class        UpperCAmelCase_			( lowercase_     ):


  '''simple docstring'''







  a__           =		"""bridgetower_vision_model"""
  def __init__( self			: Tuple			,							UpperCamelCase__			: List[str]=768			,							UpperCamelCase__			: Optional[int]=12			,							UpperCamelCase__			: List[str]=3			,							UpperCamelCase__			: Optional[Any]=16			,							UpperCamelCase__			: Union[str, Any]=288			,							UpperCamelCase__			: List[str]=1			,							UpperCamelCase__			: Dict=1E-05			,							UpperCamelCase__			: Tuple=False			,							UpperCamelCase__			: Optional[int]=True			,							UpperCamelCase__			: Any=False			,							**UpperCamelCase__			: Optional[int]			,							)			->	Optional[int]:







    """simple docstring"""






    super().__init__(**__UpperCamelCase    )
    __magic_name__				     =       hidden_size
    __magic_name__				     =       num_hidden_layers
    __magic_name__				     =       num_channels
    __magic_name__				     =       patch_size
    __magic_name__				     =       image_size
    __magic_name__				     =       initializer_factor
    __magic_name__				     =       layer_norm_eps
    __magic_name__				     =       stop_gradient
    __magic_name__				     =       share_layernorm
    __magic_name__				     =       remove_last_layer





  @classmethod
  def 							_lowercase							( cls			: int			,							UpperCamelCase__			: Union[str, os.PathLike]			,							**UpperCamelCase__			: List[str]    )			->	List[str]:







    """simple docstring"""






    __magic_name__     ,    __magic_name__				     =       cls.get_config_dict(__UpperCamelCase			,							**__UpperCamelCase    )

    if config_dict.get("""model_type"""    ) == "bridgetower":
      __magic_name__				     =       config_dict["""text_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        UpperCAmelCase_			( lowercase_     ):


  '''simple docstring'''







  a__           =		"""bridgetower_text_model"""
  def __init__( self			: List[Any]			,							UpperCamelCase__			: Any=5_0265			,							UpperCamelCase__			: List[Any]=768			,							UpperCamelCase__			: List[str]=12			,							UpperCamelCase__			: Optional[Any]=12			,							UpperCamelCase__			: str=1			,							UpperCamelCase__			: Optional[Any]=3072			,							UpperCamelCase__			: Tuple="gelu"			,							UpperCamelCase__			: List[Any]=0.1			,							UpperCamelCase__			: Tuple=0.1			,							UpperCamelCase__			: str=514			,							UpperCamelCase__			: List[Any]=1			,							UpperCamelCase__			: Dict=1E-05			,							UpperCamelCase__			: Dict=1			,							UpperCamelCase__			: str=0			,							UpperCamelCase__			: Tuple=2			,							UpperCamelCase__			: str="absolute"			,							UpperCamelCase__			: Union[str, Any]=True			,							**UpperCamelCase__			: Any			,							)			->	str:







    """simple docstring"""






    super().__init__(**__UpperCamelCase    )

    __magic_name__				     =       vocab_size
    __magic_name__				     =       hidden_size
    __magic_name__				     =       num_hidden_layers
    __magic_name__				     =       num_attention_heads
    __magic_name__				     =       hidden_act
    __magic_name__				     =       initializer_factor
    __magic_name__				     =       intermediate_size
    __magic_name__				     =       hidden_dropout_prob
    __magic_name__				     =       attention_probs_dropout_prob
    __magic_name__				     =       max_position_embeddings
    __magic_name__				     =       type_vocab_size
    __magic_name__				     =       layer_norm_eps
    __magic_name__				     =       position_embedding_type
    __magic_name__				     =       use_cache
    __magic_name__				     =       pad_token_id
    __magic_name__				     =       bos_token_id
    __magic_name__				     =       eos_token_id





  @classmethod
  def 							_lowercase							( cls			: Dict			,							UpperCamelCase__			: Union[str, os.PathLike]			,							**UpperCamelCase__			: Tuple    )			->	List[Any]:







    """simple docstring"""






    __magic_name__     ,    __magic_name__				     =       cls.get_config_dict(__UpperCamelCase			,							**__UpperCamelCase    )

    if config_dict.get("""model_type"""    ) == "bridgetower":
      __magic_name__				     =       config_dict["""text_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        UpperCAmelCase_			( lowercase_     ):


  '''simple docstring'''







  a__           =		"""bridgetower"""
  def __init__( self			: List[str]			,							UpperCamelCase__			: Union[str, Any]=True			,							UpperCamelCase__			: int="gelu"			,							UpperCamelCase__			: Union[str, Any]=768			,							UpperCamelCase__			: int=1			,							UpperCamelCase__			: List[Any]=1E-05			,							UpperCamelCase__			: Optional[Any]=False			,							UpperCamelCase__			: Dict="add"			,							UpperCamelCase__			: List[str]=12			,							UpperCamelCase__			: Optional[Any]=6			,							UpperCamelCase__			: Optional[int]=False			,							UpperCamelCase__			: List[str]=False			,							UpperCamelCase__			: str=None			,							UpperCamelCase__			: Any=None			,							**UpperCamelCase__			: Dict			,							)			->	Any:







    """simple docstring"""






    __magic_name__				     =       kwargs.pop("""text_config_dict"""			,							__UpperCamelCase    )
    __magic_name__				     =       kwargs.pop("""vision_config_dict"""			,							__UpperCamelCase    )

    super().__init__(**__UpperCamelCase    )
    __magic_name__				     =       share_cross_modal_transformer_layers
    __magic_name__				     =       hidden_act
    __magic_name__				     =       hidden_size
    __magic_name__				     =       initializer_factor
    __magic_name__				     =       layer_norm_eps
    __magic_name__				     =       share_link_tower_layers
    __magic_name__				     =       link_tower_type
    __magic_name__				     =       num_attention_heads
    __magic_name__				     =       num_hidden_layers
    __magic_name__				     =       tie_word_embeddings
    __magic_name__				     =       init_layernorm_from_vision_encoder

    if text_config is None:
      __magic_name__				     =       {}
      logger.info("""`text_config` is `None`. Initializing the `BridgeTowerTextConfig` with default values."""    )

    if vision_config is None:
      __magic_name__				     =       {}
      logger.info("""`vision_config` is `None`. Initializing the `BridgeTowerVisionConfig` with default values."""    )

    __magic_name__				     =       BridgeTowerTextConfig(**__UpperCamelCase    )
    __magic_name__				     =       BridgeTowerVisionConfig(**__UpperCamelCase    )
  @classmethod
  def 							_lowercase							( cls			: str			,							UpperCamelCase__			: BridgeTowerTextConfig			,							UpperCamelCase__			: BridgeTowerVisionConfig			,							**UpperCamelCase__			: int    )			->	int:







    """simple docstring"""






    return cls(text_config=text_config.to_dict()			,							vision_config=vision_config.to_dict()			,							**__UpperCamelCase    )





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







    """simple docstring"""






    __magic_name__				     =       copy.deepcopy(self.__dict__    )
    __magic_name__				     =       self.text_config.to_dict()
    __magic_name__				     =       self.vision_config.to_dict()
    __magic_name__				     =       self.__class__.model_type
    return output








"""simple docstring"""
def 					A__				(			UpperCamelCase       ):
							A		=  generate_pascal_triangle(UpperCamelCase       )
							for row_idx in range(UpperCamelCase       ):
														# 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 					A__				(			UpperCamelCase       ):

							if not isinstance(UpperCamelCase					,  UpperCamelCase       ):
														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"       )

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






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






def 					A__				(			UpperCamelCase					,  UpperCamelCase					,  UpperCamelCase					,  UpperCamelCase					,  ):
							A		=  triangle[current_row_idx - 1][current_col_idx - 1]
							A		=  triangle[current_row_idx - 1][current_col_idx]
							A		=  above_to_left_elt + above_to_right_elt






def 					A__				(			UpperCamelCase       ):

							if not isinstance(UpperCamelCase					,  UpperCamelCase       ):
														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"       )

							A		=  [[1]]

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

							return result






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

							def benchmark_a_function(UpperCamelCase					,  UpperCamelCase       ) -> None:
														A		=  F"{func.__name__}({value})"
														A		=  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(UpperCamelCase					,  UpperCamelCase       )
														print()


if __name__ == "__main__":
		import doctest

		doctest.testmod()
		benchmark()


