codingutf8 2023 the huggingface inc team licensed under the apache license version 2 0 the license you may not use this file except in compliance with the license you may obtain a copy of the license at http www apache orglicenseslicense2 0 unless required by applicable law or agreed to in writing software distributed under the license is distributed on an as is basis without warranties or conditions of any kind either express or implied see the license for the specific language governing permissions and limitations under the license owlv2 model configuration import os from typing import typechecking dict union if typechecking pass from configurationutils import pretrainedconfig from utils import logging logger logging getloggername owlv2pretrainedconfigarchivemap googleowlv2basepatch16 https huggingface cogoogleowlv2basepatch16resolvemainconfig json copied from transformers models owlvit configurationowlvit owlvittextconfig with owlvitowlv2 owlvitbasepatch32owlv2basepatch16 owlvitowlv2 owlvitowlv2 class owlv2textconfigpretrainedconfig r this is the configuration class to store the configuration of an owlv2textmodel it is used to instantiate an owlv2 text encoder according to the specified arguments defining the model architecture instantiating a configuration with the defaults will yield a similar configuration to that of the owlv2 googleowlv2basepatch16https huggingface cogoogleowlv2basepatch16 architecture configuration objects inherit from pretrainedconfig and can be used to control the model outputs read the documentation from pretrainedconfig for more information args vocabsize int optional defaults to 49408 vocabulary size of the owlv2 text model defines the number of different tokens that can be represented by the inputsids passed when calling owlv2textmodel hiddensize int optional defaults to 512 dimensionality of the encoder layers and the pooler layer intermediatesize int optional defaults to 2048 dimensionality of the intermediate i e feedforward layer in the transformer encoder numhiddenlayers int optional defaults to 12 number of hidden layers in the transformer encoder numattentionheads int optional defaults to 8 number of attention heads for each attention layer in the transformer encoder maxpositionembeddings int optional defaults to 16 the maximum sequence length that this model might ever be used with typically set this to something large just in case e g 512 or 1024 or 2048 hiddenact str or function optional defaults to quickgelu the nonlinear activation function function or string in the encoder and pooler if string gelu relu selu and gelunew quickgelu are supported layernormeps float optional defaults to 1e05 the epsilon used by the layer normalization layers attentiondropout float optional defaults to 0 0 the dropout ratio for the attention probabilities initializerrange float optional defaults to 0 02 the standard deviation of the truncatednormalinitializer for initializing all weight matrices initializerfactor float optional defaults to 1 0 a factor for initializing all weight matrices should be kept to 1 used internally for initialization testing padtokenid int optional defaults to 0 the id of the padding token in the input sequences bostokenid int optional defaults to 49406 the id of the beginningofsequence token in the input sequences eostokenid int optional defaults to 49407 the id of the endofsequence token in the input sequences example python from transformers import owlv2textconfig owlv2textmodel initializing a owlv2textmodel with googleowlv2basepatch16 style configuration configuration owlv2textconfig initializing a owlv2textconfig from the googleowlv2basepatch16 style configuration model owlv2textmodelconfiguration accessing the model configuration configuration model config modeltype owlv2textmodel def init self vocabsize49408 hiddensize512 intermediatesize2048 numhiddenlayers12 numattentionheads8 maxpositionembeddings16 hiddenactquickgelu layernormeps1e5 attentiondropout0 0 initializerrange0 02 initializerfactor1 0 padtokenid0 bostokenid49406 eostokenid49407 kwargs super initpadtokenidpadtokenid bostokenidbostokenid eostokenideostokenid kwargs self vocabsize vocabsize self hiddensize hiddensize self intermediatesize intermediatesize self numhiddenlayers numhiddenlayers self numattentionheads numattentionheads self maxpositionembeddings maxpositionembeddings self hiddenact hiddenact self layernormeps layernormeps self attentiondropout attentiondropout self initializerrange initializerrange self initializerfactor initializerfactor classmethod def frompretrainedcls pretrainedmodelnameorpath unionstr os pathlike kwargs pretrainedconfig cls settokeninkwargskwargs configdict kwargs cls getconfigdictpretrainedmodelnameorpath kwargs get the text config dict if we are loading from owlv2config if configdict getmodeltype owlv2 configdict configdicttextconfig if modeltype in configdict and hasattrcls modeltype and configdictmodeltype cls modeltype logger warning fyou are using a model of type configdict modeltype to instantiate a model of type fcls modeltype this is not supported for all configurations of models and can yield errors return cls fromdictconfigdict kwargs copied from transformers models owlvit configurationowlvit owlvitvisionconfig with owlvitowlv2 owlvitbasepatch32owlv2basepatch16 owlvitowlv2 owlvitowlv2 3216 class owlv2visionconfigpretrainedconfig r this is the configuration class to store the configuration of an owlv2visionmodel it is used to instantiate an owlv2 image encoder according to the specified arguments defining the model architecture instantiating a configuration with the defaults will yield a similar configuration to that of the owlv2 googleowlv2basepatch16https huggingface cogoogleowlv2basepatch16 architecture configuration objects inherit from pretrainedconfig and can be used to control the model outputs read the documentation from pretrainedconfig for more information args hiddensize int optional defaults to 768 dimensionality of the encoder layers and the pooler layer intermediatesize int optional defaults to 3072 dimensionality of the intermediate i e feedforward layer in the transformer encoder numhiddenlayers int optional defaults to 12 number of hidden layers in the transformer encoder numattentionheads int optional defaults to 12 number of attention heads for each attention layer in the transformer encoder numchannels int optional defaults to 3 number of channels in the input images imagesize int optional defaults to 768 the size resolution of each image patchsize int optional defaults to 16 the size resolution of each patch hiddenact str or function optional defaults to quickgelu the nonlinear activation function function or string in the encoder and pooler if string gelu relu selu and gelunew quickgelu are supported layernormeps float optional defaults to 1e05 the epsilon used by the layer normalization layers attentiondropout float optional defaults to 0 0 the dropout ratio for the attention probabilities initializerrange float optional defaults to 0 02 the standard deviation of the truncatednormalinitializer for initializing all weight matrices initializerfactor float optional defaults to 1 0 a factor for initializing all weight matrices should be kept to 1 used internally for initialization testing example python from transformers import owlv2visionconfig owlv2visionmodel initializing a owlv2visionmodel with googleowlv2basepatch16 style configuration configuration owlv2visionconfig initializing a owlv2visionmodel model from the googleowlv2basepatch16 style configuration model owlv2visionmodelconfiguration accessing the model configuration configuration model config modeltype owlv2visionmodel def init self hiddensize768 intermediatesize3072 numhiddenlayers12 numattentionheads12 numchannels3 imagesize768 patchsize16 hiddenactquickgelu layernormeps1e5 attentiondropout0 0 initializerrange0 02 initializerfactor1 0 kwargs super initkwargs self hiddensize hiddensize self intermediatesize intermediatesize self numhiddenlayers numhiddenlayers self numattentionheads numattentionheads self numchannels numchannels self imagesize imagesize self patchsize patchsize self hiddenact hiddenact self layernormeps layernormeps self attentiondropout attentiondropout self initializerrange initializerrange self initializerfactor initializerfactor classmethod def frompretrainedcls pretrainedmodelnameorpath unionstr os pathlike kwargs pretrainedconfig cls settokeninkwargskwargs configdict kwargs cls getconfigdictpretrainedmodelnameorpath kwargs get the vision config dict if we are loading from owlv2config if configdict getmodeltype owlv2 configdict configdictvisionconfig if modeltype in configdict and hasattrcls modeltype and configdictmodeltype cls modeltype logger warning fyou are using a model of type configdict modeltype to instantiate a model of type fcls modeltype this is not supported for all configurations of models and can yield errors return cls fromdictconfigdict kwargs copied from transformers models owlvit configurationowlvit owlvitconfig with owlvitowlv2 owlvitbasepatch32owlv2basepatch16 owlvitowlv2 owlvitowlv2 class owlv2configpretrainedconfig r owlv2config is the configuration class to store the configuration of an owlv2model it is used to instantiate an owlv2 model according to the specified arguments defining the text model and vision model configs instantiating a configuration with the defaults will yield a similar configuration to that of the owlv2 googleowlv2basepatch16https huggingface cogoogleowlv2basepatch16 architecture configuration objects inherit from pretrainedconfig and can be used to control the model outputs read the documentation from pretrainedconfig for more information args textconfig dict optional dictionary of configuration options used to initialize owlv2textconfig visionconfig dict optional dictionary of configuration options used to initialize owlv2visionconfig projectiondim int optional defaults to 512 dimensionality of text and vision projection layers logitscaleinitvalue float optional defaults to 2 6592 the inital value of the logitscale parameter default is used as per the original owlv2 implementation returndict bool optional defaults to true whether or not the model should return a dictionary if false returns a tuple kwargs optional dictionary of keyword arguments configdict configdicttextconfig textconfig configdictvisionconfig visionconfig return cls fromdictconfigdict kwargs coding utf 8 2023 the huggingface inc team licensed under the apache license version 2 0 the license you may not use this file except in compliance with the license you may obtain a copy of the license at http www apache org licenses license 2 0 unless required by applicable law or agreed to in writing software distributed under the license is distributed on an as is basis without warranties or conditions of any kind either express or implied see the license for the specific language governing permissions and limitations under the license owlv2 model configuration copied from transformers models owlvit configuration_owlvit owlvittextconfig with owlvit owlv2 owlvit base patch32 owlv2 base patch16 owlvit owlv2 owl vit owlv2 this is the configuration class to store the configuration of an owlv2textmodel it is used to instantiate an owlv2 text encoder according to the specified arguments defining the model architecture instantiating a configuration with the defaults will yield a similar configuration to that of the owlv2 google owlv2 base patch16 https huggingface co google owlv2 base patch16 architecture configuration objects inherit from pretrainedconfig and can be used to control the model outputs read the documentation from pretrainedconfig for more information args vocab_size int optional defaults to 49408 vocabulary size of the owlv2 text model defines the number of different tokens that can be represented by the inputs_ids passed when calling owlv2textmodel hidden_size int optional defaults to 512 dimensionality of the encoder layers and the pooler layer intermediate_size int optional defaults to 2048 dimensionality of the intermediate i e feed forward layer in the transformer encoder num_hidden_layers int optional defaults to 12 number of hidden layers in the transformer encoder num_attention_heads int optional defaults to 8 number of attention heads for each attention layer in the transformer encoder max_position_embeddings int optional defaults to 16 the maximum sequence length that this model might ever be used with typically set this to something large just in case e g 512 or 1024 or 2048 hidden_act str or function optional defaults to quick_gelu the non linear activation function function or string in the encoder and pooler if string gelu relu selu and gelu_new quick_gelu are supported layer_norm_eps float optional defaults to 1e 05 the epsilon used by the layer normalization layers attention_dropout float optional defaults to 0 0 the dropout ratio for the attention probabilities initializer_range float optional defaults to 0 02 the standard deviation of the truncated_normal_initializer for initializing all weight matrices initializer_factor float optional defaults to 1 0 a factor for initializing all weight matrices should be kept to 1 used internally for initialization testing pad_token_id int optional defaults to 0 the id of the padding token in the input sequences bos_token_id int optional defaults to 49406 the id of the beginning of sequence token in the input sequences eos_token_id int optional defaults to 49407 the id of the end of sequence token in the input sequences example python from transformers import owlv2textconfig owlv2textmodel initializing a owlv2textmodel with google owlv2 base patch16 style configuration configuration owlv2textconfig initializing a owlv2textconfig from the google owlv2 base patch16 style configuration model owlv2textmodel configuration accessing the model configuration configuration model config get the text config dict if we are loading from owlv2config copied from transformers models owlvit configuration_owlvit owlvitvisionconfig with owlvit owlv2 owlvit base patch32 owlv2 base patch16 owlvit owlv2 owl vit owlv2 32 16 this is the configuration class to store the configuration of an owlv2visionmodel it is used to instantiate an owlv2 image encoder according to the specified arguments defining the model architecture instantiating a configuration with the defaults will yield a similar configuration to that of the owlv2 google owlv2 base patch16 https huggingface co google owlv2 base patch16 architecture configuration objects inherit from pretrainedconfig and can be used to control the model outputs read the documentation from pretrainedconfig for more information args hidden_size int optional defaults to 768 dimensionality of the encoder layers and the pooler layer intermediate_size int optional defaults to 3072 dimensionality of the intermediate i e feed forward layer in the transformer encoder num_hidden_layers int optional defaults to 12 number of hidden layers in the transformer encoder num_attention_heads int optional defaults to 12 number of attention heads for each attention layer in the transformer encoder num_channels int optional defaults to 3 number of channels in the input images image_size int optional defaults to 768 the size resolution of each image patch_size int optional defaults to 16 the size resolution of each patch hidden_act str or function optional defaults to quick_gelu the non linear activation function function or string in the encoder and pooler if string gelu relu selu and gelu_new quick_gelu are supported layer_norm_eps float optional defaults to 1e 05 the epsilon used by the layer normalization layers attention_dropout float optional defaults to 0 0 the dropout ratio for the attention probabilities initializer_range float optional defaults to 0 02 the standard deviation of the truncated_normal_initializer for initializing all weight matrices initializer_factor float optional defaults to 1 0 a factor for initializing all weight matrices should be kept to 1 used internally for initialization testing example python from transformers import owlv2visionconfig owlv2visionmodel initializing a owlv2visionmodel with google owlv2 base patch16 style configuration configuration owlv2visionconfig initializing a owlv2visionmodel model from the google owlv2 base patch16 style configuration model owlv2visionmodel configuration accessing the model configuration configuration model config get the vision config dict if we are loading from owlv2config copied from transformers models owlvit configuration_owlvit owlvitconfig with owlvit owlv2 owlvit base patch32 owlv2 base patch16 owlvit owlv2 owl vit owlv2 owlv2config is the configuration class to store the configuration of an owlv2model it is used to instantiate an owlv2 model according to the specified arguments defining the text model and vision model configs instantiating a configuration with the defaults will yield a similar configuration to that of the owlv2 google owlv2 base patch16 https huggingface co google owlv2 base patch16 architecture configuration objects inherit from pretrainedconfig and can be used to control the model outputs read the documentation from pretrainedconfig for more information args text_config dict optional dictionary of configuration options used to initialize owlv2textconfig vision_config dict optional dictionary of configuration options used to initialize owlv2visionconfig projection_dim int optional defaults to 512 dimensionality of text and vision projection layers logit_scale_init_value float optional defaults to 2 6592 the inital value of the logit_scale parameter default is used as per the original owlv2 implementation return_dict bool optional defaults to true whether or not the model should return a dictionary if false returns a tuple kwargs optional dictionary of keyword arguments instantiate a owlv2config or a derived class from owlv2 text model configuration and owlv2 vision model configuration returns owlv2config an instance of a configuration object
import os
from typing import TYPE_CHECKING, Dict, Union


