CoolFace
Apppublic

Aluode/PerceptionLabPortable

sourceHugging Faceupdated 9mo agoView on Hugging Face
0likes
configuration_chinese_clip.py424 linesDownload Raw Back to chinese_clip
1# coding=utf-82# Copyright 2022 The OFA-Sys Team Authors and The HuggingFace Team. All rights reserved.3#4# Licensed under the Apache License, Version 2.0 (the "License");5# you may not use this file except in compliance with the License.6# You may obtain a copy of the License at7#8#     http://www.apache.org/licenses/LICENSE-2.09#10# Unless required by applicable law or agreed to in writing, software11# distributed under the License is distributed on an "AS IS" BASIS,12# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.13# See the License for the specific language governing permissions and14# limitations under the License.15"""Chinese-CLIP model configuration"""16 17from collections import OrderedDict18from collections.abc import Mapping19from typing import TYPE_CHECKING, Any, Optional20 21 22if TYPE_CHECKING:23    from ...processing_utils import ProcessorMixin24    from ...utils import TensorType25 26from ...configuration_utils import PretrainedConfig27from ...onnx import OnnxConfig28from ...utils import logging29 30 31logger = logging.get_logger(__name__)32 33 34class ChineseCLIPTextConfig(PretrainedConfig):35    r"""36    This is the configuration class to store the configuration of a [`ChineseCLIPModel`]. It is used to instantiate a37    Chinese CLIP model according to the specified arguments, defining the model architecture. Instantiating a38    configuration with the defaults will yield a similar configuration to that of the Chinese CLIP39    [OFA-Sys/chinese-clip-vit-base-patch16](https:40        //huggingface.co/OFA-Sys/chinese-clip-vit-base-patch16) architecture.41 42    Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the43    documentation from [`PretrainedConfig`] for more information.44 45 46    Args:47        vocab_size (`int`, *optional*, defaults to 30522):48            Vocabulary size of the CHINESE_CLIP model. Defines the number of different tokens that can be represented49            by the `inputs_ids` passed when calling [`ChineseCLIPModel`].50        hidden_size (`int`, *optional*, defaults to 768):51            Dimensionality of the encoder layers and the pooler layer.52        num_hidden_layers (`int`, *optional*, defaults to 12):53            Number of hidden layers in the Transformer encoder.54        num_attention_heads (`int`, *optional*, defaults to 12):55            Number of attention heads for each attention layer in the Transformer encoder.56        intermediate_size (`int`, *optional*, defaults to 3072):57            Dimensionality of the "intermediate" (often named feed-forward) layer in the Transformer encoder.58        hidden_act (`str` or `Callable`, *optional*, defaults to `"gelu"`):59            The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,60            `"relu"`, `"silu"` and `"gelu_new"` are supported.61        hidden_dropout_prob (`float`, *optional*, defaults to 0.1):62            The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.63        attention_probs_dropout_prob (`float`, *optional*, defaults to 0.1):64            The dropout ratio for the attention probabilities.65        max_position_embeddings (`int`, *optional*, defaults to 512):66            The maximum sequence length that this model might ever be used with. Typically set this to something large67            just in case (e.g., 512 or 1024 or 2048).68        type_vocab_size (`int`, *optional*, defaults to 2):69            The vocabulary size of the `token_type_ids` passed when calling [`ChineseCLIPModel`].70        initializer_range (`float`, *optional*, defaults to 0.02):71            The standard deviation of the truncated_normal_initializer for initializing all weight matrices.72        initializer_factor (`float`, *optional*, defaults to 1.0):73            A factor for initializing all weight matrices (should be kept to 1, used internally for initialization74            testing).75        layer_norm_eps (`float`, *optional*, defaults to 1e-12):76            The epsilon used by the layer normalization layers.77        pad_token_id (`int`, *optional*, defaults to 0):78            Padding token id.79        position_embedding_type (`str`, *optional*, defaults to `"absolute"`):80            Type of position embedding. Choose one of `"absolute"`, `"relative_key"`, `"relative_key_query"`. For81            positional embeddings use `"absolute"`. For more information on `"relative_key"`, please refer to82            [Self-Attention with Relative Position Representations (Shaw et al.)](https://huggingface.co/papers/1803.02155).83            For more information on `"relative_key_query"`, please refer to *Method 4* in [Improve Transformer Models84            with Better Relative Position Embeddings (Huang et al.)](https://huggingface.co/papers/2009.13658).85        use_cache (`bool`, *optional*, defaults to `True`):86            Whether or not the model should return the last key/values attentions (not used by all models). Only87            relevant if `config.is_decoder=True`.88 89    Example:90 91    ```python92    >>> from transformers import ChineseCLIPTextConfig, ChineseCLIPTextModel93 94    >>> # Initializing a ChineseCLIPTextConfig with OFA-Sys/chinese-clip-vit-base-patch16 style configuration95    >>> configuration = ChineseCLIPTextConfig()96 97    >>> # Initializing a ChineseCLIPTextModel (with random weights) from the OFA-Sys/chinese-clip-vit-base-patch16 style configuration98    >>> model = ChineseCLIPTextModel(configuration)99 100    >>> # Accessing the model configuration101    >>> configuration = model.config102    ```"""103 104    model_type = "chinese_clip_text_model"105    base_config_key = "text_config"106 107    def __init__(108        self,109        vocab_size=30522,110        hidden_size=768,111        num_hidden_layers=12,112        num_attention_heads=12,113        intermediate_size=3072,114        hidden_act="gelu",115        hidden_dropout_prob=0.1,116        attention_probs_dropout_prob=0.1,117        max_position_embeddings=512,118        type_vocab_size=2,119        initializer_range=0.02,120        initializer_factor=1.0,121        layer_norm_eps=1e-12,122        pad_token_id=0,123        position_embedding_type="absolute",124        use_cache=True,125        **kwargs,126    ):127        super().__init__(pad_token_id=pad_token_id, **kwargs)128 129        self.vocab_size = vocab_size130        self.hidden_size = hidden_size131        self.num_hidden_layers = num_hidden_layers132        self.num_attention_heads = num_attention_heads133        self.hidden_act = hidden_act134        self.intermediate_size = intermediate_size135        self.hidden_dropout_prob = hidden_dropout_prob136        self.attention_probs_dropout_prob = attention_probs_dropout_prob137        self.max_position_embeddings = max_position_embeddings138        self.type_vocab_size = type_vocab_size139        self.initializer_range = initializer_range140        self.initializer_factor = initializer_factor141        self.layer_norm_eps = layer_norm_eps142        self.position_embedding_type = position_embedding_type143        self.use_cache = use_cache144 145 146class ChineseCLIPVisionConfig(PretrainedConfig):147    r"""148    This is the configuration class to store the configuration of a [`ChineseCLIPModel`]. It is used to instantiate an149    ChineseCLIP model according to the specified arguments, defining the model architecture. Instantiating a150    configuration with the defaults will yield a similar configuration to that of the ChineseCLIP151    [OFA-Sys/chinese-clip-vit-base-patch16](https://huggingface.co/OFA-Sys/chinese-clip-vit-base-patch16) architecture.152 153    Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the154    documentation from [`PretrainedConfig`] for more information.155 156 157    Args:158        hidden_size (`int`, *optional*, defaults to 768):159            Dimensionality of the encoder layers and the pooler layer.160        intermediate_size (`int`, *optional*, defaults to 3072):161            Dimensionality of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder.162        projection_dim (`int`, *optional*, defaults to 512):163            Dimensionality of text and vision projection layers.164        num_hidden_layers (`int`, *optional*, defaults to 12):165            Number of hidden layers in the Transformer encoder.166        num_attention_heads (`int`, *optional*, defaults to 12):167            Number of attention heads for each attention layer in the Transformer encoder.168        num_channels (`int`, *optional*, defaults to 3):169            The number of input channels.170        image_size (`int`, *optional*, defaults to 224):171            The size (resolution) of each image.172        patch_size (`int`, *optional*, defaults to 32):173            The size (resolution) of each patch.174        hidden_act (`str` or `function`, *optional*, defaults to `"quick_gelu"`):175            The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,176            `"relu"`, `"selu"` and `"gelu_new"` `"quick_gelu"` are supported.177        layer_norm_eps (`float`, *optional*, defaults to 1e-05):178            The epsilon used by the layer normalization layers.179        attention_dropout (`float`, *optional*, defaults to 0.0):180            The dropout ratio for the attention probabilities.181        initializer_range (`float`, *optional*, defaults to 0.02):182            The standard deviation of the truncated_normal_initializer for initializing all weight matrices.183        initializer_factor (`float`, *optional*, defaults to 1.0):184            A factor for initializing all weight matrices (should be kept to 1, used internally for initialization185            testing).186    Example:187    ```python188    >>> from transformers import ChineseCLIPVisionConfig, ChineseCLIPVisionModel189 190    >>> # Initializing a ChineseCLIPVisionConfig with OFA-Sys/chinese-clip-vit-base-patch16 style configuration191    >>> configuration = ChineseCLIPVisionConfig()192 193    >>> # Initializing a ChineseCLIPVisionModel (with random weights) from the OFA-Sys/chinese-clip-vit-base-patch16 style configuration194    >>> model = ChineseCLIPVisionModel(configuration)195 196    >>> # Accessing the model configuration197    >>> configuration = model.config198    ```"""199 200    model_type = "chinese_clip_vision_model"201    base_config_key = "vision_config"202 203    def __init__(204        self,205        hidden_size=768,206        intermediate_size=3072,207        projection_dim=512,208        num_hidden_layers=12,209        num_attention_heads=12,210        num_channels=3,211        image_size=224,212        patch_size=32,213        hidden_act="quick_gelu",214        layer_norm_eps=1e-5,215        attention_dropout=0.0,216        initializer_range=0.02,217        initializer_factor=1.0,218        **kwargs,219    ):220        super().__init__(**kwargs)221 222        self.hidden_size = hidden_size223        self.intermediate_size = intermediate_size224        self.projection_dim = projection_dim225        self.num_hidden_layers = num_hidden_layers226        self.num_attention_heads = num_attention_heads227        self.num_channels = num_channels228        self.patch_size = patch_size229        self.image_size = image_size230        self.initializer_range = initializer_range231        self.initializer_factor = initializer_factor232        self.attention_dropout = attention_dropout233        self.layer_norm_eps = layer_norm_eps234        self.hidden_act = hidden_act235 236 237class ChineseCLIPConfig(PretrainedConfig):238    r"""239    [`ChineseCLIPConfig`] is the configuration class to store the configuration of a [`ChineseCLIPModel`]. It is used240    to instantiate Chinese-CLIP model according to the specified arguments, defining the text model and vision model241    configs. Instantiating a configuration with the defaults will yield a similar configuration to that of the242    Chinese-CLIP [OFA-Sys/chinese-clip-vit-base-patch16](https://huggingface.co/OFA-Sys/chinese-clip-vit-base-patch16)243    architecture.244 245    Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the246    documentation from [`PretrainedConfig`] for more information.247 248    Args:249        text_config (`dict`, *optional*):250            Dictionary of configuration options used to initialize [`ChineseCLIPTextConfig`].251        vision_config (`dict`, *optional*):252            Dictionary of configuration options used to initialize [`ChineseCLIPVisionConfig`].253        projection_dim (`int`, *optional*, defaults to 512):254            Dimensionality of text and vision projection layers.255        logit_scale_init_value (`float`, *optional*, defaults to 2.6592):256            The initial value of the *logit_scale* parameter. Default is used as per the original ChineseCLIP257            implementation.258        kwargs (*optional*):259            Dictionary of keyword arguments.260 261    Example:262 263    ```python264    >>> from transformers import ChineseCLIPConfig, ChineseCLIPModel265 266    >>> # Initializing a ChineseCLIPConfig with OFA-Sys/chinese-clip-vit-base-patch16 style configuration267    >>> configuration = ChineseCLIPConfig()268 269    >>> # Initializing a ChineseCLIPModel (with random weights) from the OFA-Sys/chinese-clip-vit-base-patch16 style configuration270    >>> model = ChineseCLIPModel(configuration)271 272    >>> # Accessing the model configuration273    >>> configuration = model.config274 275    >>> # We can also initialize a ChineseCLIPConfig from a ChineseCLIPTextConfig and a ChineseCLIPVisionConfig276 277    >>> # Initializing a ChineseCLIPTextConfig and ChineseCLIPVisionConfig configuration278    >>> config_text = ChineseCLIPTextConfig()279    >>> config_vision = ChineseCLIPVisionConfig()280 281    >>> config = ChineseCLIPConfig.from_text_vision_configs(config_text, config_vision)282    ```"""283 284    model_type = "chinese_clip"285    sub_configs = {"text_config": ChineseCLIPTextConfig, "vision_config": ChineseCLIPVisionConfig}286 287    def __init__(288        self, text_config=None, vision_config=None, projection_dim=512, logit_scale_init_value=2.6592, **kwargs289    ):290        # If `_config_dict` exist, we use them for the backward compatibility.291        # We pop out these 2 attributes before calling `super().__init__` to avoid them being saved (which causes a lot292        # of confusion!).293        text_config_dict = kwargs.pop("text_config_dict", None)294        vision_config_dict = kwargs.pop("vision_config_dict", None)295 296        super().__init__(**kwargs)297 298        # Instead of simply assigning `[text|vision]_config_dict` to `[text|vision]_config`, we use the values in299        # `[text|vision]_config_dict` to update the values in `[text|vision]_config`. The values should be same in most300        # cases, but we don't want to break anything regarding `_config_dict` that existed before commit `8827e1b2`.301        if text_config_dict is not None:302            if text_config is None:303                text_config = {}304 305            # This is the complete result when using `text_config_dict`.306            _text_config_dict = ChineseCLIPTextConfig(**text_config_dict).to_dict()307 308            # Give a warning if the values exist in both `_text_config_dict` and `text_config` but being different.309            for key, value in _text_config_dict.items():310                if key in text_config and value != text_config[key] and key != "transformers_version":311                    # If specified in `text_config_dict`312                    if key in text_config_dict:313                        message = (314                            f"`{key}` is found in both `text_config_dict` and `text_config` but with different values. "315                            f'The value `text_config_dict["{key}"]` will be used instead.'316                        )317                    # If inferred from default argument values (just to be super careful)318                    else:319                        message = (320                            f"`text_config_dict` is provided which will be used to initialize `ChineseCLIPTextConfig`. "321                            f'The value `text_config["{key}"]` will be overridden.'322                        )323                    logger.info(message)324 325            # Update all values in `text_config` with the ones in `_text_config_dict`.326            text_config.update(_text_config_dict)327 328        if vision_config_dict is not None:329            if vision_config is None:330                vision_config = {}331 332            # This is the complete result when using `vision_config_dict`.333            _vision_config_dict = ChineseCLIPVisionConfig(**vision_config_dict).to_dict()334            # convert keys to string instead of integer335            if "id2label" in _vision_config_dict:336                _vision_config_dict["id2label"] = {337                    str(key): value for key, value in _vision_config_dict["id2label"].items()338                }339 340            # Give a warning if the values exist in both `_vision_config_dict` and `vision_config` but being different.341            for key, value in _vision_config_dict.items():342                if key in vision_config and value != vision_config[key] and key != "transformers_version":343                    # If specified in `vision_config_dict`344                    if key in vision_config_dict:345                        message = (346                            f"`{key}` is found in both `vision_config_dict` and `vision_config` but with different "347                            f'values. The value `vision_config_dict["{key}"]` will be used instead.'348                        )349                    # If inferred from default argument values (just to be super careful)350                    else:351                        message = (352                            f"`vision_config_dict` is provided which will be used to initialize "353                            f'`ChineseCLIPVisionConfig`. The value `vision_config["{key}"]` will be overridden.'354                        )355                    logger.info(message)356 357            # Update all values in `vision_config` with the ones in `_vision_config_dict`.358            vision_config.update(_vision_config_dict)359 360        if text_config is None:361            text_config = {}362            logger.info("`text_config` is `None`. Initializing the `ChineseCLIPTextConfig` with default values.")363 364        if vision_config is None:365            vision_config = {}366            logger.info("`vision_config` is `None`. initializing the `ChineseCLIPVisionConfig` with default values.")367 368        self.text_config = ChineseCLIPTextConfig(**text_config)369        self.vision_config = ChineseCLIPVisionConfig(**vision_config)370 371        self.projection_dim = projection_dim372        self.logit_scale_init_value = logit_scale_init_value373        self.initializer_factor = 1.0374        self.initializer_range = 0.02375 376 377class ChineseCLIPOnnxConfig(OnnxConfig):378    @property379    def inputs(self) -> Mapping[str, Mapping[int, str]]:380        return OrderedDict(381            [382                ("input_ids", {0: "batch", 1: "sequence"}),383                ("pixel_values", {0: "batch", 1: "num_channels", 2: "height", 3: "width"}),384                ("attention_mask", {0: "batch", 1: "sequence"}),385            ]386        )387 388    @property389    def outputs(self) -> Mapping[str, Mapping[int, str]]:390        return OrderedDict(391            [392                ("logits_per_image", {0: "batch"}),393                ("logits_per_text", {0: "batch"}),394                ("text_embeds", {0: "batch"}),395                ("image_embeds", {0: "batch"}),396            ]397        )398 399    @property400    def atol_for_validation(self) -> float:401        return 1e-4402 403    def generate_dummy_inputs(404        self,405        processor: "ProcessorMixin",406        batch_size: int = -1,407        seq_length: int = -1,408        framework: Optional["TensorType"] = None,409    ) -> Mapping[str, Any]:410        text_input_dict = super().generate_dummy_inputs(411            processor.tokenizer, batch_size=batch_size, seq_length=seq_length, framework=framework412        )413        image_input_dict = super().generate_dummy_inputs(414            processor.image_processor, batch_size=batch_size, framework=framework415        )416        return {**text_input_dict, **image_input_dict}417 418    @property419    def default_onnx_opset(self) -> int:420        return 14421 422 423__all__ = ["ChineseCLIPConfig", "ChineseCLIPOnnxConfig", "ChineseCLIPTextConfig", "ChineseCLIPVisionConfig"]424 
Aluode/PerceptionLabPortable · CoolFace