codingutf8 2022 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 blip model configuration import os from typing import union from configurationutils import pretrainedconfig from utils import logging logger logging getloggername blippretrainedconfigarchivemap salesforceblipvqabase https huggingface cosalesforceblipvqabaseresolvemainconfig json salesforceblipvqacapfitlarge https huggingface cosalesforceblipvqabasecapfitresolvemainconfig json salesforceblipimagecaptioningbase https huggingface cosalesforceblipimagecaptioningbaseresolvemainconfig json salesforceblipimagecaptioninglarge https huggingface cosalesforceblipimagecaptioninglargeresolvemainconfig json salesforceblipitmbasecoco https huggingface cosalesforceblipitmbasecocoresolvemainconfig json salesforceblipitmlargecoco https huggingface cosalesforceblipitmlargecocoresolvemainconfig json salesforceblipitmbaseflikr https huggingface cosalesforceblipitmbaseflikrresolvemainconfig json salesforceblipitmlargeflikr https huggingface cosalesforceblipitmlargeflikrresolvemainconfig json class bliptextconfigpretrainedconfig r this is the configuration class to store the configuration of a bliptextmodel it is used to instantiate a blip text model according to the specified arguments defining the model architecture instantiating a configuration with the defaults will yield a similar configuration to that of the bliptext used by the base architectureshttps huggingface cosalesforceblipvqabase 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 30524 vocabulary size of the blip text model defines the number of different tokens that can be represented by the inputsids passed when calling blipmodel hiddensize int optional defaults to 768 dimensionality of the encoder layers and the pooler layer encoderhiddensize int optional defaults to 768 dimensionality of the encoder layers from the vision model 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 8 number of attention heads for each attention layer in the transformer encoder maxpositionembeddings int optional defaults to 512 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 gelu the nonlinear activation function function or string in the encoder and pooler if string gelu relu selu and gelunew gelu are supported layernormeps float optional defaults to 1e12 the epsilon used by the layer normalization layers hiddendropoutprob float optional defaults to 0 0 the dropout probability for all fully connected layers in the embeddings encoder and pooler 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 bostokenid int optional defaults to 30522 the id of the beginningofsequence token eostokenid int optional defaults to 2 the id of the endofsequence token padtokenid int optional defaults to 0 the id of the padding token septokenid int optional defaults to 102 the id of the separator token isdecoder bool optional defaults to true whether the model is used as a decoder usecache bool optional defaults to true whether or not the model should return the last keyvalues attentions not used by all models example python from transformers import bliptextconfig bliptextmodel initializing a bliptextconfig with salesforceblipvqabase style configuration configuration bliptextconfig initializing a bliptextmodel with random weights from the salesforceblipvqabase style configuration model bliptextmodelconfiguration accessing the model configuration configuration model config modeltype bliptextmodel def init self vocabsize30524 hiddensize768 encoderhiddensize768 intermediatesize3072 projectiondim768 numhiddenlayers12 numattentionheads8 maxpositionembeddings512 hiddenactgelu layernormeps1e12 hiddendropoutprob0 0 attentionprobsdropoutprob0 0 initializerrange0 02 bostokenid30522 eostokenid2 padtokenid0 septokenid102 isdecodertrue usecachetrue kwargs super init padtokenidpadtokenid bostokenidbostokenid eostokenideostokenid septokenidseptokenid kwargs self vocabsize vocabsize self hiddensize hiddensize self encoderhiddensize encoderhiddensize self intermediatesize intermediatesize self projectiondim projectiondim self hiddendropoutprob hiddendropoutprob self numhiddenlayers numhiddenlayers self numattentionheads numattentionheads self maxpositionembeddings maxpositionembeddings self layernormeps layernormeps self hiddenact hiddenact self initializerrange initializerrange self attentionprobsdropoutprob attentionprobsdropoutprob self isdecoder isdecoder self usecache usecache 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 blipconfig if configdict getmodeltype blip 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 class blipvisionconfigpretrainedconfig r this is the configuration class to store the configuration of a blipvisionmodel it is used to instantiate a blip vision model according to the specified arguments defining the model architecture instantiating a configuration defaults will yield a similar configuration to that of the blipbase salesforceblipvqabasehttps huggingface cosalesforceblipvqabase 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 imagesize int optional defaults to 384 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 gelu the nonlinear activation function function or string in the encoder and pooler if string gelu relu selu and gelunew gelu are supported layernormeps float optional defaults to 1e5 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 1e10 the standard deviation of the truncatednormalinitializer for initializing all weight matrices example python from transformers import blipvisionconfig blipvisionmodel initializing a blipvisionconfig with salesforceblipvqabase style configuration configuration blipvisionconfig initializing a blipvisionmodel with random weights from the salesforceblipvqabase style configuration model blipvisionmodelconfiguration accessing the model configuration configuration model config modeltype blipvisionmodel def init self hiddensize768 intermediatesize3072 projectiondim512 numhiddenlayers12 numattentionheads12 imagesize384 patchsize16 hiddenactgelu layernormeps1e5 attentiondropout0 0 initializerrange1e10 kwargs super initkwargs self hiddensize hiddensize self intermediatesize intermediatesize self projectiondim projectiondim self numhiddenlayers numhiddenlayers self numattentionheads numattentionheads self patchsize patchsize self imagesize imagesize self initializerrange initializerrange self attentiondropout attentiondropout self layernormeps layernormeps self hiddenact hiddenact 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 blipconfig if configdict getmodeltype blip 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 class blipconfigpretrainedconfig r blipconfig is the configuration class to store the configuration of a blipmodel it is used to instantiate a blip 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 blipbase salesforceblipvqabasehttps huggingface cosalesforceblipvqabase 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 bliptextconfig visionconfig dict optional dictionary of configuration options used to initialize blipvisionconfig projectiondim int optional defaults to 512 dimentionality of text and vision projection layers logitscaleinitvalue float optional defaults to 2 6592 the inital value of the logitscale paramter default is used as per the original blip implementation imagetexthiddensize int optional defaults to 256 dimentionality of the hidden state of the imagetext fusion layer kwargs optional dictionary of keyword arguments example python from transformers import blipconfig blipmodel initializing a blipconfig with salesforceblipvqabase style configuration configuration blipconfig initializing a blippmodel with random weights from the salesforceblipvqabase style configuration model blipmodelconfiguration accessing the model configuration configuration model config we can also initialize a blipconfig from a bliptextconfig and a blipvisionconfig initializing a bliptext and blipvision configuration configtext bliptextconfig configvision blipvisionconfig config blipconfig fromtextvisionconfigsconfigtext configvision modeltype blip def init self textconfignone visionconfignone projectiondim512 logitscaleinitvalue2 6592 imagetexthiddensize256 kwargs super initkwargs if textconfig is none textconfig logger infotextconfig is none initializing the bliptextconfig with default values if visionconfig is none visionconfig logger infovisionconfig is none initializing the blipvisionconfig with default values self textconfig bliptextconfigtextconfig self visionconfig blipvisionconfigvisionconfig self textconfig encoderhiddensize self visionconfig hiddensize self projectiondim projectiondim self logitscaleinitvalue logitscaleinitvalue self initializerfactor 1 0 self initializerrange 0 02 self imagetexthiddensize imagetexthiddensize classmethod def fromtextvisionconfigscls textconfig bliptextconfig visionconfig blipvisionconfig kwargs r instantiate a blipconfig or a derived class from blip text model configuration and blip vision model configuration returns blipconfig an instance of a configuration object coding utf 8 2022 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 blip model configuration this is the configuration class to store the configuration of a bliptextmodel it is used to instantiate a blip text model according to the specified arguments defining the model architecture instantiating a configuration with the defaults will yield a similar configuration to that of the bliptext used by the base architectures https huggingface co salesforce blip vqa base 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 30524 vocabulary size of the blip text model defines the number of different tokens that can be represented by the inputs_ids passed when calling blipmodel hidden_size int optional defaults to 768 dimensionality of the encoder layers and the pooler layer encoder_hidden_size int optional defaults to 768 dimensionality of the encoder layers from the vision model 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 8 number of attention heads for each attention layer in the transformer encoder max_position_embeddings int optional defaults to 512 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 gelu the non linear activation function function or string in the encoder and pooler if string gelu relu selu and gelu_new gelu are supported layer_norm_eps float optional defaults to 1e 12 the epsilon used by the layer normalization layers hidden_dropout_prob float optional defaults to 0 0 the dropout probability for all fully connected layers in the embeddings encoder and pooler 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 bos_token_id int optional defaults to 30522 the id of the beginning of sequence token eos_token_id int optional defaults to 2 the id of the end of sequence token pad_token_id int optional defaults to 0 the id of the padding token sep_token_id int optional defaults to 102 the id of the separator token is_decoder bool optional defaults to true whether the model is used as a decoder use_cache bool optional defaults to true whether or not the model should return the last key values attentions not used by all models example python from transformers import bliptextconfig bliptextmodel initializing a bliptextconfig with salesforce blip vqa base style configuration configuration bliptextconfig initializing a bliptextmodel with random weights from the salesforce blip vqa base style configuration model bliptextmodel configuration accessing the model configuration configuration model config get the text config dict if we are loading from blipconfig this is the configuration class to store the configuration of a blipvisionmodel it is used to instantiate a blip vision model according to the specified arguments defining the model architecture instantiating a configuration defaults will yield a similar configuration to that of the blip base salesforce blip vqa base https huggingface co salesforce blip vqa base 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 image_size int optional defaults to 384 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 gelu the non linear activation function function or string in the encoder and pooler if string gelu relu selu and gelu_new gelu are supported layer_norm_eps float optional defaults to 1e 5 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 1e 10 the standard deviation of the truncated_normal_initializer for initializing all weight matrices example python from transformers import blipvisionconfig blipvisionmodel initializing a blipvisionconfig with salesforce blip vqa base style configuration configuration blipvisionconfig initializing a blipvisionmodel with random weights from the salesforce blip vqa base style configuration model blipvisionmodel configuration accessing the model configuration configuration model config get the vision config dict if we are loading from blipconfig blipconfig is the configuration class to store the configuration of a blipmodel it is used to instantiate a blip 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 blip base salesforce blip vqa base https huggingface co salesforce blip vqa base 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 bliptextconfig vision_config dict optional dictionary of configuration options used to initialize blipvisionconfig projection_dim int optional defaults to 512 dimentionality of text and vision projection layers logit_scale_init_value float optional defaults to 2 6592 the inital value of the logit_scale paramter default is used as per the original blip implementation image_text_hidden_size int optional defaults to 256 dimentionality of the hidden state of the image text fusion layer kwargs optional dictionary of keyword arguments example python from transformers import blipconfig blipmodel initializing a blipconfig with salesforce blip vqa base style configuration configuration blipconfig initializing a blippmodel with random weights from the salesforce blip vqa base style configuration model blipmodel configuration accessing the model configuration configuration model config we can also initialize a blipconfig from a bliptextconfig and a blipvisionconfig initializing a bliptext and blipvision configuration config_text bliptextconfig config_vision blipvisionconfig config blipconfig from_text_vision_configs config_text config_vision instantiate a blipconfig or a derived class from blip text model configuration and blip vision model configuration returns blipconfig an instance of a configuration object
import os
from typing import Union

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


