VisualBERT¶
Overview¶
The VisualBERT model was proposed in VisualBERT: A Simple and Performant Baseline for Vision and Language by Liunian Harold Li, Mark Yatskar, Da Yin, Cho-Jui Hsieh, Kai-Wei Chang. VisualBERT is a neural network trained on a variety of (image, text) pairs.
The abstract from the paper is the following:
We propose VisualBERT, a simple and flexible framework for modeling a broad range of vision-and-language tasks. VisualBERT consists of a stack of Transformer layers that implicitly align elements of an input text and regions in an associated input image with self-attention. We further propose two visually-grounded language model objectives for pre-training VisualBERT on image caption data. Experiments on four vision-and-language tasks including VQA, VCR, NLVR2, and Flickr30K show that VisualBERT outperforms or rivals with state-of-the-art models while being significantly simpler. Further analysis demonstrates that VisualBERT can ground elements of language to image regions without any explicit supervision and is even sensitive to syntactic relationships, tracking, for example, associations between verbs and image regions corresponding to their arguments.
Tips:
Most of the checkpoints provided work with the
VisualBertForPreTrainingconfiguration. Other checkpoints provided are the fine-tuned checkpoints for down-stream tasks - VQA (‘visualbert-vqa’), VCR (‘visualbert-vcr’), NLVR2 (‘visualbert-nlvr2’). Hence, if you are not working on these downstream tasks, it is recommended that you use the pretrained checkpoints.For the VCR task, the authors use a fine-tuned detector for generating visual embeddings, for all the checkpoints. We do not provide the detector and its weights as a part of the package, but it will be available in the research projects, and the states can be loaded directly into the detector provided.
Usage¶
VisualBERT is a multi-modal vision and language model. It can be used for visual question answering, multiple choice, visual reasoning and region-to-phrase correspondence tasks. VisualBERT uses a BERT-like transformer to prepare embeddings for image-text pairs. Both the text and visual features are then projected to a latent space with identical dimension.
To feed images to the model, each image is passed through a pre-trained object detector and the regions and the bounding boxes are extracted. The authors use the features generated after passing these regions through a pre-trained CNN like ResNet as visual embeddings. They also add absolute position embeddings, and feed the resulting sequence of vectors to a standard BERT model. The text input is concatenated in the front of the visual embeddings in the embedding layer, and is expected to be bound by [CLS] and a [SEP] tokens, as in BERT. The segment IDs must also be set appropriately for the textual and visual parts.
The BertTokenizer is used to encode the text. A custom detector/feature extractor must be used
to get the visual embeddings. For an example on how to generate visual embeddings, see the colab notebook. The following example shows
how to get the last hidden state using VisualBertModel:
>>> import torch
>>> from transformers import BertTokenizer, VisualBertModel
>>> model = VisualBertModel.from_pretrained("uclanlp/visualbert-vqa-coco-pre")
>>> tokenizer = BertTokenizer.from_pretrained("bert-base-uncased")
>>> inputs = tokenizer("What is the man eating?", return_tensors="pt")
>>> # this is a custom function that returns the visual embeddings given the image path
>>> visual_embeds = get_visual_embeddings(image_path)
>>> outputs = model(**inputs)
>>> last_hidden_state = outputs.last_hidden_state
This model was contributed by gchhablani. The original code can be found here.
VisualBertConfig¶
-
class
transformers.VisualBertConfig(vocab_size=30522, hidden_size=768, visual_embedding_dim=512, 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, type_vocab_size=2, initializer_range=0.02, layer_norm_eps=1e-12, bypass_transformer=False, special_visual_initialize=True, pad_token_id=1, bos_token_id=0, eos_token_id=2, **kwargs)[source]¶ This is the configuration class to store the configuration of a
VisualBertModel. It is used to instantiate an VisualBERT 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 VisualBERT visualbert-vqa-coco-pre architecture.Configuration objects inherit from
PretrainedConfigand can be used to control the model outputs. Read the documentation fromPretrainedConfigfor more information.- Parameters
vocab_size (
int, optional, defaults to 30522) – Vocabulary size of the VisualBERT model. Defines the number of different tokens that can be represented by theinputs_idspassed when callingVisualBertModel. Vocabulary size of the model. Defines the different tokens that can be represented by theinputs_idspassed to the forward method ofVisualBertModel.hidden_size (
int, optional, defaults to 768) – Dimensionality of the encoder layers and the pooler layer.visual_embedding_dim (
int, optional, defaults to 512) – Dimensionality of the visual embeddings to be passed to the model.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.intermediate_size (
int, optional, defaults to 3072) – Dimensionality of the “intermediate” (i.e., feed-forward) layer in the Transformer encoder.hidden_act (
strorfunction, 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"are supported.hidden_dropout_prob (
float, optional, defaults to 0.1) – The dropout probabilitiy for all fully connected layers in the embeddings, encoder, and pooler.attention_probs_dropout_prob (
float, optional, defaults to 0.1) – The dropout ratio for the attention probabilities.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).type_vocab_size (
int, optional, defaults to 2) – The vocabulary size of thetoken_type_idspassed when callingVisualBertModel.initializer_range (
float, optional, defaults to 0.02) – The standard deviation of the truncated_normal_initializer for initializing all weight matrices.layer_norm_eps (
float, optional, defaults to 1e-12) – The epsilon used by the layer normalization layers.bypass_transformer (
bool, optional, defaults toFalse) – Whether or not the model should bypass the transformer for the visual embeddings. If set toTrue, the model directly concatenates the visual embeddings fromVisualBertEmbeddingswith text output from transformers, and then pass it to a self-attention layer.special_visual_initialize (
bool, optional, defaults toTrue) – Whether or not the visual token type and position type embedding weights should be initialized the same as the textual token type and positive type embeddings. When set toTrue, the weights of the textual token type and position type embeddings are copied to the respective visual embedding layers.
Example:
>>> from transformers import VisualBertModel, VisualBertConfig >>> # Initializing a VisualBERT visualbert-vqa-coco-pre style configuration >>> configuration = VisualBertConfig.from_pretrained('visualbert-vqa-coco-pre') >>> # Initializing a model from the visualbert-vqa-coco-pre style configuration >>> model = VisualBertModel(configuration) >>> # Accessing the model configuration >>> configuration = model.config
VisualBertModel¶
-
class
transformers.VisualBertModel(config, add_pooling_layer=True)[source]¶ The bare VisualBert Model transformer outputting raw hidden-states without any specific head on top. 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.
- Parameters
config (
VisualBertConfig) – Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. Check out thefrom_pretrained()method to load the model weights.
The model can behave as an encoder (with only self-attention) following the architecture described in Attention is all you need by Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N. Gomez, Lukasz Kaiser and Illia Polosukhin.
-
forward(input_ids=None, attention_mask=None, token_type_ids=None, position_ids=None, head_mask=None, inputs_embeds=None, visual_embeds=None, visual_attention_mask=None, visual_token_type_ids=None, image_text_alignment=None, output_attentions=None, output_hidden_states=None, return_dict=None)[source]¶ The
VisualBertModelforward method, overrides the__call__()special method.Note
Although the recipe for forward pass needs to be defined within this function, one should call the
Moduleinstance afterwards instead of this since the former takes care of running the pre and post processing steps while the latter silently ignores them.- Parameters
input_ids (
torch.LongTensorof shape(batch_size, sequence_length)) –Indices of input sequence tokens in the vocabulary.
Indices can be obtained using
BertTokenizer. Seetransformers.PreTrainedTokenizer.encode()andtransformers.PreTrainedTokenizer.__call__()for details.attention_mask (
torch.FloatTensorof shape(batch_size, sequence_length), optional) –Mask to avoid performing attention on padding token indices. Mask values selected in
[0, 1]:1 for tokens that are not masked,
0 for tokens that are masked.
token_type_ids (
torch.LongTensorof shape(batch_size, sequence_length), optional) –Segment token indices to indicate first and second portions of the inputs. Indices are selected in
[0, 1]:0 corresponds to a sentence A token,
1 corresponds to a sentence B token.
position_ids (
torch.LongTensorof 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].head_mask (
torch.FloatTensorof shape(num_heads,)or(num_layers, num_heads), optional) –Mask to nullify selected heads of the self-attention modules. Mask values selected in
[0, 1]:1 indicates the head is not masked,
0 indicates the head is masked.
inputs_embeds (
torch.FloatTensorof shape(batch_size, sequence_length, hidden_size), optional) – Optionally, instead of passinginput_idsyou can choose to directly pass an embedded representation. This is useful if you want more control over how to convertinput_idsindices into associated vectors than the model’s internal embedding lookup matrix.visual_embeds (
torch.FloatTensorof shape(batch_size, visual_seq_length, visual_embedding_dim), optional) – The embedded representation of the visual inputs, generally derived using using an object detector.visual_attention_mask (
torch.FloatTensorof shape(batch_size, visual_seq_length), optional) –Mask to avoid performing attention on visual embeddings. Mask values selected in
[0, 1]:1 for tokens that are not masked,
0 for tokens that are masked.
visual_token_type_ids (
torch.LongTensorof shape(batch_size, visual_seq_length), optional) –Segment token indices to indicate different portions of the visual embeds.
What are token type IDs? The authors of VisualBERT set the visual_token_type_ids to 1 for all tokens.
image_text_alignment (
torch.LongTensorof shape(batch_size, visual_seq_length, alignment_number), optional) – Image-Text alignment uses to decide the position IDs of the visual embeddings.output_attentions (
bool, optional) – Whether or not to return the attentions tensors of all attention layers. Seeattentionsunder returned tensors for more detail.output_hidden_states (
bool, optional) – Whether or not to return the hidden states of all layers. Seehidden_statesunder returned tensors for more detail.return_dict (
bool, optional) – Whether or not to return aModelOutputinstead of a plain tuple.Returns –
Example:: –
>>> # Assumption: `get_visual_embeddings(image)` gets the visual embeddings of the image. >>> from transformers import BertTokenizer, VisualBertModel >>> import torch
>>> tokenizer = BertTokenizer.from_pretrained('bert-base-uncased') >>> model = VisualBertModel.from_pretrained('uclanlp/visualbert-vqa-coco-pre')
>>> inputs = tokenizer("The capital of France is Paris.", return_tensors="pt") >>> visual_embeds = get_visual_embeddings(image).unsqueeze(0) >>> visual_token_type_ids = torch.ones(visual_embeds.shape[:-1], dtype=torch.long) #example >>> visual_attention_mask = torch.ones(visual_embeds.shape[:-1], dtype=torch.float)
>>> inputs.update({{ ... "visual_embeds": visual_embeds, ... "visual_token_type_ids": visual_token_type_ids, ... "visual_attention_mask": visual_attention_mask ... }})
>>> outputs = model(**inputs)
>>> last_hidden_states = outputs.last_hidden_state
VisualBertForPreTraining¶
-
class
transformers.VisualBertForPreTraining(config)[source]¶ VisualBert Model with two heads on top as done during the pretraining: a masked language modeling head and a sentence-image prediction (classification) head.
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.
- Parameters
config (
VisualBertConfig) – Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. Check out thefrom_pretrained()method to load the model weights.
-
forward(input_ids=None, attention_mask=None, token_type_ids=None, position_ids=None, head_mask=None, inputs_embeds=None, visual_embeds=None, visual_attention_mask=None, visual_token_type_ids=None, image_text_alignment=None, output_attentions=None, output_hidden_states=None, return_dict=None, labels=None, sentence_image_labels=None)[source]¶ The
VisualBertForPreTrainingforward method, overrides the__call__()special method.Note
Although the recipe for forward pass needs to be defined within this function, one should call the
Moduleinstance afterwards instead of this since the former takes care of running the pre and post processing steps while the latter silently ignores them.- Parameters
input_ids (
torch.LongTensorof shape(batch_size, sequence_length)) –Indices of input sequence tokens in the vocabulary.
Indices can be obtained using
BertTokenizer. Seetransformers.PreTrainedTokenizer.encode()andtransformers.PreTrainedTokenizer.__call__()for details.attention_mask (
torch.FloatTensorof shape(batch_size, sequence_length), optional) –Mask to avoid performing attention on padding token indices. Mask values selected in
[0, 1]:1 for tokens that are not masked,
0 for tokens that are masked.
token_type_ids (
torch.LongTensorof shape(batch_size, sequence_length), optional) –Segment token indices to indicate first and second portions of the inputs. Indices are selected in
[0, 1]:0 corresponds to a sentence A token,
1 corresponds to a sentence B token.
position_ids (
torch.LongTensorof 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].head_mask (
torch.FloatTensorof shape(num_heads,)or(num_layers, num_heads), optional) –Mask to nullify selected heads of the self-attention modules. Mask values selected in
[0, 1]:1 indicates the head is not masked,
0 indicates the head is masked.
inputs_embeds (
torch.FloatTensorof shape(batch_size, sequence_length, hidden_size), optional) – Optionally, instead of passinginput_idsyou can choose to directly pass an embedded representation. This is useful if you want more control over how to convertinput_idsindices into associated vectors than the model’s internal embedding lookup matrix.visual_embeds (
torch.FloatTensorof shape(batch_size, visual_seq_length, visual_embedding_dim), optional) – The embedded representation of the visual inputs, generally derived using using an object detector.visual_attention_mask (
torch.FloatTensorof shape(batch_size, visual_seq_length), optional) –Mask to avoid performing attention on visual embeddings. Mask values selected in
[0, 1]:1 for tokens that are not masked,
0 for tokens that are masked.
visual_token_type_ids (
torch.LongTensorof shape(batch_size, visual_seq_length), optional) –Segment token indices to indicate different portions of the visual embeds.
What are token type IDs? The authors of VisualBERT set the visual_token_type_ids to 1 for all tokens.
image_text_alignment (
torch.LongTensorof shape(batch_size, visual_seq_length, alignment_number), optional) – Image-Text alignment uses to decide the position IDs of the visual embeddings.output_attentions (
bool, optional) – Whether or not to return the attentions tensors of all attention layers. Seeattentionsunder returned tensors for more detail.output_hidden_states (
bool, optional) – Whether or not to return the hidden states of all layers. Seehidden_statesunder returned tensors for more detail.return_dict (
bool, optional) –Whether or not to return a
ModelOutputinstead of a plain tuple.- labels (
torch.LongTensorof shape(batch_size, total_sequence_length), optional): Labels for computing the masked language modeling loss. Indices should be in
[-100, 0, ..., config.vocab_size](seeinput_idsdocstring) Tokens with indices set to-100are ignored (masked), the loss is only computed for the tokens with labels in[0, ..., config.vocab_size]- sentence_image_labels (
torch.LongTensorof shape(batch_size,), optional): Labels for computing the sentence-image prediction (classification) loss. Input should be a sequence pair (see
input_idsdocstring) Indices should be in[0, 1]:0 indicates sequence B is a matching pair of sequence A for the given image,
1 indicates sequence B is a random sequence w.r.t A for the given image.
- labels (
- Returns
A
VisualBertForPreTrainingOutputor a tuple oftorch.FloatTensor(ifreturn_dict=Falseis passed or whenconfig.return_dict=False) comprising various elements depending on the configuration (VisualBertConfig) and inputs.loss (optional, returned when
labelsis provided,torch.FloatTensorof shape(1,)) – Total loss as the sum of the masked language modeling loss and the sentence-image prediction (classification) loss.prediction_logits (
torch.FloatTensorof shape(batch_size, sequence_length, config.vocab_size)) – Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).seq_relationship_logits (
torch.FloatTensorof shape(batch_size, 2)) – Prediction scores of the sentence-image prediction (classification) head (scores of True/False continuation before SoftMax).hidden_states (
tuple(torch.FloatTensor), optional, returned whenoutput_hidden_states=Trueis passed or whenconfig.output_hidden_states=True) – Tuple oftorch.FloatTensor(one for the output of the embeddings + 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 initial embedding outputs.
attentions (
tuple(torch.FloatTensor), optional, returned whenoutput_attentions=Trueis passed or whenconfig.output_attentions=True) – Tuple oftorch.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.
Example:
>>> # Assumption: `get_visual_embeddings(image)` gets the visual embeddings of the image in the batch. >>> from transformers import BertTokenizer, VisualBertForPreTraining >>> tokenizer = BertTokenizer.from_pretrained('bert-base-uncased') >>> model = VisualBertForPreTraining.from_pretrained('uclanlp/visualbert-vqa-coco-pre') >>> inputs = tokenizer("The capital of France is {mask}.", return_tensors="pt") >>> visual_embeds = get_visual_embeddings(image).unsqueeze(0) >>> visual_token_type_ids = torch.ones(visual_embeds.shape[:-1], dtype=torch.long) #example >>> visual_attention_mask = torch.ones(visual_embeds.shape[:-1], dtype=torch.float) >>> inputs.update({{ ... "visual_embeds": visual_embeds, ... "visual_token_type_ids": visual_token_type_ids, ... "visual_attention_mask": visual_attention_mask ... }}) >>> max_length = inputs["input_ids"].shape[-1]+visual_embeds.shape[-2] >>> labels = tokenizer("The capital of France is Paris.", return_tensors="pt", padding="max_length", max_length=max_length)["input_ids"] >>> sentence_image_labels = torch.tensor(1).unsqueeze(0) # Batch_size >>> outputs = model(**inputs, labels=labels, sentence_image_labels=sentence_image_labels) >>> loss = outputs.loss >>> prediction_logits = outputs.prediction_logits >>> seq_relationship_logits = outputs.seq_relationship_logits
- Return type
VisualBertForPreTrainingOutputortuple(torch.FloatTensor)
VisualBertForQuestionAnswering¶
-
class
transformers.VisualBertForQuestionAnswering(config)[source]¶ VisualBert Model with a classification/regression head on top (a dropout and a linear layer on top of the pooled output) for VQA.
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.
- Parameters
config (
VisualBertConfig) – Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. Check out thefrom_pretrained()method to load the model weights.
-
forward(input_ids=None, attention_mask=None, token_type_ids=None, position_ids=None, head_mask=None, inputs_embeds=None, visual_embeds=None, visual_attention_mask=None, visual_token_type_ids=None, image_text_alignment=None, output_attentions=None, output_hidden_states=None, return_dict=None, labels=None)[source]¶ The
VisualBertForQuestionAnsweringforward method, overrides the__call__()special method.Note
Although the recipe for forward pass needs to be defined within this function, one should call the
Moduleinstance afterwards instead of this since the former takes care of running the pre and post processing steps while the latter silently ignores them.- Parameters
input_ids (
torch.LongTensorof shape(batch_size, sequence_length)) –Indices of input sequence tokens in the vocabulary.
Indices can be obtained using
BertTokenizer. Seetransformers.PreTrainedTokenizer.encode()andtransformers.PreTrainedTokenizer.__call__()for details.attention_mask (
torch.FloatTensorof shape(batch_size, sequence_length), optional) –Mask to avoid performing attention on padding token indices. Mask values selected in
[0, 1]:1 for tokens that are not masked,
0 for tokens that are masked.
token_type_ids (
torch.LongTensorof shape(batch_size, sequence_length), optional) –Segment token indices to indicate first and second portions of the inputs. Indices are selected in
[0, 1]:0 corresponds to a sentence A token,
1 corresponds to a sentence B token.
position_ids (
torch.LongTensorof 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].head_mask (
torch.FloatTensorof shape(num_heads,)or(num_layers, num_heads), optional) –Mask to nullify selected heads of the self-attention modules. Mask values selected in
[0, 1]:1 indicates the head is not masked,
0 indicates the head is masked.
inputs_embeds (
torch.FloatTensorof shape(batch_size, sequence_length, hidden_size), optional) – Optionally, instead of passinginput_idsyou can choose to directly pass an embedded representation. This is useful if you want more control over how to convertinput_idsindices into associated vectors than the model’s internal embedding lookup matrix.visual_embeds (
torch.FloatTensorof shape(batch_size, visual_seq_length, visual_embedding_dim), optional) – The embedded representation of the visual inputs, generally derived using using an object detector.visual_attention_mask (
torch.FloatTensorof shape(batch_size, visual_seq_length), optional) –Mask to avoid performing attention on visual embeddings. Mask values selected in
[0, 1]:1 for tokens that are not masked,
0 for tokens that are masked.
visual_token_type_ids (
torch.LongTensorof shape(batch_size, visual_seq_length), optional) –Segment token indices to indicate different portions of the visual embeds.
What are token type IDs? The authors of VisualBERT set the visual_token_type_ids to 1 for all tokens.
image_text_alignment (
torch.LongTensorof shape(batch_size, visual_seq_length, alignment_number), optional) – Image-Text alignment uses to decide the position IDs of the visual embeddings.output_attentions (
bool, optional) – Whether or not to return the attentions tensors of all attention layers. Seeattentionsunder returned tensors for more detail.output_hidden_states (
bool, optional) – Whether or not to return the hidden states of all layers. Seehidden_statesunder returned tensors for more detail.return_dict (
bool, optional) –Whether or not to return a
ModelOutputinstead of a plain tuple.- labels (
torch.LongTensorof shape(batch_size, total_sequence_length), optional): Labels for computing the sequence classification/regression loss. Indices should be in
[0, ..., config.num_labels - 1]. A KLDivLoss is computed between the labels and the returned logits.
- labels (
- Returns
A
SequenceClassifierOutputor a tuple oftorch.FloatTensor(ifreturn_dict=Falseis passed or whenconfig.return_dict=False) comprising various elements depending on the configuration (VisualBertConfig) and inputs.loss (
torch.FloatTensorof shape(1,), optional, returned whenlabelsis provided) – Classification (or regression if config.num_labels==1) loss.logits (
torch.FloatTensorof shape(batch_size, config.num_labels)) – Classification (or regression if config.num_labels==1) scores (before SoftMax).hidden_states (
tuple(torch.FloatTensor), optional, returned whenoutput_hidden_states=Trueis passed or whenconfig.output_hidden_states=True) – Tuple oftorch.FloatTensor(one for the output of the embeddings + 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 initial embedding outputs.
attentions (
tuple(torch.FloatTensor), optional, returned whenoutput_attentions=Trueis passed or whenconfig.output_attentions=True) – Tuple oftorch.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.
Example:
>>> # Assumption: `get_visual_embeddings(image)` gets the visual embeddings of the image in the batch. >>> from transformers import BertTokenizer, VisualBertForQuestionAnswering >>> import torch >>> tokenizer = BertTokenizer.from_pretrained('bert-base-uncased') >>> model = VisualBertForQuestionAnswering.from_pretrained('uclanlp/visualbert-vqa') >>> text = "Who is eating the apple?" >>> inputs = tokenizer(text, return_tensors='pt') >>> visual_embeds = get_visual_embeddings(image).unsqueeze(0) >>> visual_token_type_ids = torch.ones(visual_embeds.shape[:-1], dtype=torch.long) #example >>> visual_attention_mask = torch.ones(visual_embeds.shape[:-1], dtype=torch.float) >>> inputs.update({{ ... "visual_embeds": visual_embeds, ... "visual_token_type_ids": visual_token_type_ids, ... "visual_attention_mask": visual_attention_mask ... }}) >>> labels = torch.tensor([[0.0,1.0]]).unsqueeze(0) # Batch size 1, Num labels 2 >>> outputs = model(**inputs, labels=labels) >>> loss = outputs.loss >>> scores = outputs.logits
- Return type
SequenceClassifierOutputortuple(torch.FloatTensor)
VisualBertForMultipleChoice¶
-
class
transformers.VisualBertForMultipleChoice(config)[source]¶ VisualBert Model with a multiple choice classification head on top (a linear layer on top of the pooled output and a softmax) e.g. for VCR tasks.
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.
- Parameters
config (
VisualBertConfig) – Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. Check out thefrom_pretrained()method to load the model weights.
-
forward(input_ids=None, attention_mask=None, token_type_ids=None, position_ids=None, head_mask=None, inputs_embeds=None, visual_embeds=None, visual_attention_mask=None, visual_token_type_ids=None, image_text_alignment=None, output_attentions=None, output_hidden_states=None, return_dict=None, labels=None)[source]¶ The
VisualBertForMultipleChoiceforward method, overrides the__call__()special method.Note
Although the recipe for forward pass needs to be defined within this function, one should call the
Moduleinstance afterwards instead of this since the former takes care of running the pre and post processing steps while the latter silently ignores them.- Parameters
input_ids (
torch.LongTensorof shape(batch_size, num_choices, sequence_length)) –Indices of input sequence tokens in the vocabulary.
Indices can be obtained using
BertTokenizer. Seetransformers.PreTrainedTokenizer.encode()andtransformers.PreTrainedTokenizer.__call__()for details.attention_mask (
torch.FloatTensorof shape(batch_size, num_choices, sequence_length), optional) –Mask to avoid performing attention on padding token indices. Mask values selected in
[0, 1]:1 for tokens that are not masked,
0 for tokens that are masked.
token_type_ids (
torch.LongTensorof shape(batch_size, num_choices, sequence_length), optional) –Segment token indices to indicate first and second portions of the inputs. Indices are selected in
[0, 1]:0 corresponds to a sentence A token,
1 corresponds to a sentence B token.
position_ids (
torch.LongTensorof shape(batch_size, num_choices, 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].head_mask (
torch.FloatTensorof shape(num_heads,)or(num_layers, num_heads), optional) –Mask to nullify selected heads of the self-attention modules. Mask values selected in
[0, 1]:1 indicates the head is not masked,
0 indicates the head is masked.
inputs_embeds (
torch.FloatTensorof shape(batch_size, num_choices, sequence_length, hidden_size), optional) – Optionally, instead of passinginput_idsyou can choose to directly pass an embedded representation. This is useful if you want more control over how to convertinput_idsindices into associated vectors than the model’s internal embedding lookup matrix.visual_embeds (
torch.FloatTensorof shape(batch_size, visual_seq_length, visual_embedding_dim), optional) – The embedded representation of the visual inputs, generally derived using using an object detector.visual_attention_mask (
torch.FloatTensorof shape(batch_size, visual_seq_length), optional) –Mask to avoid performing attention on visual embeddings. Mask values selected in
[0, 1]:1 for tokens that are not masked,
0 for tokens that are masked.
visual_token_type_ids (
torch.LongTensorof shape(batch_size, visual_seq_length), optional) –Segment token indices to indicate different portions of the visual embeds.
What are token type IDs? The authors of VisualBERT set the visual_token_type_ids to 1 for all tokens.
image_text_alignment (
torch.LongTensorof shape(batch_size, visual_seq_length, alignment_number), optional) – Image-Text alignment uses to decide the position IDs of the visual embeddings.output_attentions (
bool, optional) – Whether or not to return the attentions tensors of all attention layers. Seeattentionsunder returned tensors for more detail.output_hidden_states (
bool, optional) – Whether or not to return the hidden states of all layers. Seehidden_statesunder returned tensors for more detail.return_dict (
bool, optional) –Whether or not to return a
ModelOutputinstead of a plain tuple.- labels (
torch.LongTensorof shape(batch_size,), optional): Labels for computing the multiple choice classification loss. Indices should be in
[0, ..., num_choices-1]wherenum_choicesis the size of the second dimension of the input tensors. (Seeinput_idsabove)
- labels (
- Returns
A
MultipleChoiceModelOutputor a tuple oftorch.FloatTensor(ifreturn_dict=Falseis passed or whenconfig.return_dict=False) comprising various elements depending on the configuration (VisualBertConfig) and inputs.loss (
torch.FloatTensorof shape (1,), optional, returned whenlabelsis provided) – Classification loss.logits (
torch.FloatTensorof shape(batch_size, num_choices)) – num_choices is the second dimension of the input tensors. (see input_ids above).Classification scores (before SoftMax).
hidden_states (
tuple(torch.FloatTensor), optional, returned whenoutput_hidden_states=Trueis passed or whenconfig.output_hidden_states=True) – Tuple oftorch.FloatTensor(one for the output of the embeddings + 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 initial embedding outputs.
attentions (
tuple(torch.FloatTensor), optional, returned whenoutput_attentions=Trueis passed or whenconfig.output_attentions=True) – Tuple oftorch.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.
Example:
>>> from transformers import BertTokenizer, VisualBertForMultipleChoice >>> import torch >>> tokenizer = BertTokenizer.from_pretrained('bert-base-uncased') >>> model = VisualBertForMultipleChoice.from_pretrained('uclanlp/visualbert-vcr') >>> prompt = "In Italy, pizza served in formal settings, such as at a restaurant, is presented unsliced." >>> choice0 = "It is eaten with a fork and a knife." >>> choice1 = "It is eaten while held in the hand." >>> visual_embeds = get_visual_embeddings(image) >>> # (batch_size, num_choices, visual_seq_length, visual_embedding_dim) >>> visual_embeds = visual_embeds.expand(1, 2, *visual_embeds.shape) >>> visual_token_type_ids = torch.ones(visual_embeds.shape[:-1], dtype=torch.long) >>> visual_attention_mask = torch.ones(visual_embeds.shape[:-1], dtype=torch.float) >>> labels = torch.tensor(0).unsqueeze(0) # choice0 is correct (according to Wikipedia ;)), batch size 1 >>> encoding = tokenizer([[prompt, prompt], [choice0, choice1]], return_tensors='pt', padding=True) >>> # batch size is 1 >>> inputs_dict = {{k: v.unsqueeze(0) for k,v in encoding.items()}} >>> inputs_dict.update({{ ... visual_embeds=visual_embeds, ... visual_attention_mask=visual_attention_mask, ... visual_token_type_ids=visual_token_type_ids, ... labels=labels ... }}) >>> outputs = model(**inputs_dict) >>> loss = outputs.loss >>> logits = outputs.logits
- Return type
MultipleChoiceModelOutputortuple(torch.FloatTensor)
VisualBertForVisualReasoning¶
-
class
transformers.VisualBertForVisualReasoning(config)[source]¶ VisualBert Model with a sequence classification head on top (a dropout and a linear layer on top of the pooled output) for Visual Reasoning e.g. for NLVR task.
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.
- Parameters
config (
VisualBertConfig) – Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. Check out thefrom_pretrained()method to load the model weights.
-
forward(input_ids=None, attention_mask=None, token_type_ids=None, position_ids=None, head_mask=None, inputs_embeds=None, visual_embeds=None, visual_attention_mask=None, visual_token_type_ids=None, image_text_alignment=None, output_attentions=None, output_hidden_states=None, return_dict=None, labels=None)[source]¶ The
VisualBertForVisualReasoningforward method, overrides the__call__()special method.Note
Although the recipe for forward pass needs to be defined within this function, one should call the
Moduleinstance afterwards instead of this since the former takes care of running the pre and post processing steps while the latter silently ignores them.- Parameters
input_ids (
torch.LongTensorof shape(batch_size, sequence_length)) –Indices of input sequence tokens in the vocabulary.
Indices can be obtained using
BertTokenizer. Seetransformers.PreTrainedTokenizer.encode()andtransformers.PreTrainedTokenizer.__call__()for details.attention_mask (
torch.FloatTensorof shape(batch_size, sequence_length), optional) –Mask to avoid performing attention on padding token indices. Mask values selected in
[0, 1]:1 for tokens that are not masked,
0 for tokens that are masked.
token_type_ids (
torch.LongTensorof shape(batch_size, sequence_length), optional) –Segment token indices to indicate first and second portions of the inputs. Indices are selected in
[0, 1]:0 corresponds to a sentence A token,
1 corresponds to a sentence B token.
position_ids (
torch.LongTensorof 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].head_mask (
torch.FloatTensorof shape(num_heads,)or(num_layers, num_heads), optional) –Mask to nullify selected heads of the self-attention modules. Mask values selected in
[0, 1]:1 indicates the head is not masked,
0 indicates the head is masked.
inputs_embeds (
torch.FloatTensorof shape(batch_size, sequence_length, hidden_size), optional) – Optionally, instead of passinginput_idsyou can choose to directly pass an embedded representation. This is useful if you want more control over how to convertinput_idsindices into associated vectors than the model’s internal embedding lookup matrix.visual_embeds (
torch.FloatTensorof shape(batch_size, visual_seq_length, visual_embedding_dim), optional) – The embedded representation of the visual inputs, generally derived using using an object detector.visual_attention_mask (
torch.FloatTensorof shape(batch_size, visual_seq_length), optional) –Mask to avoid performing attention on visual embeddings. Mask values selected in
[0, 1]:1 for tokens that are not masked,
0 for tokens that are masked.
visual_token_type_ids (
torch.LongTensorof shape(batch_size, visual_seq_length), optional) –Segment token indices to indicate different portions of the visual embeds.
What are token type IDs? The authors of VisualBERT set the visual_token_type_ids to 1 for all tokens.
image_text_alignment (
torch.LongTensorof shape(batch_size, visual_seq_length, alignment_number), optional) – Image-Text alignment uses to decide the position IDs of the visual embeddings.output_attentions (
bool, optional) – Whether or not to return the attentions tensors of all attention layers. Seeattentionsunder returned tensors for more detail.output_hidden_states (
bool, optional) – Whether or not to return the hidden states of all layers. Seehidden_statesunder returned tensors for more detail.return_dict (
bool, optional) –Whether or not to return a
ModelOutputinstead of a plain tuple.- labels (
torch.LongTensorof shape(batch_size,), optional): Labels for computing the sequence classification/regression loss. Indices should be in
[0, ..., config.num_labels - 1]. A classification loss is computed (Cross-Entropy) against these labels.
- labels (
- Returns
A
SequenceClassifierOutputor a tuple oftorch.FloatTensor(ifreturn_dict=Falseis passed or whenconfig.return_dict=False) comprising various elements depending on the configuration (VisualBertConfig) and inputs.loss (
torch.FloatTensorof shape(1,), optional, returned whenlabelsis provided) – Classification (or regression if config.num_labels==1) loss.logits (
torch.FloatTensorof shape(batch_size, config.num_labels)) – Classification (or regression if config.num_labels==1) scores (before SoftMax).hidden_states (
tuple(torch.FloatTensor), optional, returned whenoutput_hidden_states=Trueis passed or whenconfig.output_hidden_states=True) – Tuple oftorch.FloatTensor(one for the output of the embeddings + 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 initial embedding outputs.
attentions (
tuple(torch.FloatTensor), optional, returned whenoutput_attentions=Trueis passed or whenconfig.output_attentions=True) – Tuple oftorch.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.
Example:
>>> # Assumption: `get_visual_embeddings(image)` gets the visual embeddings of the image in the batch. >>> from transformers import BertTokenizer, VisualBertForVisualReasoning >>> import torch >>> tokenizer = BertTokenizer.from_pretrained('bert-base-uncased') >>> model = VisualBertForVisualReasoning.from_pretrained('uclanlp/visualbert-nlvr2') >>> text = "Who is eating the apple?" >>> inputs = tokenizer(text, return_tensors='pt') >>> visual_embeds = get_visual_embeddings(image).unsqueeze(0) >>> visual_token_type_ids = torch.ones(visual_embeds.shape[:-1], dtype=torch.long) #example >>> visual_attention_mask = torch.ones(visual_embeds.shape[:-1], dtype=torch.float) >>> inputs.update({{ ... "visual_embeds": visual_embeds, ... "visual_token_type_ids": visual_token_type_ids, ... "visual_attention_mask": visual_attention_mask ... }}) >>> labels = torch.tensor(1).unsqueeze(0) # Batch size 1, Num choices 2 >>> outputs = model(**inputs, labels=labels) >>> loss = outputs.loss >>> scores = outputs.logits
- Return type
SequenceClassifierOutputortuple(torch.FloatTensor)
VisualBertForRegionToPhraseAlignment¶
-
class
transformers.VisualBertForRegionToPhraseAlignment(config)[source]¶ VisualBert Model with a Masked Language Modeling head and an attention layer on top for Region-to-Phrase Alignment e.g. for Flickr30 Entities task.
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.
- Parameters
config (
VisualBertConfig) – Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. Check out thefrom_pretrained()method to load the model weights.
-
forward(input_ids=None, attention_mask=None, token_type_ids=None, position_ids=None, head_mask=None, inputs_embeds=None, visual_embeds=None, visual_attention_mask=None, visual_token_type_ids=None, image_text_alignment=None, output_attentions=None, output_hidden_states=None, return_dict=None, region_to_phrase_position=None, labels=None)[source]¶ The
VisualBertForRegionToPhraseAlignmentforward method, overrides the__call__()special method.Note
Although the recipe for forward pass needs to be defined within this function, one should call the
Moduleinstance afterwards instead of this since the former takes care of running the pre and post processing steps while the latter silently ignores them.- Parameters
input_ids (
torch.LongTensorof shape(batch_size, sequence_length)) –Indices of input sequence tokens in the vocabulary.
Indices can be obtained using
BertTokenizer. Seetransformers.PreTrainedTokenizer.encode()andtransformers.PreTrainedTokenizer.__call__()for details.attention_mask (
torch.FloatTensorof shape(batch_size, sequence_length), optional) –Mask to avoid performing attention on padding token indices. Mask values selected in
[0, 1]:1 for tokens that are not masked,
0 for tokens that are masked.
token_type_ids (
torch.LongTensorof shape(batch_size, sequence_length), optional) –Segment token indices to indicate first and second portions of the inputs. Indices are selected in
[0, 1]:0 corresponds to a sentence A token,
1 corresponds to a sentence B token.
position_ids (
torch.LongTensorof 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].head_mask (
torch.FloatTensorof shape(num_heads,)or(num_layers, num_heads), optional) –Mask to nullify selected heads of the self-attention modules. Mask values selected in
[0, 1]:1 indicates the head is not masked,
0 indicates the head is masked.
inputs_embeds (
torch.FloatTensorof shape(batch_size, sequence_length, hidden_size), optional) – Optionally, instead of passinginput_idsyou can choose to directly pass an embedded representation. This is useful if you want more control over how to convertinput_idsindices into associated vectors than the model’s internal embedding lookup matrix.visual_embeds (
torch.FloatTensorof shape(batch_size, visual_seq_length, visual_embedding_dim), optional) – The embedded representation of the visual inputs, generally derived using using an object detector.visual_attention_mask (
torch.FloatTensorof shape(batch_size, visual_seq_length), optional) –Mask to avoid performing attention on visual embeddings. Mask values selected in
[0, 1]:1 for tokens that are not masked,
0 for tokens that are masked.
visual_token_type_ids (
torch.LongTensorof shape(batch_size, visual_seq_length), optional) –Segment token indices to indicate different portions of the visual embeds.
What are token type IDs? The authors of VisualBERT set the visual_token_type_ids to 1 for all tokens.
image_text_alignment (
torch.LongTensorof shape(batch_size, visual_seq_length, alignment_number), optional) – Image-Text alignment uses to decide the position IDs of the visual embeddings.output_attentions (
bool, optional) – Whether or not to return the attentions tensors of all attention layers. Seeattentionsunder returned tensors for more detail.output_hidden_states (
bool, optional) – Whether or not to return the hidden states of all layers. Seehidden_statesunder returned tensors for more detail.return_dict (
bool, optional) –Whether or not to return a
ModelOutputinstead of a plain tuple.- region_to_phrase_position (
torch.LongTensorof shape(batch_size, total_sequence_length), optional): The positions depicting the position of the image embedding corresponding to the textual tokens.
- labels (
torch.LongTensorof shape(batch_size, total_sequence_length, visual_sequence_length), optional): Labels for computing the masked language modeling loss. KLDivLoss is computed against these labels and the outputs from the attention layer.
- region_to_phrase_position (
- Returns
A
SequenceClassifierOutputor a tuple oftorch.FloatTensor(ifreturn_dict=Falseis passed or whenconfig.return_dict=False) comprising various elements depending on the configuration (VisualBertConfig) and inputs.loss (
torch.FloatTensorof shape(1,), optional, returned whenlabelsis provided) – Classification (or regression if config.num_labels==1) loss.logits (
torch.FloatTensorof shape(batch_size, config.num_labels)) – Classification (or regression if config.num_labels==1) scores (before SoftMax).hidden_states (
tuple(torch.FloatTensor), optional, returned whenoutput_hidden_states=Trueis passed or whenconfig.output_hidden_states=True) – Tuple oftorch.FloatTensor(one for the output of the embeddings + 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 initial embedding outputs.
attentions (
tuple(torch.FloatTensor), optional, returned whenoutput_attentions=Trueis passed or whenconfig.output_attentions=True) – Tuple oftorch.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.
Example:
>>> # Assumption: `get_visual_embeddings(image)` gets the visual embeddings of the image in the batch. >>> from transformers import BertTokenizer, VisualBertForRegionToPhraseAlignment >>> import torch >>> tokenizer = BertTokenizer.from_pretrained('bert-base-uncased') >>> model = VisualBertForRegionToPhraseAlignment.from_pretrained('uclanlp/visualbert-vqa-coco-pre') >>> text = "Who is eating the apple?" >>> inputs = tokenizer(text, return_tensors='pt') >>> visual_embeds = get_visual_embeddings(image).unsqueeze(0) >>> visual_token_type_ids = torch.ones(visual_embeds.shape[:-1], dtype=torch.long) #example >>> visual_attention_mask = torch.ones(visual_embeds.shape[:-1], dtype=torch.float) >>> region_to_phrase_position = torch.ones((1, inputs["input_ids"].shape[-1]+visual_embeds.shape[-2])) >>> inputs.update({{ ... "region_to_phrase_position": region_to_phrase_position, ... "visual_embeds": visual_embeds, ... "visual_token_type_ids": visual_token_type_ids, ... "visual_attention_mask": visual_attention_mask ... }}) >>> labels = torch.ones((1, inputs["input_ids"].shape[-1]+visual_embeds.shape[-2], visual_embeds.shape[-2])) # Batch size 1 >>> outputs = model(**inputs, labels=labels) >>> loss = outputs.loss >>> scores = outputs.logits
- Return type
SequenceClassifierOutputortuple(torch.FloatTensor)