CoolFace
Apppublic

Aluode/PerceptionLabPortable

sourceHugging Faceupdated 9mo agoView on Hugging Face
0likes
configuration_clipseg.py385 linesDownload Raw Back to clipseg
1# coding=utf-82# Copyright 2022 The HuggingFace Inc. 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"""CLIPSeg model configuration"""16 17from ...configuration_utils import PretrainedConfig18from ...utils import logging19 20 21logger = logging.get_logger(__name__)22 23 24class CLIPSegTextConfig(PretrainedConfig):25    r"""26    This is the configuration class to store the configuration of a [`CLIPSegModel`]. It is used to instantiate an27    CLIPSeg model according to the specified arguments, defining the model architecture. Instantiating a configuration28    with the defaults will yield a similar configuration to that of the CLIPSeg29    [CIDAS/clipseg-rd64](https://huggingface.co/CIDAS/clipseg-rd64) architecture.30 31    Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the32    documentation from [`PretrainedConfig`] for more information.33 34    Args:35        vocab_size (`int`, *optional*, defaults to 49408):36            Vocabulary size of the CLIPSeg text model. Defines the number of different tokens that can be represented37            by the `inputs_ids` passed when calling [`CLIPSegModel`].38        hidden_size (`int`, *optional*, defaults to 512):39            Dimensionality of the encoder layers and the pooler layer.40        intermediate_size (`int`, *optional*, defaults to 2048):41            Dimensionality of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder.42        num_hidden_layers (`int`, *optional*, defaults to 12):43            Number of hidden layers in the Transformer encoder.44        num_attention_heads (`int`, *optional*, defaults to 8):45            Number of attention heads for each attention layer in the Transformer encoder.46        max_position_embeddings (`int`, *optional*, defaults to 77):47            The maximum sequence length that this model might ever be used with. Typically set this to something large48            just in case (e.g., 512 or 1024 or 2048).49        hidden_act (`str` or `function`, *optional*, defaults to `"quick_gelu"`):50            The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,51            `"relu"`, `"selu"` and `"gelu_new"` `"quick_gelu"` are supported.52        layer_norm_eps (`float`, *optional*, defaults to 1e-05):53            The epsilon used by the layer normalization layers.54        attention_dropout (`float`, *optional*, defaults to 0.0):55            The dropout ratio for the attention probabilities.56        initializer_range (`float`, *optional*, defaults to 0.02):57            The standard deviation of the truncated_normal_initializer for initializing all weight matrices.58        initializer_factor (`float`, *optional*, defaults to 1.0):59            A factor for initializing all weight matrices (should be kept to 1, used internally for initialization60            testing).61        pad_token_id (`int`, *optional*, defaults to 1):62            Padding token id.63        bos_token_id (`int`, *optional*, defaults to 49406):64            Beginning of stream token id.65        eos_token_id (`int`, *optional*, defaults to 49407):66            End of stream token id.67 68    Example:69 70    ```python71    >>> from transformers import CLIPSegTextConfig, CLIPSegTextModel72 73    >>> # Initializing a CLIPSegTextConfig with CIDAS/clipseg-rd64 style configuration74    >>> configuration = CLIPSegTextConfig()75 76    >>> # Initializing a CLIPSegTextModel (with random weights) from the CIDAS/clipseg-rd64 style configuration77    >>> model = CLIPSegTextModel(configuration)78 79    >>> # Accessing the model configuration80    >>> configuration = model.config81    ```"""82 83    model_type = "clipseg_text_model"84    base_config_key = "text_config"85 86    def __init__(87        self,88        vocab_size=49408,89        hidden_size=512,90        intermediate_size=2048,91        num_hidden_layers=12,92        num_attention_heads=8,93        max_position_embeddings=77,94        hidden_act="quick_gelu",95        layer_norm_eps=1e-5,96        attention_dropout=0.0,97        initializer_range=0.02,98        initializer_factor=1.0,99        pad_token_id=1,100        bos_token_id=49406,101        eos_token_id=49407,102        **kwargs,103    ):104        super().__init__(pad_token_id=pad_token_id, bos_token_id=bos_token_id, eos_token_id=eos_token_id, **kwargs)105 106        self.vocab_size = vocab_size107        self.hidden_size = hidden_size108        self.intermediate_size = intermediate_size109        self.num_hidden_layers = num_hidden_layers110        self.num_attention_heads = num_attention_heads111        self.max_position_embeddings = max_position_embeddings112        self.layer_norm_eps = layer_norm_eps113        self.hidden_act = hidden_act114        self.initializer_range = initializer_range115        self.initializer_factor = initializer_factor116        self.attention_dropout = attention_dropout117 118 119class CLIPSegVisionConfig(PretrainedConfig):120    r"""121    This is the configuration class to store the configuration of a [`CLIPSegModel`]. It is used to instantiate an122    CLIPSeg model according to the specified arguments, defining the model architecture. Instantiating a configuration123    with the defaults will yield a similar configuration to that of the CLIPSeg124    [CIDAS/clipseg-rd64](https://huggingface.co/CIDAS/clipseg-rd64) architecture.125 126    Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the127    documentation from [`PretrainedConfig`] for more information.128 129    Args:130        hidden_size (`int`, *optional*, defaults to 768):131            Dimensionality of the encoder layers and the pooler layer.132        intermediate_size (`int`, *optional*, defaults to 3072):133            Dimensionality of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder.134        num_hidden_layers (`int`, *optional*, defaults to 12):135            Number of hidden layers in the Transformer encoder.136        num_attention_heads (`int`, *optional*, defaults to 12):137            Number of attention heads for each attention layer in the Transformer encoder.138        num_channels (`int`, *optional*, defaults to 3):139            The number of input channels.140        image_size (`int`, *optional*, defaults to 224):141            The size (resolution) of each image.142        patch_size (`int`, *optional*, defaults to 32):143            The size (resolution) of each patch.144        hidden_act (`str` or `function`, *optional*, defaults to `"quick_gelu"`):145            The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,146            `"relu"`, `"selu"` and `"gelu_new"` `"quick_gelu"` are supported.147        layer_norm_eps (`float`, *optional*, defaults to 1e-05):148            The epsilon used by the layer normalization layers.149        attention_dropout (`float`, *optional*, defaults to 0.0):150            The dropout ratio for the attention probabilities.151        initializer_range (`float`, *optional*, defaults to 0.02):152            The standard deviation of the truncated_normal_initializer for initializing all weight matrices.153        initializer_factor (`float`, *optional*, defaults to 1.0):154            A factor for initializing all weight matrices (should be kept to 1, used internally for initialization155            testing).156 157    Example:158 159    ```python160    >>> from transformers import CLIPSegVisionConfig, CLIPSegVisionModel161 162    >>> # Initializing a CLIPSegVisionConfig with CIDAS/clipseg-rd64 style configuration163    >>> configuration = CLIPSegVisionConfig()164 165    >>> # Initializing a CLIPSegVisionModel (with random weights) from the CIDAS/clipseg-rd64 style configuration166    >>> model = CLIPSegVisionModel(configuration)167 168    >>> # Accessing the model configuration169    >>> configuration = model.config170    ```"""171 172    model_type = "clipseg_vision_model"173    base_config_key = "vision_config"174 175    def __init__(176        self,177        hidden_size=768,178        intermediate_size=3072,179        num_hidden_layers=12,180        num_attention_heads=12,181        num_channels=3,182        image_size=224,183        patch_size=32,184        hidden_act="quick_gelu",185        layer_norm_eps=1e-5,186        attention_dropout=0.0,187        initializer_range=0.02,188        initializer_factor=1.0,189        **kwargs,190    ):191        super().__init__(**kwargs)192 193        self.hidden_size = hidden_size194        self.intermediate_size = intermediate_size195        self.num_hidden_layers = num_hidden_layers196        self.num_attention_heads = num_attention_heads197        self.num_channels = num_channels198        self.patch_size = patch_size199        self.image_size = image_size200        self.initializer_range = initializer_range201        self.initializer_factor = initializer_factor202        self.attention_dropout = attention_dropout203        self.layer_norm_eps = layer_norm_eps204        self.hidden_act = hidden_act205 206 207class CLIPSegConfig(PretrainedConfig):208    r"""209    [`CLIPSegConfig`] is the configuration class to store the configuration of a [`CLIPSegModel`]. It is used to210    instantiate a CLIPSeg model according to the specified arguments, defining the text model and vision model configs.211    Instantiating a configuration with the defaults will yield a similar configuration to that of the CLIPSeg212    [CIDAS/clipseg-rd64](https://huggingface.co/CIDAS/clipseg-rd64) architecture.213 214    Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the215    documentation from [`PretrainedConfig`] for more information.216 217    Args:218        text_config (`dict`, *optional*):219            Dictionary of configuration options used to initialize [`CLIPSegTextConfig`].220        vision_config (`dict`, *optional*):221            Dictionary of configuration options used to initialize [`CLIPSegVisionConfig`].222        projection_dim (`int`, *optional*, defaults to 512):223            Dimensionality of text and vision projection layers.224        logit_scale_init_value (`float`, *optional*, defaults to 2.6592):225            The initial value of the *logit_scale* parameter. Default is used as per the original CLIPSeg implementation.226        extract_layers (`list[int]`, *optional*, defaults to `[3, 6, 9]`):227            Layers to extract when forwarding the query image through the frozen visual backbone of CLIP.228        reduce_dim (`int`, *optional*, defaults to 64):229            Dimensionality to reduce the CLIP vision embedding.230        decoder_num_attention_heads (`int`, *optional*, defaults to 4):231            Number of attention heads in the decoder of CLIPSeg.232        decoder_attention_dropout (`float`, *optional*, defaults to 0.0):233            The dropout ratio for the attention probabilities.234        decoder_hidden_act (`str` or `function`, *optional*, defaults to `"quick_gelu"`):235            The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,236            `"relu"`, `"selu"` and `"gelu_new"` `"quick_gelu"` are supported.237        decoder_intermediate_size (`int`, *optional*, defaults to 2048):238            Dimensionality of the "intermediate" (i.e., feed-forward) layers in the Transformer decoder.239        conditional_layer (`int`, *optional*, defaults to 0):240            The layer to use of the Transformer encoder whose activations will be combined with the condition241            embeddings using FiLM (Feature-wise Linear Modulation). If 0, the last layer is used.242        use_complex_transposed_convolution (`bool`, *optional*, defaults to `False`):243            Whether to use a more complex transposed convolution in the decoder, enabling more fine-grained244            segmentation.245        kwargs (*optional*):246            Dictionary of keyword arguments.247 248    Example:249 250    ```python251    >>> from transformers import CLIPSegConfig, CLIPSegModel252 253    >>> # Initializing a CLIPSegConfig with CIDAS/clipseg-rd64 style configuration254    >>> configuration = CLIPSegConfig()255 256    >>> # Initializing a CLIPSegModel (with random weights) from the CIDAS/clipseg-rd64 style configuration257    >>> model = CLIPSegModel(configuration)258 259    >>> # Accessing the model configuration260    >>> configuration = model.config261 262    >>> # We can also initialize a CLIPSegConfig from a CLIPSegTextConfig and a CLIPSegVisionConfig263 264    >>> # Initializing a CLIPSegText and CLIPSegVision configuration265    >>> config_text = CLIPSegTextConfig()266    >>> config_vision = CLIPSegVisionConfig()267 268    >>> config = CLIPSegConfig.from_text_vision_configs(config_text, config_vision)269    ```"""270 271    model_type = "clipseg"272    sub_configs = {"text_config": CLIPSegTextConfig, "vision_config": CLIPSegVisionConfig}273 274    def __init__(275        self,276        text_config=None,277        vision_config=None,278        projection_dim=512,279        logit_scale_init_value=2.6592,280        extract_layers=[3, 6, 9],281        reduce_dim=64,282        decoder_num_attention_heads=4,283        decoder_attention_dropout=0.0,284        decoder_hidden_act="quick_gelu",285        decoder_intermediate_size=2048,286        conditional_layer=0,287        use_complex_transposed_convolution=False,288        **kwargs,289    ):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 = CLIPSegTextConfig(**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 `CLIPSegTextConfig`. The "321                            f'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 = CLIPSegVisionConfig(**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 `CLIPSegVisionConfig`. "353                            f'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 `CLIPSegTextConfig` with default values.")363 364        if vision_config is None:365            vision_config = {}366            logger.info("`vision_config` is `None`. initializing the `CLIPSegVisionConfig` with default values.")367 368        self.text_config = CLIPSegTextConfig(**text_config)369        self.vision_config = CLIPSegVisionConfig(**vision_config)370 371        self.projection_dim = projection_dim372        self.logit_scale_init_value = logit_scale_init_value373        self.extract_layers = extract_layers374        self.reduce_dim = reduce_dim375        self.decoder_num_attention_heads = decoder_num_attention_heads376        self.decoder_attention_dropout = decoder_attention_dropout377        self.decoder_hidden_act = decoder_hidden_act378        self.decoder_intermediate_size = decoder_intermediate_size379        self.conditional_layer = conditional_layer380        self.initializer_factor = 1.0381        self.use_complex_transposed_convolution = use_complex_transposed_convolution382 383 384__all__ = ["CLIPSegConfig", "CLIPSegTextConfig", "CLIPSegVisionConfig"]385 
Aluode/PerceptionLabPortable · CoolFace