The BLIP-2 model was proposed in BLIP-2: Bootstrapping Language-Image Pre-training with Frozen Image Encoders and Large Language Models by Junnan Li, Dongxu Li, Silvio Savarese, Steven Hoi. BLIP-2 leverages frozen pre-trained image encoders and large language models (LLMs) by training a lightweight, 12-layer Transformer encoder in between them, achieving state-of-the-art performance on various vision-language tasks. Most notably, BLIP-2 improves upon Flamingo, an 80 billion parameter model, by 8.7% on zero-shot VQAv2 with 54x fewer trainable parameters.
The abstract from the paper is the following:
The cost of vision-and-language pre-training has become increasingly prohibitive due to end-to-end training of large-scale models. This paper proposes BLIP-2, a generic and efficient pre-training strategy that bootstraps vision-language pre-training from off-the-shelf frozen pre-trained image encoders and frozen large language models. BLIP-2 bridges the modality gap with a lightweight Querying Transformer, which is pre-trained in two stages. The first stage bootstraps vision-language representation learning from a frozen image encoder. The second stage bootstraps vision-to-language generative learning from a frozen language model. BLIP-2 achieves state-of-the-art performance on various vision-language tasks, despite having significantly fewer trainable parameters than existing methods. For example, our model outperforms Flamingo80B by 8.7% on zero-shot VQAv2 with 54x fewer trainable parameters. We also demonstrate the modelβs emerging capabilities of zero-shot image-to-text generation that can follow natural language instructions.
BLIP-2 architecture. Taken from the original paper.This model was contributed by nielsr. The original code can be found here.
Usage tipsgenerate
method.Resources[!NOTE] BLIP models after release v4.46 will raise warnings about adding
processor.num_query_tokens = {{num_query_tokens}}
and expand model embeddings layer to add special<image>
token. It is strongly recommended to add the attributes to the processor if you own the model checkpoint, or open a PR if it is not owned by you. Adding these attributes means that BLIP will add the number of query tokens required per image and expand the text with as many<image>
placeholders as there will be query tokens. Usually it is around 500 tokens per image, so make sure that the text is not truncated as otherwise there wil be failure when merging the embeddings. The attributes can be obtained from model config, asmodel.config.num_query_tokens
and model embeddings expansion can be done by following this link.
A list of official Hugging Face and community (indicated by π) resources to help you get started with BLIP-2.
If youβre interested in submitting a resource to be included here, please feel free to open a Pull Request and weβll review it! The resource should ideally demonstrate something new instead of duplicating an existing resource.
Blip2Config class transformers.Blip2Config < source >( vision_config = None qformer_config = None text_config = None num_query_tokens = 32 image_text_hidden_size = 256 image_token_index = None **kwargs )
Parameters
dict
, optional) β Dictionary of configuration options used to initialize Blip2VisionConfig. dict
, optional) β Dictionary of configuration options used to initialize Blip2QFormerConfig. dict
, optional) β Dictionary of configuration options used to initialize any PretrainedConfig. int
, optional, defaults to 32) β The number of query tokens passed through the Transformer. int
, optional, defaults to 256) β Dimentionality of the hidden state of the image-text fusion layer. int
, optional) β Token index of special image token. Blip2Config is the configuration class to store the configuration of a Blip2ForConditionalGeneration. It is used to instantiate a BLIP-2 model according to the specified arguments, defining the vision model, Q-Former model and language model configs. Instantiating a configuration with the defaults will yield a similar configuration to that of the BLIP-2 Salesforce/blip2-opt-2.7b architecture.
Configuration objects inherit from PretrainedConfig and can be used to control the model outputs. Read the documentation from PretrainedConfig for more information.
Example:
>>> from transformers import ( ... Blip2VisionConfig, ... Blip2QFormerConfig, ... OPTConfig, ... Blip2Config, ... Blip2ForConditionalGeneration, ... ) >>> >>> configuration = Blip2Config() >>> >>> model = Blip2ForConditionalGeneration(configuration) >>> >>> configuration = model.config >>> >>> >>> vision_config = Blip2VisionConfig() >>> qformer_config = Blip2QFormerConfig() >>> text_config = OPTConfig() >>> config = Blip2Config.from_text_vision_configs(vision_config, qformer_config, text_config)from_vision_qformer_text_configs < source >
( vision_config: Blip2VisionConfig qformer_config: Blip2QFormerConfig text_config: typing.Optional[transformers.configuration_utils.PretrainedConfig] = None **kwargs ) β Blip2Config
Parameters
dict
) β Dictionary of configuration options used to initialize Blip2VisionConfig. dict
) β Dictionary of configuration options used to initialize Blip2QFormerConfig. dict
, optional) β Dictionary of configuration options used to initialize any PretrainedConfig. An instance of a configuration object
Instantiate a Blip2Config (or a derived class) from a BLIP-2 vision model, Q-Former and language model configurations.
Blip2VisionConfig class transformers.Blip2VisionConfig < source >( hidden_size = 1408 intermediate_size = 6144 num_hidden_layers = 39 num_attention_heads = 16 image_size = 224 patch_size = 14 hidden_act = 'gelu' layer_norm_eps = 1e-06 attention_dropout = 0.0 initializer_range = 1e-10 qkv_bias = True **kwargs )
Parameters
int
, optional, defaults to 1408) β Dimensionality of the encoder layers and the pooler layer. int
, optional, defaults to 6144) β Dimensionality of the βintermediateβ (i.e., feed-forward) layer in the Transformer encoder. int
, optional, defaults to 39) β Number of hidden layers in the Transformer encoder. int
, optional, defaults to 16) β Number of attention heads for each attention layer in the Transformer encoder. int
, optional, defaults to 224) β The size (resolution) of each image. int
, optional, defaults to 14) β The size (resolution) of each patch. 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. float
, optional, defaults to 0.0) β The dropout ratio for the attention probabilities. float
, optional, defaults to 0.02) β The standard deviation of the truncated_normal_initializer for initializing all weight matrices. bool
, optional, defaults to True
) β Whether to add a bias to the queries and values in the self-attention layers. This is the configuration class to store the configuration of a Blip2VisionModel. It is used to instantiate a BLIP-2 vision encoder according to the specified arguments, defining the model architecture. Instantiating a configuration defaults will yield a similar configuration to that of the BLIP-2 Salesforce/blip2-opt-2.7b architecture.
Configuration objects inherit from PretrainedConfig and can be used to control the model outputs. Read the documentation from PretrainedConfig for more information.
Example:
>>> from transformers import Blip2VisionConfig, Blip2VisionModel >>> >>> configuration = Blip2VisionConfig() >>> >>> model = Blip2VisionModel(configuration) >>> >>> configuration = model.configBlip2QFormerConfig class transformers.Blip2QFormerConfig < source >
( vocab_size = 30522 hidden_size = 768 num_hidden_layers = 12 num_attention_heads = 12 intermediate_size = 3072 hidden_act = 'gelu' hidden_dropout_prob = 0.1 attention_probs_dropout_prob = 0.1 max_position_embeddings = 512 initializer_range = 0.02 layer_norm_eps = 1e-12 pad_token_id = 0 position_embedding_type = 'absolute' cross_attention_frequency = 2 encoder_hidden_size = 1408 use_qformer_text_input = False **kwargs )
Parameters
int
, optional, defaults to 30522) β Vocabulary size of the Q-Former model. Defines the number of different tokens that can be represented by the inputs_ids
passed when calling the model. int
, optional, defaults to 768) β Dimensionality of the encoder layers and the pooler layer. int
, optional, defaults to 12) β Number of hidden layers in the Transformer encoder. int
, optional, defaults to 12) β Number of attention heads for each attention layer in the Transformer encoder. int
, optional, defaults to 3072) β Dimensionality of the βintermediateβ (often named feed-forward) layer in the Transformer encoder. str
or Callable
, optional, defaults to "gelu"
) β The non-linear activation function (function or string) in the encoder and pooler. If string, "gelu"
, "relu"
, "silu"
and "gelu_new"
are supported. float
, optional, defaults to 0.1) β The dropout probability for all fully connected layers in the embeddings, encoder, and pooler. float
, optional, defaults to 0.1) β The dropout ratio for the attention probabilities. 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). float
, optional, defaults to 0.02) β The standard deviation of the truncated_normal_initializer for initializing all weight matrices. float
, optional, defaults to 1e-12) β The epsilon used by the layer normalization layers. str
, optional, defaults to "absolute"
) β Type of position embedding. Choose one of "absolute"
, "relative_key"
, "relative_key_query"
. For positional embeddings use "absolute"
. For more information on "relative_key"
, please refer to Self-Attention with Relative Position Representations (Shaw et al.). For more information on "relative_key_query"
, please refer to Method 4 in Improve Transformer Models with Better Relative Position Embeddings (Huang et al.). int
, optional, defaults to 2) β The frequency of adding cross-attention to the Transformer layers. int
, optional, defaults to 1408) β The hidden size of the hidden states for cross-attention. bool
, optional, defaults to False
) β Whether to use BERT-style embeddings. This is the configuration class to store the configuration of a Blip2QFormerModel. It is used to instantiate a BLIP-2 Querying Transformer (Q-Former) 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 BLIP-2 Salesforce/blip2-opt-2.7b architecture. Configuration objects inherit from PretrainedConfig and can be used to control the model outputs. Read the documentation from PretrainedConfig for more information.
Note that Blip2QFormerModel is very similar to BertLMHeadModel with interleaved cross-attention.
Examples:
>>> from transformers import Blip2QFormerConfig, Blip2QFormerModel >>> >>> configuration = Blip2QFormerConfig() >>> >>> model = Blip2QFormerModel(configuration) >>> >>> configuration = model.configBlip2Processor class transformers.Blip2Processor < source >
( image_processor tokenizer num_query_tokens = None **kwargs )
Parameters
BlipImageProcessor
) β An instance of BlipImageProcessor. The image processor is a required input. AutoTokenizer
) β An instance of [βPreTrainedTokenizer`]. The tokenizer is a required input. int
, optional) β Number of tokens used by the Qformer as queries, should be same as in modelβs config. Constructs a BLIP-2 processor which wraps a BLIP image processor and an OPT/T5 tokenizer into a single processor.
BlipProcessor offers all the functionalities of BlipImageProcessor and AutoTokenizer. See the docstring of __call__()
and decode() for more information.
This method forwards all its arguments to PreTrainedTokenizerβs batch_decode(). Please refer to the docstring of this method for more information.
This method forwards all its arguments to PreTrainedTokenizerβs decode(). Please refer to the docstring of this method for more information.
Blip2VisionModel class transformers.Blip2VisionModel < source >( config: Blip2VisionConfig )
forward < source >( pixel_values: typing.Optional[torch.FloatTensor] = None output_attentions: typing.Optional[bool] = None output_hidden_states: typing.Optional[bool] = None return_dict: typing.Optional[bool] = None interpolate_pos_encoding: bool = False ) β transformers.modeling_outputs.BaseModelOutputWithPooling or tuple(torch.FloatTensor)
Parameters
torch.FloatTensor
of shape (batch_size, num_channels, height, width)
) β Pixel values. Pixel values can be obtained using Blip2Processor. See Blip2Processor.__call__()
for details. bool
, optional) β Whether or not to return the attentions tensors of all attention layers. See attentions
under returned tensors for more detail. bool
, optional) β Whether or not to return the hidden states of all layers. See hidden_states
under returned tensors for more detail. bool
, optional) β Whether or not to return a ModelOutput instead of a plain tuple. bool
, optional, defaults to False
) β Whether to interpolate the pre-trained position encodings. A transformers.modeling_outputs.BaseModelOutputWithPooling or a tuple of torch.FloatTensor
(if return_dict=False
is passed or when config.return_dict=False
) comprising various elements depending on the configuration (<class 'transformers.models.blip_2.configuration_blip_2.Blip2VisionConfig'>
) and inputs.
last_hidden_state (torch.FloatTensor
of shape (batch_size, sequence_length, hidden_size)
) β Sequence of hidden-states at the output of the last layer of the model.
pooler_output (torch.FloatTensor
of shape (batch_size, hidden_size)
) β Last layer hidden-state of the first token of the sequence (classification token) after further processing through the layers used for the auxiliary pretraining task. E.g. for BERT-family of models, this returns the classification token after processing through a linear layer and a tanh activation function. The linear layer weights are trained from the next sentence prediction (classification) objective during pretraining.
hidden_states (tuple(torch.FloatTensor)
, optional, returned when output_hidden_states=True
is passed or when config.output_hidden_states=True
) β Tuple of torch.FloatTensor
(one for the output of the embeddings, if the model has an embedding layer, + one for the output of each layer) of shape (batch_size, sequence_length, hidden_size)
.
Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.
attentions (tuple(torch.FloatTensor)
, optional, returned when output_attentions=True
is passed or when config.output_attentions=True
) β Tuple of torch.FloatTensor
(one for each layer) of shape (batch_size, num_heads, sequence_length, sequence_length)
.
Attentions weights after the attention softmax, used to compute the weighted average in the self-attention heads.
The Blip2VisionModel forward method, overrides the __call__
special method.
Although the recipe for forward pass needs to be defined within this function, one should call the Module
instance afterwards instead of this since the former takes care of running the pre and post processing steps while the latter silently ignores them.
( config: Blip2QFormerConfig )
Querying Transformer (Q-Former), used in BLIP-2.
forward < source >( query_embeds: FloatTensor query_length: typing.Optional[int] = None attention_mask: typing.Optional[torch.FloatTensor] = None head_mask: typing.Optional[torch.FloatTensor] = None encoder_hidden_states: typing.Optional[torch.FloatTensor] = None encoder_attention_mask: typing.Optional[torch.FloatTensor] = None past_key_values: typing.Optional[typing.Tuple[typing.Tuple[torch.FloatTensor]]] = None use_cache: typing.Optional[bool] = None output_attentions: typing.Optional[bool] = None output_hidden_states: typing.Optional[bool] = None return_dict: typing.Optional[bool] = None )
encoder_hidden_states (torch.FloatTensor
of shape (batch_size, sequence_length, hidden_size)
, optional
): Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention if the model is configured as a decoder. encoder_attention_mask (torch.FloatTensor
of shape (batch_size, sequence_length)
, optional
): Mask to avoid performing attention on the padding token indices of the encoder input. This mask is used in the cross-attention if the model is configured as a decoder. Mask values selected in [0, 1]
:
tuple(tuple(torch.FloatTensor))
of length config.n_layers
with each tuple having 4 tensors of: shape (batch_size, num_heads, sequence_length - 1, embed_size_per_head)
): Contains precomputed key and value hidden states of the attention blocks. Can be used to speed up decoding. If past_key_values
are used, the user can optionally input only the last decoder_input_ids
(those that donβt have their past key value states given to this model) of shape (batch_size, 1)
instead of all decoder_input_ids
of shape (batch_size, sequence_length)
. use_cache (bool
, optional
): If set to True
, past_key_values
key value states are returned and can be used to speed up decoding (see past_key_values
).( config: Blip2Config )
Parameters
BLIP-2 Model for generating text and image features. The model consists of a vision encoder, Querying Transformer (Q-Former) and a language model.
This model inherits from PreTrainedModel. Check the superclass documentation for the generic methods the library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads etc.)
This model is also a PyTorch torch.nn.Module subclass. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and behavior.
forward < source >( pixel_values: FloatTensor input_ids: FloatTensor attention_mask: typing.Optional[torch.LongTensor] = None decoder_input_ids: typing.Optional[torch.LongTensor] = None decoder_attention_mask: typing.Optional[torch.LongTensor] = None output_attentions: typing.Optional[bool] = None output_hidden_states: typing.Optional[bool] = None labels: typing.Optional[torch.LongTensor] = None return_dict: typing.Optional[bool] = None interpolate_pos_encoding: bool = False ) β transformers.models.blip_2.modeling_blip_2.Blip2ForConditionalGenerationModelOutput
or tuple(torch.FloatTensor)
Parameters
torch.FloatTensor
of shape (batch_size, num_channels, height, width)
) β Pixel values. Pixel values can be obtained using Blip2Processor. See Blip2Processor.__call__()
for details. torch.LongTensor
of shape (batch_size, sequence_length)
, optional) β Indices of input sequence tokens in the vocabulary of the language model. Input tokens can optionally be provided to serve as text prompt, which the language model can continue.
Indices can be obtained using Blip2Processor. See Blip2Processor.__call__()
for details.
torch.Tensor
of shape (batch_size, sequence_length)
, optional) β Mask to avoid performing attention on padding token indices. Mask values selected in [0, 1]
:
torch.LongTensor
of shape (batch_size, target_sequence_length)
, optional) β Indices of decoder input sequence tokens in the vocabulary of the language model. Only relevant in case an encoder-decoder language model (like T5) is used.
Indices can be obtained using AutoTokenizer. See PreTrainedTokenizer.encode() and PreTrainedTokenizer.call() for details. What are decoder input IDs?
torch.BoolTensor
of shape (batch_size, target_sequence_length)
, optional) β Default behavior: generate a tensor that ignores pad tokens in decoder_input_ids
. Causal mask will also be used by default.
Only relevant in case an encoder-decoder language model (like T5) is used.
bool
, optional) β Whether or not to return the attentions tensors of all attention layers. See attentions
under returned tensors for more detail. bool
, optional) β Whether or not to return the hidden states of all layers. See hidden_states
under returned tensors for more detail. bool
, optional) β Whether or not to return a ModelOutput instead of a plain tuple. bool
, optional, defaults to False
) β Whether to interpolate the pre-trained position encodings. bool
, optional) β If set to True
, past_key_values
key value states are returned and can be used to speed up decoding (see past_key_values
). Returns
transformers.models.blip_2.modeling_blip_2.Blip2ForConditionalGenerationModelOutput
or tuple(torch.FloatTensor)
A transformers.models.blip_2.modeling_blip_2.Blip2ForConditionalGenerationModelOutput
or a tuple of torch.FloatTensor
(if return_dict=False
is passed or when config.return_dict=False
) comprising various elements depending on the configuration (<class 'transformers.models.blip_2.configuration_blip_2.Blip2VisionConfig'>
) and inputs.
torch.FloatTensor
, optional, returned when labels
is provided, torch.FloatTensor
of shape (1,)
) β Language modeling loss from the language model.torch.FloatTensor
of shape (batch_size, sequence_length, config.vocab_size)
) β Prediction scores of the language modeling head of the language model.BaseModelOutputWithPooling
) β Outputs of the vision encoder.BaseModelOutputWithPoolingAndCrossAttentions
) β Outputs of the Q-Former (Querying Transformer).CausalLMOutputWithPast
or Seq2SeqLMOutput
) β Outputs of the language model.The Blip2Model forward method, overrides the __call__
special method.
Although the recipe for forward pass needs to be defined within this function, one should call the Module
instance afterwards instead of this since the former takes care of running the pre and post processing steps while the latter silently ignores them.
Examples:
>>> from PIL import Image >>> import requests >>> from transformers import Blip2Processor, Blip2Model >>> import torch >>> device = "cuda" if torch.cuda.is_available() else "cpu" >>> processor = Blip2Processor.from_pretrained("Salesforce/blip2-opt-2.7b") >>> model = Blip2Model.from_pretrained("Salesforce/blip2-opt-2.7b", torch_dtype=torch.float16) >>> model.to(device) >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg" >>> image = Image.open(requests.get(url, stream=True).raw) >>> prompt = "Question: how many cats are there? Answer:" >>> inputs = processor(images=image, text=prompt, return_tensors="pt").to(device, torch.float16) >>> outputs = model(**inputs)get_text_features < source >
( input_ids: typing.Optional[torch.Tensor] = None attention_mask: typing.Optional[torch.Tensor] = None decoder_input_ids: typing.Optional[torch.Tensor] = None decoder_attention_mask: typing.Optional[torch.Tensor] = None labels: typing.Optional[torch.Tensor] = None output_attentions: typing.Optional[bool] = None output_hidden_states: typing.Optional[bool] = None return_dict: typing.Optional[bool] = None ) β text_outputs (CausalLMOutputWithPast
, or tuple(torch.FloatTensor)
if return_dict=False
)
Parameters
torch.LongTensor
of shape (batch_size, sequence_length)
) β Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide it. Indices can be obtained using AutoTokenizer. See PreTrainedTokenizer.encode() and PreTrainedTokenizer.call() for details. What are input IDs? torch.Tensor
of shape (batch_size, sequence_length)
, optional) β Mask to avoid performing attention on padding token indices. Mask values selected in [0, 1]
:
torch.LongTensor
of shape (batch_size, target_sequence_length)
, optional) β Indices of decoder input sequence tokens in the vocabulary.
Indices can be obtained using AutoTokenizer. See PreTrainedTokenizer.encode() and PreTrainedTokenizer.call() for details.
T5 uses the pad_token_id
as the starting token for decoder_input_ids
generation. If past_key_values
is used, optionally only the last decoder_input_ids
have to be input (see past_key_values
).
To know more on how to prepare decoder_input_ids
for pretraining take a look at T5 Training.
torch.BoolTensor
of shape (batch_size, target_sequence_length)
, optional) β Default behavior: generate a tensor that ignores pad tokens in decoder_input_ids
. Causal mask will also be used by default. bool
, optional) β Whether or not to return the attentions tensors of all attention layers. See attentions
under returned tensors for more detail. bool
, optional) β Whether or not to return the hidden states of all layers. See hidden_states
under returned tensors for more detail. bool
, optional) β Whether or not to return a ModelOutput instead of a plain tuple. Returns
text_outputs (CausalLMOutputWithPast
, or tuple(torch.FloatTensor)
if return_dict=False
)
The language model outputs. If return_dict=True
, the output is a CausalLMOutputWithPast
that contains the language model logits, the past key values and the hidden states if output_hidden_states=True
.
The Blip2Model forward method, overrides the __call__
special method.
Although the recipe for forward pass needs to be defined within this function, one should call the Module
instance afterwards instead of this since the former takes care of running the pre and post processing steps while the latter silently ignores them.
Examples:
>>> import torch >>> from transformers import AutoTokenizer, Blip2Model >>> model = Blip2Model.from_pretrained("Salesforce/blip2-opt-2.7b") >>> tokenizer = AutoTokenizer.from_pretrained("Salesforce/blip2-opt-2.7b") >>> inputs = tokenizer(["a photo of a cat"], padding=True, return_tensors="pt") >>> text_features = model.get_text_features(**inputs)get_image_features < source >
( pixel_values: typing.Optional[torch.FloatTensor] = None output_attentions: typing.Optional[bool] = None output_hidden_states: typing.Optional[bool] = None return_dict: typing.Optional[bool] = None interpolate_pos_encoding: bool = False ) β vision_outputs (BaseModelOutputWithPooling
or tuple of torch.FloatTensor
)
Parameters
torch.FloatTensor
of shape (batch_size, num_channels, height, width)
) β Pixel values. Pixel values can be obtained using Blip2Processor. See Blip2Processor.__call__()
for details. bool
, optional) β Whether or not to return the attentions tensors of all attention layers. See attentions
under returned tensors for more detail. bool
, optional) β Whether or not to return the hidden states of all layers. See hidden_states
under returned tensors for more detail. bool
, optional) β Whether or not to return a ModelOutput instead of a plain tuple. bool
, optional, defaults to False
) β Whether to interpolate the pre-trained position encodings. Returns
vision_outputs (BaseModelOutputWithPooling
or tuple of torch.FloatTensor
)
The vision model outputs. If return_dict=True
, the output is a BaseModelOutputWithPooling
that contains the image features, the pooled image features and the hidden states if output_hidden_states=True
.
The Blip2Model forward method, overrides the __call__
special method.
Although the recipe for forward pass needs to be defined within this function, one should call the Module
instance afterwards instead of this since the former takes care of running the pre and post processing steps while the latter silently ignores them.
Examples:
>>> import torch >>> from PIL import Image >>> import requests >>> from transformers import AutoProcessor, Blip2Model >>> model = Blip2Model.from_pretrained("Salesforce/blip2-opt-2.7b") >>> processor = AutoProcessor.from_pretrained("Salesforce/blip2-opt-2.7b") >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg" >>> image = Image.open(requests.get(url, stream=True).raw) >>> inputs = processor(images=image, return_tensors="pt") >>> image_outputs = model.get_image_features(**inputs)get_qformer_features < source >
( pixel_values: typing.Optional[torch.FloatTensor] = None output_attentions: typing.Optional[bool] = None output_hidden_states: typing.Optional[bool] = None return_dict: typing.Optional[bool] = None interpolate_pos_encoding: bool = False ) β vision_outputs (BaseModelOutputWithPooling
or tuple of torch.FloatTensor
)
Parameters
torch.FloatTensor
of shape (batch_size, num_channels, height, width)
) β Pixel values. Pixel values can be obtained using Blip2Processor. See Blip2Processor.__call__()
for details. torch.LongTensor
of shape (batch_size, sequence_length)
, optional) β Indices of input sequence tokens in the vocabulary of the language model. Input tokens can optionally be provided to serve as text prompt, which the language model can continue.
Indices can be obtained using Blip2Processor. See Blip2Processor.__call__()
for details.
torch.Tensor
of shape (batch_size, sequence_length)
, optional) β Mask to avoid performing attention on padding token indices. Mask values selected in [0, 1]
:
torch.LongTensor
of shape (batch_size, target_sequence_length)
, optional) β Indices of decoder input sequence tokens in the vocabulary of the language model. Only relevant in case an encoder-decoder language model (like T5) is used.
Indices can be obtained using AutoTokenizer. See PreTrainedTokenizer.encode() and PreTrainedTokenizer.call() for details. What are decoder input IDs?
torch.BoolTensor
of shape (batch_size, target_sequence_length)
, optional) β Default behavior: generate a tensor that ignores pad tokens in decoder_input_ids
. Causal mask will also be used by default.
Only relevant in case an encoder-decoder language model (like T5) is used.
bool
, optional) β Whether or not to return the attentions tensors of all attention layers. See attentions
under returned tensors for more detail. bool
, optional) β Whether or not to return the hidden states of all layers. See hidden_states
under returned tensors for more detail. bool
, optional) β Whether or not to return a ModelOutput instead of a plain tuple. bool
, optional, defaults to False
) β Whether to interpolate the pre-trained position encodings. bool
, optional) β If set to True
, past_key_values
key value states are returned and can be used to speed up decoding (see past_key_values
). Returns
vision_outputs (BaseModelOutputWithPooling
or tuple of torch.FloatTensor
)
The vision model outputs. If return_dict=True
, the output is a BaseModelOutputWithPooling
that contains the image features, the pooled image features and the hidden states if output_hidden_states=True
.
The Blip2Model forward method, overrides the __call__
special method.
Although the recipe for forward pass needs to be defined within this function, one should call the Module
instance afterwards instead of this since the former takes care of running the pre and post processing steps while the latter silently ignores them.
Examples:
>>> import torch >>> from PIL import Image >>> import requests >>> from transformers import Blip2Processor, Blip2Model >>> processor = Blip2Processor.from_pretrained("Salesforce/blip2-opt-2.7b") >>> model = Blip2Model.from_pretrained("Salesforce/blip2-opt-2.7b") >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg" >>> image = Image.open(requests.get(url, stream=True).raw) >>> inputs = processor(images=image, return_tensors="pt") >>> qformer_outputs = model.get_qformer_features(**inputs)Blip2ForConditionalGeneration class transformers.Blip2ForConditionalGeneration < source >
( config: Blip2Config )
Parameters
BLIP-2 Model for generating text given an image and an optional text prompt. The model consists of a vision encoder, Querying Transformer (Q-Former) and a language model.
One can optionally pass input_ids
to the model, which serve as a text prompt, to make the language model continue the prompt. Otherwise, the language model starts generating text from the [BOS] (beginning-of-sequence) token.
Note that Flan-T5 checkpoints cannot be cast to float16. They are pre-trained using bfloat16.
This model inherits from PreTrainedModel. Check the superclass documentation for the generic methods the library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads etc.)
This model is also a PyTorch torch.nn.Module subclass. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and behavior.
forward < source >( pixel_values: FloatTensor input_ids: FloatTensor attention_mask: typing.Optional[torch.LongTensor] = None decoder_input_ids: typing.Optional[torch.LongTensor] = None decoder_attention_mask: typing.Optional[torch.LongTensor] = None output_attentions: typing.Optional[bool] = None output_hidden_states: typing.Optional[bool] = None labels: typing.Optional[torch.LongTensor] = None return_dict: typing.Optional[bool] = None interpolate_pos_encoding: bool = False use_cache: typing.Optional[bool] = None ) β transformers.models.blip_2.modeling_blip_2.Blip2ForConditionalGenerationModelOutput
or tuple(torch.FloatTensor)
Parameters
torch.FloatTensor
of shape (batch_size, num_channels, height, width)
) β Pixel values. Pixel values can be obtained using Blip2Processor. See Blip2Processor.__call__()
for details. torch.LongTensor
of shape (batch_size, sequence_length)
, optional) β Indices of input sequence tokens in the vocabulary of the language model. Input tokens can optionally be provided to serve as text prompt, which the language model can continue.
Indices can be obtained using Blip2Processor. See Blip2Processor.__call__()
for details.
torch.Tensor
of shape (batch_size, sequence_length)
, optional) β Mask to avoid performing attention on padding token indices. Mask values selected in [0, 1]
:
torch.LongTensor
of shape (batch_size, target_sequence_length)
, optional) β Indices of decoder input sequence tokens in the vocabulary of the language model. Only relevant in case an encoder-decoder language model (like T5) is used.
Indices can be obtained using AutoTokenizer. See PreTrainedTokenizer.encode() and PreTrainedTokenizer.call() for details. What are decoder input IDs?
torch.BoolTensor
of shape (batch_size, target_sequence_length)
, optional) β Default behavior: generate a tensor that ignores pad tokens in decoder_input_ids
. Causal mask will also be used by default.
Only relevant in case an encoder-decoder language model (like T5) is used.
bool
, optional) β Whether or not to return the attentions tensors of all attention layers. See attentions
under returned tensors for more detail. bool
, optional) β Whether or not to return the hidden states of all layers. See hidden_states
under returned tensors for more detail. bool
, optional) β Whether or not to return a ModelOutput instead of a plain tuple. bool
, optional, defaults to False
) β Whether to interpolate the pre-trained position encodings. bool
, optional) β If set to True
, past_key_values
key value states are returned and can be used to speed up decoding (see past_key_values
). Returns
transformers.models.blip_2.modeling_blip_2.Blip2ForConditionalGenerationModelOutput
or tuple(torch.FloatTensor)
A transformers.models.blip_2.modeling_blip_2.Blip2ForConditionalGenerationModelOutput
or a tuple of torch.FloatTensor
(if return_dict=False
is passed or when config.return_dict=False
) comprising various elements depending on the configuration (<class 'transformers.models.blip_2.configuration_blip_2.Blip2VisionConfig'>
) and inputs.
torch.FloatTensor
, optional, returned when labels
is provided, torch.FloatTensor
of shape (1,)
) β Language modeling loss from the language model.torch.FloatTensor
of shape (batch_size, sequence_length, config.vocab_size)
) β Prediction scores of the language modeling head of the language model.BaseModelOutputWithPooling
) β Outputs of the vision encoder.BaseModelOutputWithPoolingAndCrossAttentions
) β Outputs of the Q-Former (Querying Transformer).CausalLMOutputWithPast
or Seq2SeqLMOutput
) β Outputs of the language model.The Blip2ForConditionalGeneration forward method, overrides the __call__
special method.
Although the recipe for forward pass needs to be defined within this function, one should call the Module
instance afterwards instead of this since the former takes care of running the pre and post processing steps while the latter silently ignores them.
Examples:
Prepare processor, model and image input
>>> from PIL import Image >>> import requests >>> from transformers import Blip2Processor, Blip2ForConditionalGeneration >>> import torch >>> device = "cuda" if torch.cuda.is_available() else "cpu" >>> processor = Blip2Processor.from_pretrained("Salesforce/blip2-opt-2.7b") >>> model = Blip2ForConditionalGeneration.from_pretrained( ... "Salesforce/blip2-opt-2.7b", load_in_8bit=True, device_map={"": 0}, torch_dtype=torch.float16 ... ) >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg" >>> image = Image.open(requests.get(url, stream=True).raw)
Image captioning (without providing a text prompt):
>>> inputs = processor(images=image, return_tensors="pt").to(device, torch.float16) >>> generated_ids = model.generate(**inputs) >>> generated_text = processor.batch_decode(generated_ids, skip_special_tokens=True)[0].strip() >>> print(generated_text) two cats laying on a couch
Visual question answering (prompt = question):
>>> prompt = "Question: how many cats are there? Answer:" >>> inputs = processor(images=image, text=prompt, return_tensors="pt").to(device="cuda", dtype=torch.float16) >>> generated_ids = model.generate(**inputs) >>> generated_text = processor.batch_decode(generated_ids, skip_special_tokens=True)[0].strip() >>> print(generated_text) two
Note that int8 inference is also supported through bitsandbytes. This greatly reduces the amount of memory used by the model while maintaining the same performance.
>>> model = Blip2ForConditionalGeneration.from_pretrained( ... "Salesforce/blip2-opt-2.7b", load_in_8bit=True, device_map={"": 0}, torch_dtype=torch.bfloat16 ... ) >>> inputs = processor(images=image, text=prompt, return_tensors="pt").to(device="cuda", dtype=torch.bfloat16) >>> generated_ids = model.generate(**inputs) >>> generated_text = processor.batch_decode(generated_ids, skip_special_tokens=True)[0].strip() >>> print(generated_text) twogenerate < source >
( pixel_values: FloatTensor input_ids: typing.Optional[torch.LongTensor] = None attention_mask: typing.Optional[torch.LongTensor] = None interpolate_pos_encoding: bool = False **generate_kwargs ) β captions (list)
Parameters
torch.FloatTensor
of shape (batch_size, num_channels, height, width)) β Input images to be processed. torch.LongTensor
of shape (batch_size, sequence_length), optional) β The sequence used as a prompt for the generation. torch.LongTensor
of shape (batch_size, sequence_length), optional) β Mask to avoid performing attention on padding token indices A list of strings of length batch_size * num_captions.
Overrides generate
function to be able to use the model as a conditional generator.
( config: Blip2Config )
Parameters
BLIP-2 Model with a vision and text projector, and a classification head on top. The model is used in the context of image-text retrieval. Given an image and a text, the model returns the probability of the text being relevant to the image.
This model inherits from PreTrainedModel. Check the superclass documentation for the generic methods the library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads etc.)
This model is also a PyTorch torch.nn.Module subclass. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and behavior.
forward < source >( pixel_values: FloatTensor input_ids: LongTensor attention_mask: typing.Optional[torch.LongTensor] = None use_image_text_matching_head: typing.Optional[bool] = False output_attentions: typing.Optional[bool] = None output_hidden_states: typing.Optional[bool] = None return_dict: typing.Optional[bool] = None ) β transformers.models.blip_2.modeling_blip_2.Blip2ImageTextMatchingModelOutput
or tuple(torch.FloatTensor)
Parameters
torch.FloatTensor
of shape (batch_size, num_channels, height, width)
) β Pixel values. Pixel values can be obtained using Blip2Processor. See Blip2Processor.__call__()
for details. torch.LongTensor
of shape (batch_size, sequence_length)
, optional) β Indices of input sequence tokens in the vocabulary of the language model. Input tokens can optionally be provided to serve as text prompt, which the language model can continue.
Indices can be obtained using Blip2Processor. See Blip2Processor.__call__()
for details.
torch.Tensor
of shape (batch_size, sequence_length)
, optional) β Mask to avoid performing attention on padding token indices. Mask values selected in [0, 1]
:
bool
, optional) β Whether to return the Image-Text Matching or Contrastive scores. bool
, optional) β Whether or not to return the attentions tensors of all attention layers. See attentions
under returned tensors for more detail. bool
, optional) β Whether or not to return the hidden states of all layers. See hidden_states
under returned tensors for more detail. bool
, optional) β Whether or not to return a ModelOutput instead of a plain tuple. Returns
transformers.models.blip_2.modeling_blip_2.Blip2ImageTextMatchingModelOutput
or tuple(torch.FloatTensor)
A transformers.models.blip_2.modeling_blip_2.Blip2ImageTextMatchingModelOutput
or a tuple of torch.FloatTensor
(if return_dict=False
is passed or when config.return_dict=False
) comprising various elements depending on the configuration (<class 'transformers.models.blip_2.configuration_blip_2.Blip2Config'>
) and inputs.
torch.FloatTensor
of shape (1,)
, optional, returned when return_loss
is True
) β Contrastive loss for image-text similarity.torch.FloatTensor
of shape (image_batch_size, text_batch_size)
) β The scaled dot product scores between image_embeds
and text_embeds
. This represents the image-text similarity scores.torch.FloatTensor
of shape (text_batch_size, image_batch_size)
) β The scaled dot product scores between text_embeds
and image_embeds
. This represents the text-image similarity scores.torch.FloatTensor
of shape (batch_size, output_dim
) β The text embeddings obtained by applying the projection layer to the pooled output.torch.FloatTensor
of shape (batch_size, output_dim
) β The image embeddings obtained by applying the projection layer to the pooled output.BaseModelOutputWithPooling
) β The output of the Blip2QFormerModel.BaseModelOutputWithPooling
) β The output of the Blip2VisionModel.The Blip2ForImageTextRetrieval forward method, overrides the __call__
special method.
Although the recipe for forward pass needs to be defined within this function, one should call the Module
instance afterwards instead of this since the former takes care of running the pre and post processing steps while the latter silently ignores them.
Examples:
>>> import torch >>> from PIL import Image >>> import requests >>> from transformers import AutoProcessor, Blip2ForImageTextRetrieval >>> device = "cuda" if torch.cuda.is_available() else "cpu" >>> model = Blip2ForImageTextRetrieval.from_pretrained("Salesforce/blip2-itm-vit-g", torch_dtype=torch.float16) >>> processor = AutoProcessor.from_pretrained("Salesforce/blip2-itm-vit-g") >>> model.to(device) >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg" >>> image = Image.open(requests.get(url, stream=True).raw) >>> text = "two cats laying on a pink blanket" >>> inputs = processor(images=image, text=text, return_tensors="pt").to(device, torch.float16) >>> itm_out = model(**inputs, use_image_text_matching_head=True) >>> logits_per_image = torch.nn.functional.softmax(itm_out.logits_per_image, dim=1) >>> probs = logits_per_image.softmax(dim=1) >>> print(f"{probs[0][0]:.1%} that image 0 is not '{text}'") 26.9% that image 0 is not 'two cats laying on a pink blanket' >>> print(f"{probs[0][1]:.1%} that image 0 is '{text}'") 73.0% that image 0 is 'two cats laying on a pink blanket' >>> texts = ["a photo of a cat", "a photo of a dog"] >>> inputs = processor(images=image, text=texts, return_tensors="pt").to(device, torch.float16) >>> itc_out = model(**inputs, use_image_text_matching_head=False) >>> logits_per_image = itc_out.logits_per_image >>> probs = logits_per_image.softmax(dim=1) >>> print(f"{probs[0][0]:.1%} that image 0 is '{texts[0]}'") 55.3% that image 0 is 'a photo of a cat' >>> print(f"{probs[0][1]:.1%} that image 0 is '{texts[1]}'") 44.7% that image 0 is 'a photo of a dog'Blip2TextModelWithProjection class transformers.Blip2TextModelWithProjection < source >
( config: Blip2Config )
Parameters
BLIP-2 Text Model with a projection layer on top (a linear layer on top of the pooled output).
This model inherits from PreTrainedModel. Check the superclass documentation for the generic methods the library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads etc.)
This model is also a PyTorch torch.nn.Module subclass. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and behavior.
forward < source >( input_ids: typing.Optional[torch.Tensor] = None attention_mask: typing.Optional[torch.Tensor] = None position_ids: typing.Optional[torch.Tensor] = None output_attentions: typing.Optional[bool] = None output_hidden_states: typing.Optional[bool] = None return_dict: typing.Optional[bool] = None ) β transformers.models.blip_2.modeling_blip_2.Blip2TextModelOutput
or tuple(torch.FloatTensor)
Parameters
torch.LongTensor
of shape (batch_size, sequence_length)
) β Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide it. Indices can be obtained using AutoTokenizer. See PreTrainedTokenizer.encode() and PreTrainedTokenizer.call() for details. What are input IDs? torch.Tensor
of shape (batch_size, sequence_length)
, optional) β Mask to avoid performing attention on padding token indices. Mask values selected in [0, 1]
:
torch.LongTensor
of shape (batch_size, sequence_length)
, optional) β Indices of positions of each input sequence tokens in the position embeddings. Selected in the range [0, config.max_position_embeddings - 1]
. bool
, optional) β Whether or not to return the attentions tensors of all attention layers. See attentions
under returned tensors for more detail. bool
, optional) β Whether or not to return the hidden states of all layers. See hidden_states
under returned tensors for more detail. bool
, optional) β Whether or not to return a ModelOutput instead of a plain tuple. Returns
transformers.models.blip_2.modeling_blip_2.Blip2TextModelOutput
or tuple(torch.FloatTensor)
A transformers.models.blip_2.modeling_blip_2.Blip2TextModelOutput
or a tuple of torch.FloatTensor
(if return_dict=False
is passed or when config.return_dict=False
) comprising various elements depending on the configuration (<class 'transformers.models.blip_2.configuration_blip_2.Blip2Config'>
) and inputs.
text_embeds (torch.FloatTensor
of shape (batch_size, output_dim)
optional returned when model is initialized with with_projection=True
) β The text embeddings obtained by applying the projection layer to the pooler_output.
last_hidden_state (torch.FloatTensor
of shape (batch_size, sequence_length, hidden_size)
) β Sequence of hidden-states at the output of the last layer of the model.
hidden_states (tuple(torch.FloatTensor)
, optional, returned when output_hidden_states=True
is passed or when config.output_hidden_states=True
) β Tuple of torch.FloatTensor
(one for the output of the embeddings, if the model has an embedding layer, + one for the output of each layer) of shape (batch_size, sequence_length, hidden_size)
.
Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.
attentions (tuple(torch.FloatTensor)
, optional, returned when output_attentions=True
is passed or when config.output_attentions=True
) β Tuple of torch.FloatTensor
(one for each layer) of shape (batch_size, num_heads, sequence_length, sequence_length)
.
Attentions weights after the attention softmax, used to compute the weighted average in the self-attention heads.
The Blip2TextModelWithProjection forward method, overrides the __call__
special method.
Although the recipe for forward pass needs to be defined within this function, one should call the Module
instance afterwards instead of this since the former takes care of running the pre and post processing steps while the latter silently ignores them.
Examples:
>>> import torch >>> from transformers import AutoProcessor, Blip2TextModelWithProjection >>> device = "cuda" if torch.cuda.is_available() else "cpu" >>> model = Blip2TextModelWithProjection.from_pretrained( ... "Salesforce/blip2-itm-vit-g", torch_dtype=torch.float16 ... ) >>> model.to(device) >>> processor = AutoProcessor.from_pretrained("Salesforce/blip2-itm-vit-g") >>> inputs = processor(text=["a photo of a cat", "a photo of a dog"], return_tensors="pt").to(device) >>> outputs = model(**inputs) >>> text_embeds = outputs.text_embeds >>> print(text_embeds.shape) torch.Size([2, 7, 256])Blip2VisionModelWithProjection class transformers.Blip2VisionModelWithProjection < source >
( config: Blip2Config )
Parameters
BLIP-2 Vision Model with a projection layer on top (a linear layer on top of the pooled output).
This model inherits from PreTrainedModel. Check the superclass documentation for the generic methods the library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads etc.)
This model is also a PyTorch torch.nn.Module subclass. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and behavior.
forward < source >( pixel_values: typing.Optional[torch.FloatTensor] = None output_attentions: typing.Optional[bool] = None output_hidden_states: typing.Optional[bool] = None return_dict: typing.Optional[bool] = None ) β transformers.models.blip_2.modeling_blip_2.Blip2VisionModelOutput
or tuple(torch.FloatTensor)
Parameters
torch.FloatTensor
of shape (batch_size, num_channels, height, width)
) β Pixel values. Pixel values can be obtained using Blip2Processor. See Blip2Processor.__call__()
for details. bool
, optional) β Whether or not to return the attentions tensors of all attention layers. See attentions
under returned tensors for more detail. bool
, optional) β Whether or not to return the hidden states of all layers. See hidden_states
under returned tensors for more detail. bool
, optional) β Whether or not to return a ModelOutput instead of a plain tuple. bool
, optional, defaults to False
) β Whether to interpolate the pre-trained position encodings. Returns
transformers.models.blip_2.modeling_blip_2.Blip2VisionModelOutput
or tuple(torch.FloatTensor)
A transformers.models.blip_2.modeling_blip_2.Blip2VisionModelOutput
or a tuple of torch.FloatTensor
(if return_dict=False
is passed or when config.return_dict=False
) comprising various elements depending on the configuration (<class 'transformers.models.blip_2.configuration_blip_2.Blip2Config'>
) and inputs.
image_embeds (torch.FloatTensor
of shape (batch_size, output_dim)
optional returned when model is initialized with with_projection=True
) β The image embeddings obtained by applying the projection layer to the pooler_output.
last_hidden_state (torch.FloatTensor
of shape (batch_size, sequence_length, hidden_size)
) β Sequence of hidden-states at the output of the last layer of the model.
hidden_states (tuple(torch.FloatTensor)
, optional, returned when output_hidden_states=True
is passed or when config.output_hidden_states=True
) β Tuple of torch.FloatTensor
(one for the output of the embeddings, if the model has an embedding layer, + one for the output of each layer) of shape (batch_size, sequence_length, hidden_size)
.
Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.
attentions (tuple(torch.FloatTensor)
, optional, returned when output_attentions=True
is passed or when config.output_attentions=True
) β Tuple of torch.FloatTensor
(one for each layer) of shape (batch_size, num_heads, sequence_length, sequence_length)
.
Attentions weights after the attention softmax, used to compute the weighted average in the self-attention heads.
The Blip2VisionModelWithProjection forward method, overrides the __call__
special method.
Although the recipe for forward pass needs to be defined within this function, one should call the Module
instance afterwards instead of this since the former takes care of running the pre and post processing steps while the latter silently ignores them.
Examples:
>>> import torch >>> from PIL import Image >>> import requests >>> from transformers import AutoProcessor, Blip2VisionModelWithProjection >>> device = "cuda" if torch.cuda.is_available() else "cpu" >>> processor = AutoProcessor.from_pretrained("Salesforce/blip2-itm-vit-g") >>> model = Blip2VisionModelWithProjection.from_pretrained( ... "Salesforce/blip2-itm-vit-g", torch_dtype=torch.float16 ... ) >>> model.to(device) >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg" >>> image = Image.open(requests.get(url, stream=True).raw) >>> inputs = processor(images=image, return_tensors="pt").to(device, torch.float16) >>> outputs = model(**inputs) >>> image_embeds = outputs.image_embeds >>> print(image_embeds.shape) torch.Size([1, 32, 256])< > Update on GitHub
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.3