VisualBERT
Last updated
Last updated
The VisualBERT model was proposed in 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 configuration. 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.
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 is used to encode the text. A custom detector/image processor must be used to get the visual embeddings. The following example notebooks show how to use VisualBERT with Detectron-like models:
: This notebook contains an example on VisualBERT VQA.
: This notebook contains an example on how to generate visual embeddings.
The following example shows how to get the last hidden state using :
Copied
( vocab_size = 30522hidden_size = 768visual_embedding_dim = 512num_hidden_layers = 12num_attention_heads = 12intermediate_size = 3072hidden_act = 'gelu'hidden_dropout_prob = 0.1attention_probs_dropout_prob = 0.1max_position_embeddings = 512type_vocab_size = 2initializer_range = 0.02layer_norm_eps = 1e-12bypass_transformer = Falsespecial_visual_initialize = Truepad_token_id = 1bos_token_id = 0eos_token_id = 2**kwargs )
Parameters
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 (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"
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).
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 to False
) — Whether or not the model should bypass the transformer for the visual embeddings. If set to True
, the model directly concatenates the visual embeddings from VisualBertEmbeddings
with text output from transformers, and then pass it to a self-attention layer.
special_visual_initialize (bool
, optional, defaults to True
) — 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 to True
, the weights of the textual token type and position type embeddings are copied to the respective visual embedding layers.
Example:
Copied
( configadd_pooling_layer = True )
Parameters
forward
Parameters
input_ids (torch.LongTensor
of shape (batch_size, sequence_length)
) — Indices of input sequence tokens in the vocabulary.
attention_mask (torch.FloatTensor
of 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.LongTensor
of 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.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]
.
head_mask (torch.FloatTensor
of 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.FloatTensor
of shape (batch_size, sequence_length, hidden_size)
, optional) — Optionally, instead of passing input_ids
you can choose to directly pass an embedded representation. This is useful if you want more control over how to convert input_ids
indices into associated vectors than the model’s internal embedding lookup matrix.
visual_embeds (torch.FloatTensor
of 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.FloatTensor
of 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.LongTensor
of shape (batch_size, visual_seq_length)
, optional) — Segment token indices to indicate different portions of the visual embeds.
image_text_alignment (torch.LongTensor
of 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. See attentions
under returned tensors for more detail.
output_hidden_states (bool
, optional) — Whether or not to return the hidden states of all layers. See hidden_states
under returned tensors for more detail.
Returns
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.
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.
Example:
Copied
( config )
Parameters
VisualBert Model with two heads on top as done during the pretraining: a masked language modeling
head and a sentence-image prediction (classification)
head.
forward
( input_ids: typing.Optional[torch.LongTensor] = Noneattention_mask: typing.Optional[torch.LongTensor] = Nonetoken_type_ids: typing.Optional[torch.LongTensor] = Noneposition_ids: typing.Optional[torch.LongTensor] = Nonehead_mask: typing.Optional[torch.LongTensor] = Noneinputs_embeds: typing.Optional[torch.FloatTensor] = Nonevisual_embeds: typing.Optional[torch.FloatTensor] = Nonevisual_attention_mask: typing.Optional[torch.LongTensor] = Nonevisual_token_type_ids: typing.Optional[torch.LongTensor] = Noneimage_text_alignment: typing.Optional[torch.LongTensor] = Noneoutput_attentions: typing.Optional[bool] = Noneoutput_hidden_states: typing.Optional[bool] = Nonereturn_dict: typing.Optional[bool] = Nonelabels: typing.Optional[torch.LongTensor] = Nonesentence_image_labels: typing.Optional[torch.LongTensor] = None ) → transformers.models.visual_bert.modeling_visual_bert.VisualBertForPreTrainingOutput
or tuple(torch.FloatTensor)
Parameters
input_ids (torch.LongTensor
of shape (batch_size, sequence_length)
) — Indices of input sequence tokens in the vocabulary.
attention_mask (torch.FloatTensor
of 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.LongTensor
of 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.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]
.
head_mask (torch.FloatTensor
of 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.FloatTensor
of shape (batch_size, sequence_length, hidden_size)
, optional) — Optionally, instead of passing input_ids
you can choose to directly pass an embedded representation. This is useful if you want more control over how to convert input_ids
indices into associated vectors than the model’s internal embedding lookup matrix.
visual_embeds (torch.FloatTensor
of 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.FloatTensor
of 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.LongTensor
of shape (batch_size, visual_seq_length)
, optional) — Segment token indices to indicate different portions of the visual embeds.
image_text_alignment (torch.LongTensor
of 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. See attentions
under returned tensors for more detail.
output_hidden_states (bool
, optional) — Whether or not to return the hidden states of all layers. See hidden_states
under returned tensors for more detail.
labels (torch.LongTensor
of shape (batch_size, total_sequence_length)
, optional) — Labels for computing the masked language modeling loss. Indices should be in [-100, 0, ..., config.vocab_size]
(see input_ids
docstring) Tokens with indices set to -100
are ignored (masked), the loss is only computed for the tokens with labels in [0, ..., config.vocab_size]
sentence_image_labels (torch.LongTensor
of shape (batch_size,)
, optional) — Labels for computing the sentence-image prediction (classification) loss. Input should be a sequence pair (see input_ids
docstring) 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.
Returns
transformers.models.visual_bert.modeling_visual_bert.VisualBertForPreTrainingOutput
or tuple(torch.FloatTensor)
loss (optional, returned when labels
is provided, torch.FloatTensor
of shape (1,)
) — Total loss as the sum of the masked language modeling loss and the sentence-image prediction (classification) loss.
prediction_logits (torch.FloatTensor
of 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.FloatTensor
of 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 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 + 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 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.
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.
Example:
Copied
( config )
Parameters
VisualBert Model with a classification/regression head on top (a dropout and a linear layer on top of the pooled output) for VQA.
forward
Parameters
input_ids (torch.LongTensor
of shape (batch_size, sequence_length)
) — Indices of input sequence tokens in the vocabulary.
attention_mask (torch.FloatTensor
of 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.LongTensor
of 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.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]
.
head_mask (torch.FloatTensor
of 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.FloatTensor
of shape (batch_size, sequence_length, hidden_size)
, optional) — Optionally, instead of passing input_ids
you can choose to directly pass an embedded representation. This is useful if you want more control over how to convert input_ids
indices into associated vectors than the model’s internal embedding lookup matrix.
visual_embeds (torch.FloatTensor
of 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.FloatTensor
of 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.LongTensor
of shape (batch_size, visual_seq_length)
, optional) — Segment token indices to indicate different portions of the visual embeds.
image_text_alignment (torch.LongTensor
of 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. See attentions
under returned tensors for more detail.
output_hidden_states (bool
, optional) — Whether or not to return the hidden states of all layers. See hidden_states
under returned tensors for more detail.
labels (torch.LongTensor
of 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.
Returns
loss (torch.FloatTensor
of shape (1,)
, optional, returned when labels
is provided) — Classification (or regression if config.num_labels==1) loss.
logits (torch.FloatTensor
of shape (batch_size, config.num_labels)
) — Classification (or regression if config.num_labels==1) scores (before SoftMax).
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.
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.
Example:
Copied
( config )
Parameters
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.
forward
Parameters
input_ids (torch.LongTensor
of shape (batch_size, num_choices, sequence_length)
) — Indices of input sequence tokens in the vocabulary.
attention_mask (torch.FloatTensor
of 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.LongTensor
of 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.LongTensor
of 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.FloatTensor
of 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.FloatTensor
of shape (batch_size, num_choices, sequence_length, hidden_size)
, optional) — Optionally, instead of passing input_ids
you can choose to directly pass an embedded representation. This is useful if you want more control over how to convert input_ids
indices into associated vectors than the model’s internal embedding lookup matrix.
visual_embeds (torch.FloatTensor
of 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.FloatTensor
of 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.LongTensor
of shape (batch_size, visual_seq_length)
, optional) — Segment token indices to indicate different portions of the visual embeds.
image_text_alignment (torch.LongTensor
of 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. See attentions
under returned tensors for more detail.
output_hidden_states (bool
, optional) — Whether or not to return the hidden states of all layers. See hidden_states
under returned tensors for more detail.
labels (torch.LongTensor
of shape (batch_size,)
, optional) — Labels for computing the multiple choice classification loss. Indices should be in [0, ..., num_choices-1]
where num_choices
is the size of the second dimension of the input tensors. (See input_ids
above)
Returns
loss (torch.FloatTensor
of shape (1,), optional, returned when labels
is provided) — Classification loss.
logits (torch.FloatTensor
of 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 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.
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.
Example:
Copied
( config )
Parameters
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.
forward
Parameters
input_ids (torch.LongTensor
of shape (batch_size, sequence_length)
) — Indices of input sequence tokens in the vocabulary.
attention_mask (torch.FloatTensor
of 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.LongTensor
of 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.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]
.
head_mask (torch.FloatTensor
of 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.FloatTensor
of shape (batch_size, sequence_length, hidden_size)
, optional) — Optionally, instead of passing input_ids
you can choose to directly pass an embedded representation. This is useful if you want more control over how to convert input_ids
indices into associated vectors than the model’s internal embedding lookup matrix.
visual_embeds (torch.FloatTensor
of 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.FloatTensor
of 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.LongTensor
of shape (batch_size, visual_seq_length)
, optional) — Segment token indices to indicate different portions of the visual embeds.
image_text_alignment (torch.LongTensor
of 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. See attentions
under returned tensors for more detail.
output_hidden_states (bool
, optional) — Whether or not to return the hidden states of all layers. See hidden_states
under returned tensors for more detail.
labels (torch.LongTensor
of 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.
Returns
loss (torch.FloatTensor
of shape (1,)
, optional, returned when labels
is provided) — Classification (or regression if config.num_labels==1) loss.
logits (torch.FloatTensor
of shape (batch_size, config.num_labels)
) — Classification (or regression if config.num_labels==1) scores (before SoftMax).
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.
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.
Example:
Copied
( config )
Parameters
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.
forward
Parameters
input_ids (torch.LongTensor
of shape (batch_size, sequence_length)
) — Indices of input sequence tokens in the vocabulary.
attention_mask (torch.FloatTensor
of 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.LongTensor
of 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.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]
.
head_mask (torch.FloatTensor
of 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.FloatTensor
of shape (batch_size, sequence_length, hidden_size)
, optional) — Optionally, instead of passing input_ids
you can choose to directly pass an embedded representation. This is useful if you want more control over how to convert input_ids
indices into associated vectors than the model’s internal embedding lookup matrix.
visual_embeds (torch.FloatTensor
of 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.FloatTensor
of 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.LongTensor
of shape (batch_size, visual_seq_length)
, optional) — Segment token indices to indicate different portions of the visual embeds.
image_text_alignment (torch.LongTensor
of 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. See attentions
under returned tensors for more detail.
output_hidden_states (bool
, optional) — Whether or not to return the hidden states of all layers. See hidden_states
under returned tensors for more detail.
region_to_phrase_position (torch.LongTensor
of shape (batch_size, total_sequence_length)
, optional) — The positions depicting the position of the image embedding corresponding to the textual tokens.
labels (torch.LongTensor
of 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.
Returns
loss (torch.FloatTensor
of shape (1,)
, optional, returned when labels
is provided) — Classification (or regression if config.num_labels==1) loss.
logits (torch.FloatTensor
of shape (batch_size, config.num_labels)
) — Classification (or regression if config.num_labels==1) scores (before SoftMax).
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.
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.
Example:
Copied
This model was contributed by . The original code can be found .
vocab_size (int
, optional, defaults to 30522) — Vocabulary size of the VisualBERT model. Defines the number of different tokens that can be represented by the inputs_ids
passed when calling . Vocabulary size of the model. Defines the different tokens that can be represented by the inputs_ids
passed to the forward method of .
type_vocab_size (int
, optional, defaults to 2) — The vocabulary size of the token_type_ids
passed when calling .
This is the configuration class to store the configuration of a . 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 architecture.
Configuration objects inherit from and can be used to control the model outputs. Read the documentation from for more information.
config () — 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 the method to load the model weights.
The bare VisualBert Model transformer outputting raw hidden-states without any specific head on top. This model inherits from . 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 subclass. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and behavior.
The model can behave as an encoder (with only self-attention) following the architecture described in by Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N. Gomez, Lukasz Kaiser and Illia Polosukhin.
( input_ids: typing.Optional[torch.LongTensor] = Noneattention_mask: typing.Optional[torch.LongTensor] = Nonetoken_type_ids: typing.Optional[torch.LongTensor] = Noneposition_ids: typing.Optional[torch.LongTensor] = Nonehead_mask: typing.Optional[torch.LongTensor] = Noneinputs_embeds: typing.Optional[torch.FloatTensor] = Nonevisual_embeds: typing.Optional[torch.FloatTensor] = Nonevisual_attention_mask: typing.Optional[torch.LongTensor] = Nonevisual_token_type_ids: typing.Optional[torch.LongTensor] = Noneimage_text_alignment: typing.Optional[torch.LongTensor] = Noneoutput_attentions: typing.Optional[bool] = Noneoutput_hidden_states: typing.Optional[bool] = Nonereturn_dict: typing.Optional[bool] = None ) → or tuple(torch.FloatTensor)
Indices can be obtained using . See and for details.
The authors of VisualBERT set the visual_token_type_ids to 1 for all tokens.
return_dict (bool
, optional) — Whether or not to return a instead of a plain tuple.
or tuple(torch.FloatTensor)
A 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 () and inputs.
The forward method, overrides the __call__
special method.
config () — 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 the method to load the model weights.
This model inherits from . 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 subclass. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and behavior.
Indices can be obtained using . See and for details.
The authors of VisualBERT set the visual_token_type_ids to 1 for all tokens.
return_dict (bool
, optional) — Whether or not to return a instead of a plain tuple.
A transformers.models.visual_bert.modeling_visual_bert.VisualBertForPreTrainingOutput
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 () and inputs.
The forward method, overrides the __call__
special method.
config () — 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 the method to load the model weights.
This model inherits from . 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 subclass. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and behavior.
( input_ids: typing.Optional[torch.LongTensor] = Noneattention_mask: typing.Optional[torch.LongTensor] = Nonetoken_type_ids: typing.Optional[torch.LongTensor] = Noneposition_ids: typing.Optional[torch.LongTensor] = Nonehead_mask: typing.Optional[torch.LongTensor] = Noneinputs_embeds: typing.Optional[torch.FloatTensor] = Nonevisual_embeds: typing.Optional[torch.FloatTensor] = Nonevisual_attention_mask: typing.Optional[torch.LongTensor] = Nonevisual_token_type_ids: typing.Optional[torch.LongTensor] = Noneimage_text_alignment: typing.Optional[torch.LongTensor] = Noneoutput_attentions: typing.Optional[bool] = Noneoutput_hidden_states: typing.Optional[bool] = Nonereturn_dict: typing.Optional[bool] = Nonelabels: typing.Optional[torch.LongTensor] = None ) → or tuple(torch.FloatTensor)
Indices can be obtained using . See and for details.
The authors of VisualBERT set the visual_token_type_ids to 1 for all tokens.
return_dict (bool
, optional) — Whether or not to return a instead of a plain tuple.
or tuple(torch.FloatTensor)
A 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 () and inputs.
The forward method, overrides the __call__
special method.
config () — 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 the method to load the model weights.
This model inherits from . 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 subclass. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and behavior.
( input_ids: typing.Optional[torch.LongTensor] = Noneattention_mask: typing.Optional[torch.LongTensor] = Nonetoken_type_ids: typing.Optional[torch.LongTensor] = Noneposition_ids: typing.Optional[torch.LongTensor] = Nonehead_mask: typing.Optional[torch.LongTensor] = Noneinputs_embeds: typing.Optional[torch.FloatTensor] = Nonevisual_embeds: typing.Optional[torch.FloatTensor] = Nonevisual_attention_mask: typing.Optional[torch.LongTensor] = Nonevisual_token_type_ids: typing.Optional[torch.LongTensor] = Noneimage_text_alignment: typing.Optional[torch.LongTensor] = Noneoutput_attentions: typing.Optional[bool] = Noneoutput_hidden_states: typing.Optional[bool] = Nonereturn_dict: typing.Optional[bool] = Nonelabels: typing.Optional[torch.LongTensor] = None ) → or tuple(torch.FloatTensor)
Indices can be obtained using . See and for details.
The authors of VisualBERT set the visual_token_type_ids to 1 for all tokens.
return_dict (bool
, optional) — Whether or not to return a instead of a plain tuple.
or tuple(torch.FloatTensor)
A 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 () and inputs.
The forward method, overrides the __call__
special method.
config () — 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 the method to load the model weights.
This model inherits from . 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 subclass. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and behavior.
( input_ids: typing.Optional[torch.LongTensor] = Noneattention_mask: typing.Optional[torch.LongTensor] = Nonetoken_type_ids: typing.Optional[torch.LongTensor] = Noneposition_ids: typing.Optional[torch.LongTensor] = Nonehead_mask: typing.Optional[torch.LongTensor] = Noneinputs_embeds: typing.Optional[torch.FloatTensor] = Nonevisual_embeds: typing.Optional[torch.FloatTensor] = Nonevisual_attention_mask: typing.Optional[torch.LongTensor] = Nonevisual_token_type_ids: typing.Optional[torch.LongTensor] = Noneimage_text_alignment: typing.Optional[torch.LongTensor] = Noneoutput_attentions: typing.Optional[bool] = Noneoutput_hidden_states: typing.Optional[bool] = Nonereturn_dict: typing.Optional[bool] = Nonelabels: typing.Optional[torch.LongTensor] = None ) → or tuple(torch.FloatTensor)
Indices can be obtained using . See and for details.
The authors of VisualBERT set the visual_token_type_ids to 1 for all tokens.
return_dict (bool
, optional) — Whether or not to return a instead of a plain tuple.
or tuple(torch.FloatTensor)
A 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 () and inputs.
The forward method, overrides the __call__
special method.
config () — 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 the method to load the model weights.
This model inherits from . 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 subclass. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and behavior.
( input_ids: typing.Optional[torch.LongTensor] = Noneattention_mask: typing.Optional[torch.LongTensor] = Nonetoken_type_ids: typing.Optional[torch.LongTensor] = Noneposition_ids: typing.Optional[torch.LongTensor] = Nonehead_mask: typing.Optional[torch.LongTensor] = Noneinputs_embeds: typing.Optional[torch.FloatTensor] = Nonevisual_embeds: typing.Optional[torch.FloatTensor] = Nonevisual_attention_mask: typing.Optional[torch.LongTensor] = Nonevisual_token_type_ids: typing.Optional[torch.LongTensor] = Noneimage_text_alignment: typing.Optional[torch.LongTensor] = Noneoutput_attentions: typing.Optional[bool] = Noneoutput_hidden_states: typing.Optional[bool] = Nonereturn_dict: typing.Optional[bool] = Noneregion_to_phrase_position: typing.Optional[torch.LongTensor] = Nonelabels: typing.Optional[torch.LongTensor] = None ) → or tuple(torch.FloatTensor)
Indices can be obtained using . See and for details.
The authors of VisualBERT set the visual_token_type_ids to 1 for all tokens.
return_dict (bool
, optional) — Whether or not to return a instead of a plain tuple.
or tuple(torch.FloatTensor)
A 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 () and inputs.
The forward method, overrides the __call__
special method.