






import copy
import os
from typing import Union

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


__A      =				logging.get_logger(__name__)

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





class 						SCREAMING_SNAKE_CASE				( snake_case					):





							"""simple docstring"""

							A_						  =					"altclip_text_model"

							def __init__(  self:   List[str]		,     __A:   Union[str, Any]=25_00_02		,     __A:   List[str]=10_24		,     __A:   int=24		,     __A:   int=16		,     __A:   Dict=40_96		,     __A:   List[Any]="gelu"		,     __A:   List[str]=0.1		,     __A:   List[str]=0.1		,     __A:   int=5_14		,     __A:   Optional[Any]=1		,     __A:   int=0.02		,     __A:   Tuple=0.02		,     __A:   Optional[int]=1e-05		,     __A:   Any=1		,     __A:   Optional[int]=0		,     __A:   Union[str, Any]=2		,     __A:   Dict="absolute"		,     __A:   Any=True		,     __A:   Tuple=7_68		,     **__A:   Optional[int]		,     )    ->				Tuple:
												super().__init__(pad_token_id=__A		,     bos_token_id=__A		,     eos_token_id=__A		,     **__A   )

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





class 						SCREAMING_SNAKE_CASE				( snake_case					):





							"""simple docstring"""

							A_						  =					"altclip_vision_model"

							def __init__(  self:   Any		,     __A:   Union[str, Any]=7_68		,     __A:   List[Any]=30_72		,     __A:   str=5_12		,     __A:   Optional[int]=12		,     __A:   Optional[int]=12		,     __A:   Optional[Any]=3		,     __A:   Tuple=2_24		,     __A:   Dict=32		,     __A:   Tuple="quick_gelu"		,     __A:   List[str]=1e-5		,     __A:   Tuple=0.0		,     __A:   Tuple=0.02		,     __A:   str=1.0		,     **__A:   str		,     )    ->				int:
												super().__init__(**__A   )

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



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

												_A							,_A								= cls.get_config_dict(__A		,     **__A   )

												# get the vision config dict if we are loading from AltCLIPConfig
												if config_dict.get('''model_type'''   ) == "altclip":
																	_A								= 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(__A		,     **__A   )





class 						SCREAMING_SNAKE_CASE				( snake_case					):





							"""simple docstring"""

							A_						  =					"altclip"
							A_						  =					True

							def __init__(  self:   Optional[int]		,     __A:   Tuple=None		,     __A:   Union[str, Any]=None		,     __A:   Dict=7_68		,     __A:   Optional[Any]=2.6_592		,     **__A:   Dict   )    ->				Optional[int]:
												# If `_config_dict` exist, we use them for the backward compatibility.
												# We pop out these 2 attributes before calling `super().__init__` to avoid them being saved (which causes a lot
												# of confusion!).
												_A								= kwargs.pop('''text_config_dict'''		,     __A   )
												_A								= kwargs.pop('''vision_config_dict'''		,     __A   )

												super().__init__(**__A   )

												# 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:
																						_A								= {}

																	# This is the complete result when using `text_config_dict`.
																	_A								= AltCLIPTextConfig(**__A   ).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:
																																_A								= (
																																    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:
																																_A								= (
																																    f"""`text_config_dict` is provided which will be used to initialize `AltCLIPTextConfig`. The """
																																    f"""value `text_config[\"{key}\"]` will be overriden."""
																																)
																											logger.warning(__A   )

            # 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:
																						_A								= {}

																	# This is the complete result when using `vision_config_dict`.
																	_A								= AltCLIPVisionConfig(**__A   ).to_dict()
																	# convert keys to string instead of integer
																	if "id2label" in _vision_config_dict:
																						_A								= {
																						    str(__A   ): 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:
																																_A								= (
																																    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:
																																_A								= (
																																    f"""`vision_config_dict` is provided which will be used to initialize `AltCLIPVisionConfig`. """
																																    f"""The value `vision_config[\"{key}\"]` will be overriden."""
																																)
																											logger.warning(__A   )

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

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

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

												_A								= AltCLIPTextConfig(**__A   )
												_A								= AltCLIPVisionConfig(**__A   )

												_A								= projection_dim
												_A								= logit_scale_init_value
												_A								= 1.0

							@classmethod
							def       __A (  cls:   str		,     __A:   AltCLIPTextConfig		,     __A:   AltCLIPVisionConfig		,     **__A:   Dict   )    ->				str:
												return cls(text_config=text_config.to_dict()		,     vision_config=vision_config.to_dict()		,     **__A   )



							def       __A (  self:   str   )    ->				Dict:
												_A								= copy.deepcopy(self.__dict__   )
												_A								= self.text_config.to_dict()
												_A								= self.vision_config.to_dict()
												_A								= self.__class__.model_type
												return output











__A      =				{0: [2, 3], 1: [0], 2: [1], 3: [4], 4: []}

__A      =				{0: [1, 2, 3], 1: [2], 2: [0], 3: [4], 4: [5], 5: [3]}




def      __A					(     _lowercase					,			_lowercase					,			_lowercase ):

					'''simple docstring'''







					_A								= True
					_A								= []

					for neighbour in graph[vert]:
										if not visited[neighbour]:
															order += topology_sort(_lowercase					,			_lowercase					,			_lowercase )

					order.append(_lowercase )

					return order




def      __A					(     _lowercase					,			_lowercase					,			_lowercase ):

					'''simple docstring'''







					_A								= True
					_A								= [vert]

					for neighbour in reversed_graph[vert]:
										if not visited[neighbour]:
															component += find_components(_lowercase					,			_lowercase					,			_lowercase )

					return component




def      __A					(     _lowercase ):

					'''simple docstring'''







					_A								= len(_lowercase ) * [False]
					_A								= {vert: [] for vert in range(len(_lowercase ) )}

					for vert, neighbours in graph.items():
										for neighbour in neighbours:
															reversed_graph[neighbour].append(_lowercase )

					_A								= []
					for i, was_visited in enumerate(_lowercase ):
										if not was_visited:
															order += topology_sort(_lowercase					,			_lowercase					,			_lowercase )

					_A								= []
					_A								= len(_lowercase ) * [False]

					for i in range(len(_lowercase ) ):
										_A								= order[len(_lowercase ) - i - 1]
										if not visited[vert]:
															_A								= find_components(_lowercase					,			_lowercase					,			_lowercase )
															components_list.append(_lowercase )

					return components_list



