

import copy
import os
from typing import Union

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


_a:    int 							=			logging.get_logger(__name__)

_a:    Any 							=			{
    """BAAI/AltCLIP""": """https://huggingface.co/BAAI/AltCLIP/resolve/main/config.json""",
    # See all AltCLIP models at https://huggingface.co/models?filter=altclip
}

class 						__UpperCamelCase    (					lowercase						):
	SCREAMING_SNAKE_CASE__    				=     'altclip_text_model'




	def __init__(		self	:						Any		,	lowerCAmelCase	:						Tuple=250_002		,	lowerCAmelCase	:						Tuple=1_024		,	lowerCAmelCase	:						int=24		,	lowerCAmelCase	:						List[str]=16		,	lowerCAmelCase	:						Tuple=4_096		,	lowerCAmelCase	:						Optional[int]="gelu"		,	lowerCAmelCase	:						Any=0.1		,	lowerCAmelCase	:						int=0.1		,	lowerCAmelCase	:						Dict=514		,	lowerCAmelCase	:						Union[str, Any]=1		,	lowerCAmelCase	:						Union[str, Any]=0.02		,	lowerCAmelCase	:						Tuple=0.02		,	lowerCAmelCase	:						Union[str, Any]=1e-05		,	lowerCAmelCase	:						str=1		,	lowerCAmelCase	:						Union[str, Any]=0		,	lowerCAmelCase	:						Optional[Any]=2		,	lowerCAmelCase	:						Any="absolute"		,	lowerCAmelCase	:						Dict=True		,	lowerCAmelCase	:						Any=768		,	**lowerCAmelCase	:						Dict		,	):


		'''simple docstring'''







		super().__init__(pad_token_id=lowerCAmelCase		,	bos_token_id=lowerCAmelCase		,	eos_token_id=lowerCAmelCase		,	**lowerCAmelCase							)

		UpperCAmelCase_       				=			vocab_size
		UpperCAmelCase_       				=			hidden_size
		UpperCAmelCase_       				=			num_hidden_layers
		UpperCAmelCase_       				=			num_attention_heads
		UpperCAmelCase_       				=			hidden_act
		UpperCAmelCase_       				=			intermediate_size
		UpperCAmelCase_       				=			hidden_dropout_prob
		UpperCAmelCase_       				=			attention_probs_dropout_prob
		UpperCAmelCase_       				=			max_position_embeddings
		UpperCAmelCase_       				=			type_vocab_size
		UpperCAmelCase_       				=			initializer_range
		UpperCAmelCase_       				=			initializer_factor
		UpperCAmelCase_       				=			layer_norm_eps
		UpperCAmelCase_       				=			position_embedding_type
		UpperCAmelCase_       				=			use_cache
		UpperCAmelCase_       				=			project_dim