logger = logging.get_logger(__name__)

BLIP_PRETRAINED_CONFIG_ARCHIVE_MAP = {
    "Salesforce/blip-vqa-base": "https://huggingface.co/Salesforce/blip-vqa-base/resolve/main/config.json",
    "Salesforce/blip-vqa-capfit-large": (
        "https://huggingface.co/Salesforce/blip-vqa-base-capfit/resolve/main/config.json"
    ),
    "Salesforce/blip-image-captioning-base": (
        "https://huggingface.co/Salesforce/blip-image-captioning-base/resolve/main/config.json"
    ),
    "Salesforce/blip-image-captioning-large": (
        "https://huggingface.co/Salesforce/blip-image-captioning-large/resolve/main/config.json"
    ),
    "Salesforce/blip-itm-base-coco": "https://huggingface.co/Salesforce/blip-itm-base-coco/resolve/main/config.json",
    "Salesforce/blip-itm-large-coco": "https://huggingface.co/Salesforce/blip-itm-large-coco/resolve/main/config.json",
    "Salesforce/blip-itm-base-flikr": "https://huggingface.co/Salesforce/blip-itm-base-flikr/resolve/main/config.json",
    "Salesforce/blip-itm-large-flikr": (
        "https://huggingface.co/Salesforce/blip-itm-large-flikr/resolve/main/config.json"
    ),
}