if TYPE_CHECKING:
    pass

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


logger = logging.get_logger(__name__)

OWLV2_PRETRAINED_CONFIG_ARCHIVE_MAP = {
    "google/owlv2-base-patch16": "https://huggingface.co/google/owlv2-base-patch16/resolve/main/config.json",
}



class Owlv2TextConfig(PretrainedConfig):
    r

    model_type = "owlv2_text_model"

    def __init__(
        self,
        vocab_size=49408,
        hidden_size=512,
        intermediate_size=2048,
        num_hidden_layers=12,
        num_attention_heads=8,
        max_position_embeddings=16,
        hidden_act="quick_gelu",
        layer_norm_eps=1e-5,
        attention_dropout=0.0,
        initializer_range=0.02,
        initializer_factor=1.0,
        pad_token_id=0,
        bos_token_id=49406,
        eos_token_id=49407,
        **kwargs,
    ):
        super().__init__(pad_token_id=pad_token_id, bos_token_id=bos_token_id, eos_token_id=eos_token_id, **kwargs)

        self.vocab_size = vocab_size
        self.hidden_size = hidden_size
        self.intermediate_size = intermediate_size
        self.num_hidden_layers = num_hidden_layers
        self.num_attention_heads = num_attention_heads
        self.max_position_embeddings = max_position_embeddings
        self.hidden_act = hidden_act
        self.layer_norm_eps = layer_norm_eps
        self.attention_dropout = attention_dropout
        self.initializer_range = initializer_range
        self.initializer_factor = initializer_factor

    @classmethod
    def from_pretrained(cls, pretrained_model_name_or_path: Union[str, os.PathLike], **kwargs) -> "PretrainedConfig":
        cls._set_token_in_kwargs(kwargs)

        config_dict, kwargs = cls.get_config_dict(pretrained_model_name_or_path, **kwargs)

        
        if config_dict.get("model_type") == "owlv2":
            config_dict = config_dict["text_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(config_dict, **kwargs)



class Owlv2VisionConfig(PretrainedConfig):
    r

    model_type = "owlv2_vision_model"

    def __init__(
        self,
        hidden_size=768,
        intermediate_size=3072,
        num_hidden_layers=12,
        num_attention_heads=12,
        num_channels=3,
        image_size=768,
        patch_size=16,
        hidden_act="quick_gelu",
        layer_norm_eps=1e-5,
        attention_dropout=0.0,
        initializer_range=0.02,
        initializer_factor=1.0,
        **kwargs,
    ):
        super().__init__(**kwargs)

        self.hidden_size = hidden_size
        self.intermediate_size = intermediate_size
        self.num_hidden_layers = num_hidden_layers
        self.num_attention_heads = num_attention_heads
        self.num_channels = num_channels
        self.image_size = image_size
        self.patch_size = patch_size
        self.hidden_act = hidden_act
        self.layer_norm_eps = layer_norm_eps
        self.attention_dropout = attention_dropout
        self.initializer_range = initializer_range
        self.initializer_factor = initializer_factor

    @classmethod
    def from_pretrained(cls, pretrained_model_name_or_path: Union[str, os.PathLike], **kwargs) -> "PretrainedConfig":
        cls._set_token_in_kwargs(kwargs)

        config_dict, kwargs = cls.get_config_dict(pretrained_model_name_or_path, **kwargs)

        
        if config_dict.get("model_type") == "owlv2":
            config_dict = 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(config_dict, **kwargs)



class Owlv2Config(PretrainedConfig):
    r

    model_type = "owlv2"

    def __init__(
        self,
        text_config=None,
        vision_config=None,
        projection_dim=512,
        logit_scale_init_value=2.6592,
        return_dict=True,
        **kwargs,
    ):
        super().__init__(**kwargs)

        if text_config is None:
            text_config = {}
            logger.info("text_config is None. Initializing the Owlv2TextConfig with default values.")

        if vision_config is None:
            vision_config = {}
            logger.info("vision_config is None. initializing the Owlv2VisionConfig with default values.")

        self.text_config = Owlv2TextConfig(**text_config)
        self.vision_config = Owlv2VisionConfig(**vision_config)

        self.projection_dim = projection_dim
        self.logit_scale_init_value = logit_scale_init_value
        self.return_dict = return_dict
        self.initializer_factor = 1.0

    @classmethod
    def from_pretrained(cls, pretrained_model_name_or_path: Union[str, os.PathLike], **kwargs) -> "PretrainedConfig":
        cls._set_token_in_kwargs(kwargs)

        config_dict, kwargs = cls.get_config_dict(pretrained_model_name_or_path, **kwargs)

        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(config_dict, **kwargs)

    @classmethod
    def from_text_vision_configs(cls, text_config: Dict, vision_config: Dict, **kwargs):
        r
        config_dict = {}
        config_dict["text_config"] = text_config
        config_dict["vision_config"] = vision_config

        return cls.from_dict(config_dict, **kwargs)