




import copy
import os
from typing import Union

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


_snake_case            = logging.get_logger(__name__)

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







class 		lowercase							(     UpperCamelCase__	):
     _a											=		"altclip_text_model"

     def __init__(						self	,  _a=25_0002	,  _a=1024	,  _a=24	,  _a=16	,  _a=4096	,  _a="gelu"	,  _a=0.1	,  _a=0.1	,  _a=514	,  _a=1	,  _a=0.02	,  _a=0.02	,  _a=1e-05	,  _a=1	,  _a=0	,  _a=2	,  _a="absolute"	,  _a=True	,  _a=768	,  **_a	,  )		->							Optional[Any]:
           super().__init__(pad_token_id=_a	,  bos_token_id=_a	,  eos_token_id=_a	,  **_a       )

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







class 		lowercase							(     UpperCamelCase__	):
     _a											=		"altclip_vision_model"

     def __init__(						self	,  _a=768	,  _a=3072	,  _a=512	,  _a=12	,  _a=12	,  _a=3	,  _a=224	,  _a=32	,  _a="quick_gelu"	,  _a=1e-5	,  _a=0.0	,  _a=0.02	,  _a=1.0	,  **_a	,  )		->							Any:
           super().__init__(**_a       )

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



     @classmethod
     def       a__			(						cls	,  _a	,  **_a       )		->							"PretrainedConfig":
           cls._set_token_in_kwargs(_a       )

           _A    ,     _A							:  int    =		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							:  str    =		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 		lowercase							(     UpperCamelCase__	):
     _a											=		"altclip"
     _a											=		True

     def __init__(						self	,  _a=None	,  _a=None	,  _a=768	,  _a=2.6592	,  **_a       )		->							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							:  Union[str, Any]    =		kwargs.pop("""text_config_dict"""	,  _a       )
           _A							:  Optional[int]    =		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							:  Optional[int]    =		{}

                 # This is the complete result when using `text_config_dict`.
                 _A							:  str    =		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							:  Dict    =		(
                                       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							:  List[str]    =		(
                                       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							:  Dict    =		{}

                 # This is the complete result when using `vision_config_dict`.
                 _A							:  Union[str, Any]    =		AltCLIPVisionConfig(**_a       ).to_dict()
                 # convert keys to string instead of integer
                 if "id2label" in _vision_config_dict:
                       _A							:  List[Any]    =		{
                           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							:  int    =		(
                                       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							:  List[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(_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							:  Any    =		{}
                 logger.info("""`text_config` is `None`. Initializing the `AltCLIPTextConfig` with default values."""       )

           if vision_config is None:
                 _A							:  List[str]    =		{}
                 logger.info("""`vision_config` is `None`. initializing the `AltCLIPVisionConfig` with default values."""       )

           _A							:  Tuple    =		AltCLIPTextConfig(**_a       )
           _A							:  List[Any]    =		AltCLIPVisionConfig(**_a       )

           _A							:  Optional[Any]    =		projection_dim
           _A							:  Tuple    =		logit_scale_init_value
           _A							:  Dict    =		1.0

     @classmethod
     def       a__			(						cls	,  _a	,  _a	,  **_a       )		->							Tuple:
           return cls(text_config=text_config.to_dict()	,  vision_config=vision_config.to_dict()	,  **_a       )



     def       a__			(						self       )		->							Tuple:
           _A							:  List[Any]    =		copy.deepcopy(self.__dict__       )
           _A							:  List[Any]    =		self.text_config.to_dict()
           _A							:  Dict    =		self.vision_config.to_dict()
           _A							:  List[Any]    =		self.__class__.model_type
           return output







from unittest import TestCase

from datasets import Sequence, Value
from datasets.arrow_dataset import Dataset







class 		lowercase							(     UpperCamelCase__	):

     def       a__			(						self       )		->							Optional[int]:
           return [
               {"col_1": 3, "col_2": "a"},
               {"col_1": 2, "col_2": "b"},
               {"col_1": 1, "col_2": "c"},
               {"col_1": 0, "col_2": "d"},
           ]

     def       a__			(						self       )		->							Optional[int]:
           _A							:  Union[str, Any]    =		{"""col_1""": [3, 2, 1, 0], """col_2""": ["""a""", """b""", """c""", """d"""]}
           return Dataset.from_dict(_a       )

     def       a__			(						self       )		->							Any:
           _A							:  str    =		self._create_example_records()
           _A							:  List[Any]    =		Dataset.from_list(_a       )
           self.assertListEqual(dset.column_names	,  ["""col_1""", """col_2"""]       )
           for i, r in enumerate(_a       ):
                 self.assertDictEqual(_a	,  example_records[i]       )

     def       a__			(						self       )		->							List[str]:
           _A							:  Dict    =		self._create_example_records()
           _A							:  List[str]    =		Dataset.from_list(_a       )
           _A							:  str    =		Dataset.from_dict({k: [r[k] for r in example_records] for k in example_records[0]}       )
           self.assertEqual(dset.info	,  dset_from_dict.info       )

     def       a__			(						self       )		->							str:  # checks what happens with missing columns
           _A							:  List[str]    =		[{"""col_1""": 1}, {"""col_2""": """x"""}]
           _A							:  List[str]    =		Dataset.from_list(_a       )
           self.assertDictEqual(dset[0]	,  {"""col_1""": 1}       )
           self.assertDictEqual(dset[1]	,  {"""col_1""": None}       )  # NB: first record is used for columns

     def       a__			(						self       )		->							Dict:  # checks if the type can be inferred from the second record
           _A							:  List[Any]    =		[{"""col_1""": []}, {"""col_1""": [1, 2]}]
           _A							:  str    =		Dataset.from_list(_a       )
           self.assertEqual(dset.info.features["""col_1"""]	,  Sequence(Value("""int64"""       )       )       )



     def       a__			(						self       )		->							Dict:
           _A							:  List[str]    =		Dataset.from_list([]       )
           self.assertEqual(len(_a       )	,  0       )
           self.assertListEqual(dset.column_names	,  []       )