class BlipTextConfig(PretrainedConfig):
    r

    model_type = "blip_text_model"

    def __init__(
        self,
        vocab_size=30524,
        hidden_size=768,
        encoder_hidden_size=768,
        intermediate_size=3072,
        projection_dim=768,
        num_hidden_layers=12,
        num_attention_heads=8,
        max_position_embeddings=512,
        hidden_act="gelu",
        layer_norm_eps=1e-12,
        hidden_dropout_prob=0.0,
        attention_probs_dropout_prob=0.0,
        initializer_range=0.02,
        bos_token_id=30522,
        eos_token_id=2,
        pad_token_id=0,
        sep_token_id=102,
        is_decoder=True,
        use_cache=True,
        **kwargs,
    ):
        super().__init__(
            pad_token_id=pad_token_id,
            bos_token_id=bos_token_id,
            eos_token_id=eos_token_id,
            sep_token_id=sep_token_id,
            **kwargs,
        )

        self.vocab_size = vocab_size
        self.hidden_size = hidden_size
        self.encoder_hidden_size = encoder_hidden_size
        self.intermediate_size = intermediate_size
        self.projection_dim = projection_dim
        self.hidden_dropout_prob = hidden_dropout_prob
        self.num_hidden_layers = num_hidden_layers
        self.num_attention_heads = num_attention_heads
        self.max_position_embeddings = max_position_embeddings
        self.layer_norm_eps = layer_norm_eps
        self.hidden_act = hidden_act
        self.initializer_range = initializer_range
        self.attention_probs_dropout_prob = attention_probs_dropout_prob
        self.is_decoder = is_decoder
        self.use_cache = use_cache

    @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") == "blip":
            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 BlipVisionConfig(PretrainedConfig):
    r

    model_type = "blip_vision_model"

    def __init__(
        self,
        hidden_size=768,
        intermediate_size=3072,
        projection_dim=512,
        num_hidden_layers=12,
        num_attention_heads=12,
        image_size=384,
        patch_size=16,
        hidden_act="gelu",
        layer_norm_eps=1e-5,
        attention_dropout=0.0,
        initializer_range=1e-10,
        **kwargs,
    ):
        super().__init__(**kwargs)

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

    @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") == "blip":
            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 BlipConfig(PretrainedConfig):
    r

    model_type = "blip"

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

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

        if vision_config is None:
            vision_config = {}
            logger.info("`vision_config` is `None`. Initializing the `BlipVisionConfig` with default values.")

        self.text_config = BlipTextConfig(**text_config)
        self.vision_config = BlipVisionConfig(**vision_config)

        self.text_config.encoder_hidden_size = self.vision_config.hidden_size

        self.projection_dim = projection_dim
        self.logit_scale_init_value = logit_scale_init_value
        self.initializer_factor = 1.0
        self.initializer_range = 0.02
        self.image_text_hidden_size = image_text_hidden_size

    @classmethod
    def from_text_vision_configs(cls, text_config: BlipTextConfig, vision_config: BlipVisionConfig, **kwargs):
        r

        return cls(text_config=text_config.to_dict(), vision_config=vision_config.to_dict(), **kwargs)