



'''simple docstring'''






import copy
import os
from typing import Union

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


lowerCAmelCase: Any							=						logging.get_logger(__name__)

lowerCAmelCase: Union[str, Any]							=						{
    'BAAI/AltCLIP': 'https://huggingface.co/BAAI/AltCLIP/resolve/main/config.json',
    # See all AltCLIP models at https://huggingface.co/models?filter=altclip
}

class 							a__( lowerCamelCase__     ):
    lowercase__			=   """altclip_text_model"""







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

      a						: int					       =					vocab_size
      a						: Tuple					       =					hidden_size
      a						: List[Any]					       =					num_hidden_layers
      a						: int					       =					num_attention_heads
      a						: List[Any]					       =					hidden_act
      a						: str					       =					intermediate_size
      a						: Union[str, Any]					       =					hidden_dropout_prob
      a						: Dict					       =					attention_probs_dropout_prob
      a						: Union[str, Any]					       =					max_position_embeddings
      a						: Union[str, Any]					       =					type_vocab_size
      a						: int					       =					initializer_range
      a						: Union[str, Any]					       =					initializer_factor
      a						: Dict					       =					layer_norm_eps
      a						: List[str]					       =					position_embedding_type
      a						: Any					       =					use_cache
      a						: Optional[Any]					       =					project_dim

class 							a__( lowerCamelCase__     ):
    lowercase__			=   """altclip_vision_model"""







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

      a						: str					       =					hidden_size
      a						: Tuple					       =					intermediate_size
      a						: Any					       =					projection_dim
      a						: List[str]					       =					num_hidden_layers
      a						: Optional[Any]					       =					num_attention_heads
      a						: List[str]					       =					num_channels
      a						: List[str]					       =					patch_size
      a						: int					       =					image_size
      a						: Union[str, Any]					       =					initializer_range
      a						: Tuple					       =					initializer_factor
      a						: Union[str, Any]					       =					attention_dropout
      a						: List[str]					       =					layer_norm_eps
      a						: int					       =					hidden_act







    @classmethod
    def       lowercase_	(				cls			:  int						,      __snake_case			:  Union[str, os.PathLike]						,      **__snake_case			:  Dict     ):
      cls._set_token_in_kwargs(__snake_case     )

      a						: Optional[Any]					       =					cls.get_config_dict(__snake_case						,      **__snake_case     )

      # get the vision config dict if we are loading from AltCLIPConfig
      if config_dict.get('model_type'     ) == "altclip":
        a						: int					       =					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__( lowerCamelCase__     ):
    lowercase__			=   """altclip"""
    lowercase__			=   True







    def __init__(				self			:  str						,      __snake_case			:  Optional[int]=None						,      __snake_case			:  Optional[int]=None						,      __snake_case			:  Tuple=7_68						,      __snake_case			:  Any=2.6592						,      **__snake_case			:  List[Any]     ):
      # 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						: Optional[int]					       =					kwargs.pop('text_config_dict'						,      __snake_case     )
      a						: Dict					       =					kwargs.pop('vision_config_dict'						,      __snake_case     )

      super().__init__(**__snake_case     )

      # 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						: List[Any]					       =					{}

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

            # 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						: Optional[int]					       =					{}

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

            # 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						: List[Any]					       =					{}
        logger.info('`text_config` is `None`. Initializing the `AltCLIPTextConfig` with default values.'     )

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

      a						: Any					       =					AltCLIPTextConfig(**__snake_case     )
      a						: List[Any]					       =					AltCLIPVisionConfig(**__snake_case     )

      a						: str					       =					projection_dim
      a						: int					       =					logit_scale_init_value
      a						: Optional[Any]					       =					1.0







    @classmethod
    def       lowercase_	(				cls			:  Any						,      __snake_case			:  AltCLIPTextConfig						,      __snake_case			:  AltCLIPVisionConfig						,      **__snake_case			:  str     ):
      return cls(text_config=text_config.to_dict()						,      vision_config=vision_config.to_dict()						,      **__snake_case     )







    def       lowercase_	(				self			:  Optional[Any]     ):
      a						: Dict					       =					copy.deepcopy(self.__dict__     )
      a						: Union[str, Any]					       =					self.text_config.to_dict()
      a						: Union[str, Any]					       =					self.vision_config.to_dict()
      a						: Union[str, Any]					       =					self.__class__.model_type
      return output




'''simple docstring'''






lowerCAmelCase: Union[str, Any]							=						{
    'meter': 'm',
    'kilometer': 'km',
    'megametre': 'Mm',
    'gigametre': 'Gm',
    'terametre': 'Tm',
    'petametre': 'Pm',
    'exametre': 'Em',
    'zettametre': 'Zm',
    'yottametre': 'Ym',
}
# Exponent of the factor(meter)
lowerCAmelCase: Optional[Any]							=						{
    'm': 0,
    'km': 3,
    'Mm': 6,
    'Gm': 9,
    'Tm': 1_2,
    'Pm': 1_5,
    'Em': 1_8,
    'Zm': 2_1,
    'Ym': 2_4,
}
def 				lowerCamelCase__	(						_A			,      _A			,      _A    ):
  a						: Optional[int]					       =					from_type.lower().strip('s'    )
  a						: Optional[Any]					       =					to_type.lower().strip('s'    )

  a						: Dict					       =					UNIT_SYMBOL.get(_A			,      _A    )
  a						: Optional[Any]					       =					UNIT_SYMBOL.get(_A			,      _A    )

  if from_sanitized not in METRIC_CONVERSION:
    a						: Optional[Any]					       =					(
        f"""Invalid 'from_type' value: {from_type!r}.\n"""
        f"""Conversion abbreviations are: {", ".join(_A    )}"""
    )
    raise ValueError(_A    )
  if to_sanitized not in METRIC_CONVERSION:
    a						: Union[str, Any]					       =					(
        f"""Invalid 'to_type' value: {to_type!r}.\n"""
        f"""Conversion abbreviations are: {", ".join(_A    )}"""
    )
    raise ValueError(_A    )
  a						: List[Any]					       =					METRIC_CONVERSION[from_sanitized]
  a						: int					       =					METRIC_CONVERSION[to_sanitized]
  a						: Tuple					       =					1

  if from_exponent > to_exponent:
    a						: Optional[int]					       =					from_exponent - to_exponent
  else:
    a						: Optional[Any]					       =					-(to_exponent - from_exponent)

  return value * pow(10			,      _A    )


if __name__ == "__main__":
     from doctest import testmod

     testmod()