class 						__UpperCamelCase    (					lowercase						):
	SCREAMING_SNAKE_CASE__    				=     'altclip_vision_model'




	def __init__(		self	:						Optional[Any]		,	lowerCAmelCase	:						Tuple=768		,	lowerCAmelCase	:						Optional[Any]=3_072		,	lowerCAmelCase	:						Optional[int]=512		,	lowerCAmelCase	:						Union[str, Any]=12		,	lowerCAmelCase	:						Optional[int]=12		,	lowerCAmelCase	:						List[str]=3		,	lowerCAmelCase	:						Optional[Any]=224		,	lowerCAmelCase	:						Any=32		,	lowerCAmelCase	:						List[str]="quick_gelu"		,	lowerCAmelCase	:						Optional[int]=1e-5		,	lowerCAmelCase	:						Tuple=0.0		,	lowerCAmelCase	:						str=0.02		,	lowerCAmelCase	:						Tuple=1.0		,	**lowerCAmelCase	:						Tuple		,	):


		'''simple docstring'''







		super().__init__(**lowerCAmelCase							)

		UpperCAmelCase_       				=			hidden_size
		UpperCAmelCase_       				=			intermediate_size
		UpperCAmelCase_       				=			projection_dim
		UpperCAmelCase_       				=			num_hidden_layers
		UpperCAmelCase_       				=			num_attention_heads
		UpperCAmelCase_       				=			num_channels
		UpperCAmelCase_       				=			patch_size
		UpperCAmelCase_       				=			image_size
		UpperCAmelCase_       				=			initializer_range
		UpperCAmelCase_       				=			initializer_factor
		UpperCAmelCase_       				=			attention_dropout
		UpperCAmelCase_       				=			layer_norm_eps
		UpperCAmelCase_       				=			hidden_act




	@classmethod
	def       __A					(		cls	:						Optional[Any]		,	lowerCAmelCase	:						Union[str, os.PathLike]		,	**lowerCAmelCase	:						int							):


		'''simple docstring'''







		cls._set_token_in_kwargs(lowerCAmelCase							)

		UpperCAmelCase_				,   UpperCAmelCase_       				=			cls.get_config_dict(lowerCAmelCase		,	**lowerCAmelCase							)

		# get the vision config dict if we are loading from AltCLIPConfig
		if config_dict.get("model_type"							) == "altclip":
			UpperCAmelCase_       				=			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 						__UpperCamelCase    (					lowercase						):
	SCREAMING_SNAKE_CASE__    				=     'altclip'
	SCREAMING_SNAKE_CASE__    				=     True




	def __init__(		self	:						Optional[int]		,	lowerCAmelCase	:						int=None		,	lowerCAmelCase	:						Any=None		,	lowerCAmelCase	:						List[str]=768		,	lowerCAmelCase	:						List[Any]=2.6_592		,	**lowerCAmelCase	:						List[str]							):


		'''simple docstring'''







		UpperCAmelCase_       				=			kwargs.pop("text_config_dict"		,	lowerCAmelCase							)
		UpperCAmelCase_       				=			kwargs.pop("vision_config_dict"		,	lowerCAmelCase							)

		super().__init__(**lowerCAmelCase							)

		# Instead of simply assigning `[text|vision]_config_dict` to `[text|vision]_config`, we use the values in
		# `[text|vision]_config_dict` to update the values in `[text|vision]_config`. The values should be same in most
		# cases, but we don't want to break anything regarding `_config_dict` that existed before commit `8827e1b2`.
		if text_config_dict is not None:
			if text_config is None:
				UpperCAmelCase_       				=			{}

			# This is the complete result when using `text_config_dict`.
			UpperCAmelCase_       				=			AltCLIPTextConfig(**lowerCAmelCase							).to_dict()

			# Give a warning if the values exist in both `_text_config_dict` and `text_config` but being different.
			for key, value in _text_config_dict.items():
				if key in text_config and value != text_config[key] and key not in ["transformers_version"]:
					# If specified in `text_config_dict`
					if key in text_config_dict:
						UpperCAmelCase_       				=			(
						    F"`{key}` is found in both `text_config_dict` and `text_config` but with different values. "
						    F"The value `text_config_dict[\"{key}\"]` will be used instead."
						)
					# If inferred from default argument values (just to be super careful)
					else:
						UpperCAmelCase_       				=			(
						    F"`text_config_dict` is provided which will be used to initialize `AltCLIPTextConfig`. The "
						    F"value `text_config[\"{key}\"]` will be overriden."
						)
					logger.warning(lowerCAmelCase							)

            # Update all values in `text_config` with the ones in `_text_config_dict`.
			text_config.update(_text_config_dict							)

		if vision_config_dict is not None:
			if vision_config is None:
				UpperCAmelCase_       				=			{}

			# This is the complete result when using `vision_config_dict`.
			UpperCAmelCase_       				=			AltCLIPVisionConfig(**lowerCAmelCase							).to_dict()
			# convert keys to string instead of integer
			if "id2label" in _vision_config_dict:
				UpperCAmelCase_       				=			{
				    str(lowerCAmelCase							): value for key, value in _vision_config_dict["id2label"].items()
				}

			# Give a warning if the values exist in both `_vision_config_dict` and `vision_config` but being different.
			for key, value in _vision_config_dict.items():
				if key in vision_config and value != vision_config[key] and key not in ["transformers_version"]:
					# If specified in `vision_config_dict`
					if key in vision_config_dict:
						UpperCAmelCase_       				=			(
						    F"`{key}` is found in both `vision_config_dict` and `vision_config` but with different "
						    F"values. The value `vision_config_dict[\"{key}\"]` will be used instead."
						)
					# If inferred from default argument values (just to be super careful)
					else:
						UpperCAmelCase_       				=			(
						    F"`vision_config_dict` is provided which will be used to initialize `AltCLIPVisionConfig`. "
						    F"The value `vision_config[\"{key}\"]` will be overriden."
						)
					logger.warning(lowerCAmelCase							)

            # Update all values in `vision_config` with the ones in `_vision_config_dict`.
			vision_config.update(_vision_config_dict							)

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

		if vision_config is None:
			UpperCAmelCase_       				=			{}
			logger.info("`vision_config` is `None`. initializing the `AltCLIPVisionConfig` with default values."							)

		UpperCAmelCase_       				=			AltCLIPTextConfig(**lowerCAmelCase							)
		UpperCAmelCase_       				=			AltCLIPVisionConfig(**lowerCAmelCase							)

		UpperCAmelCase_       				=			projection_dim
		UpperCAmelCase_       				=			logit_scale_init_value
		UpperCAmelCase_       				=			1.0




	@classmethod
	def       __A					(		cls	:						Tuple		,	lowerCAmelCase	:						AltCLIPTextConfig		,	lowerCAmelCase	:						AltCLIPVisionConfig		,	**lowerCAmelCase	:						Union[str, Any]							):


		'''simple docstring'''







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




	def       __A					(		self	:						int							):


		'''simple docstring'''







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


def       __lowerCAmelCase      (						A    ):
	UpperCAmelCase_       				=			generate_pascal_triangle(A    )
	for row_idx in range(A    ):
		# 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       __lowerCAmelCase      (						A    ):

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

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



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



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



def       __lowerCAmelCase      (						A    ):

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

	UpperCAmelCase_       				=			[[1]]

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

	return result



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

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


if __name__ == "__main__":
				import doctest

				doctest.testmod()
				benchmark()