The LXMERT model was proposed in LXMERT: Learning Cross-Modality Encoder Representations from Transformers by Hao Tan & Mohit Bansal. It is a series of bidirectional transformer encoders (one for the vision modality, one for the language modality, and then one to fuse both modalities) pretrained using a combination of masked language modeling, visual-language text alignment, ROI-feature regression, masked visual-attribute modeling, masked visual-object modeling, and visual-question answering objectives. The pretraining consists of multiple multi-modal datasets: MSCOCO, Visual-Genome + Visual-Genome Question Answering, VQA 2.0, and GQA.
The abstract from the paper is the following:
Vision-and-language reasoning requires an understanding of visual concepts, language semantics, and, most importantly, the alignment and relationships between these two modalities. We thus propose the LXMERT (Learning Cross-Modality Encoder Representations from Transformers) framework to learn these vision-and-language connections. In LXMERT, we build a large-scale Transformer model that consists of three encoders: an object relationship encoder, a language encoder, and a cross-modality encoder. Next, to endow our model with the capability of connecting vision and language semantics, we pre-train the model with large amounts of image-and-sentence pairs, via five diverse representative pretraining tasks: masked language modeling, masked object prediction (feature regression and label classification), cross-modality matching, and image question answering. These tasks help in learning both intra-modality and cross-modality relationships. After fine-tuning from our pretrained parameters, our model achieves the state-of-the-art results on two visual question answering datasets (i.e., VQA and GQA). We also show the generalizability of our pretrained cross-modality model by adapting it to a challenging visual-reasoning task, NLVR, and improve the previous best result by 22% absolute (54% to 76%). Lastly, we demonstrate detailed ablation studies to prove that both our novel model components and pretraining strategies significantly contribute to our strong results; and also present several attention visualizations for the different encoders
This model was contributed by eltoto1219. The original code can be found here.
( vocab_size = 30522 hidden_size = 768 num_attention_heads = 12 num_qa_labels = 9500 num_object_labels = 1600 num_attr_labels = 400 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 l_layers = 9 x_layers = 5 r_layers = 5 visual_feat_dim = 2048 visual_pos_dim = 4 visual_loss_normalizer = 6.67 task_matched = True task_mask_lm = True task_obj_predict = True task_qa = True visual_obj_loss = True visual_attr_loss = True visual_feat_loss = True **kwargs )
Parameters
int
, optional, defaults to 30522) —
Vocabulary size of the LXMERT model. Defines the number of different tokens that can be represented by the
inputs_ids
passed when calling LxmertModel or TFLxmertModel. int
, optional, defaults to 768) —
Dimensionality of the encoder layers and the pooler layer. int
, optional, defaults to 12) —
Number of attention heads for each attention layer in the Transformer encoder. int
, optional, defaults to 9500) —
This represents the total number of different question answering (QA) labels there are. If using more than
one dataset with QA, the user will need to account for the total number of labels that all of the datasets
have in total. int
, optional, defaults to 1600) —
This represents the total number of semantically unique objects that lxmert will be able to classify a
pooled-object feature as belonging too. int
, optional, defaults to 400) —
This represents the total number of semantically unique attributes that lxmert will be able to classify a
pooled-object feature as possessing. int
, optional, defaults to 3072) —
Dimensionality of the “intermediate” (often named feed-forward) layer in the Transformer encoder. str
or Callable
, optional, defaults to "gelu"
) —
The non-linear activation function (function or string) in the encoder and pooler. If string, "gelu"
,
"relu"
, "silu"
and "gelu_new"
are supported. float
, optional, defaults to 0.1) —
The dropout probability for all fully connected layers in the embeddings, encoder, and pooler. float
, optional, defaults to 0.1) —
The dropout ratio for the attention probabilities. int
, optional, defaults to 512) —
The maximum sequence length that this model might ever be used with. Typically set this to something large
just in case (e.g., 512 or 1024 or 2048). int
, optional, defaults to 2) —
The vocabulary size of the token_type_ids passed into BertModel. float
, optional, defaults to 0.02) —
The standard deviation of the truncated_normal_initializer for initializing all weight matrices. float
, optional, defaults to 1e-12) —
The epsilon used by the layer normalization layers. int
, optional, defaults to 9) —
Number of hidden layers in the Transformer language encoder. int
, optional, defaults to 5) —
Number of hidden layers in the Transformer cross modality encoder. int
, optional, defaults to 5) —
Number of hidden layers in the Transformer visual encoder. int
, optional, defaults to 2048) —
This represents the last dimension of the pooled-object features used as input for the model, representing
the size of each object feature itself. int
, optional, defaults to 4) —
This represents the number of spacial features that are mixed into the visual features. The default is set
to 4 because most commonly this will represent the location of a bounding box. i.e., (x, y, width, height) float
, optional, defaults to 6.67) —
This represents the scaling factor in which each visual loss is multiplied by if during pretraining, one
decided to train with multiple vision-based loss objectives. bool
, optional, defaults to True
) —
This task is used for sentence-image matching. If the sentence correctly describes the image the label will
be 1. If the sentence does not correctly describe the image, the label will be 0. bool
, optional, defaults to True
) —
Whether or not to add masked language modeling (as used in pretraining models such as BERT) to the loss
objective. bool
, optional, defaults to True
) —
Whether or not to add object prediction, attribute prediction and feature regression to the loss objective. bool
, optional, defaults to True
) —
Whether or not to add the question-answering loss to the objective bool
, optional, defaults to True
) —
Whether or not to calculate the object-prediction loss objective bool
, optional, defaults to True
) —
Whether or not to calculate the attribute-prediction loss objective bool
, optional, defaults to True
) —
Whether or not to calculate the feature-regression loss objective This is the configuration class to store the configuration of a LxmertModel or a TFLxmertModel. It is used to instantiate a LXMERT 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 Lxmert unc-nlp/lxmert-base-uncased architecture.
Configuration objects inherit from PretrainedConfig and can be used to control the model outputs. Read the documentation from PretrainedConfig for more information.
( vocab_file do_lower_case = True do_basic_tokenize = True never_split = None unk_token = '[UNK]' sep_token = '[SEP]' pad_token = '[PAD]' cls_token = '[CLS]' mask_token = '[MASK]' tokenize_chinese_chars = True strip_accents = None **kwargs )
Parameters
str
) —
File containing the vocabulary. bool
, optional, defaults to True
) —
Whether or not to lowercase the input when tokenizing. bool
, optional, defaults to True
) —
Whether or not to do basic tokenization before WordPiece. Iterable
, optional) —
Collection of tokens which will never be split during tokenization. Only has an effect when
do_basic_tokenize=True
str
, optional, defaults to "[UNK]"
) —
The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
token instead. str
, optional, defaults to "[SEP]"
) —
The separator token, which is used when building a sequence from multiple sequences, e.g. two sequences for
sequence classification or for a text and a question for question answering. It is also used as the last
token of a sequence built with special tokens. str
, optional, defaults to "[PAD]"
) —
The token used for padding, for example when batching sequences of different lengths. str
, optional, defaults to "[CLS]"
) —
The classifier token which is used when doing sequence classification (classification of the whole sequence
instead of per-token classification). It is the first token of the sequence when built with special tokens. str
, optional, defaults to "[MASK]"
) —
The token used for masking values. This is the token used when training this model with masked language
modeling. This is the token which the model will try to predict. bool
, optional, defaults to True
) —
Whether or not to tokenize Chinese characters.
This should likely be deactivated for Japanese (see this issue).
bool
, optional) —
Whether or not to strip all accents. If this option is not specified, then it will be determined by the
value for lowercase
(as in the original Lxmert). Construct a Lxmert tokenizer. Based on WordPiece.
This tokenizer inherits from PreTrainedTokenizer which contains most of the main methods. Users should refer to this superclass for more information regarding those methods.
( token_ids_0: List token_ids_1: Optional = None ) → List[int]
Parameters
List[int]
) —
List of IDs to which the special tokens will be added. List[int]
, optional) —
Optional second list of IDs for sequence pairs. Returns
List[int]
List of input IDs with the appropriate special tokens.
Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and adding special tokens. A Lxmert sequence has the following format:
[CLS] X [SEP]
[CLS] A [SEP] B [SEP]
Converts a sequence of tokens (string) in a single string.
( token_ids_0: List token_ids_1: Optional = None ) → List[int]
Parameters
List[int]
) —
List of IDs. List[int]
, optional) —
Optional second list of IDs for sequence pairs. Returns
List[int]
List of token type IDs according to the given sequence(s).
Create a mask from the two sequences passed to be used in a sequence-pair classification task. A Lxmert sequence
pair mask has the following format:
0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1
| first sequence | second sequence |
If token_ids_1
is None
, this method only returns the first portion of the mask (0s).
( token_ids_0: List token_ids_1: Optional = None already_has_special_tokens: bool = False ) → List[int]
Parameters
List[int]
) —
List of IDs. List[int]
, optional) —
Optional second list of IDs for sequence pairs. bool
, optional, defaults to False
) —
Whether or not the token list is already formatted with special tokens for the model. Returns
List[int]
A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding
special tokens using the tokenizer prepare_for_model
method.
( vocab_file = None tokenizer_file = None do_lower_case = True unk_token = '[UNK]' sep_token = '[SEP]' pad_token = '[PAD]' cls_token = '[CLS]' mask_token = '[MASK]' tokenize_chinese_chars = True strip_accents = None **kwargs )
Parameters
str
) —
File containing the vocabulary. bool
, optional, defaults to True
) —
Whether or not to lowercase the input when tokenizing. str
, optional, defaults to "[UNK]"
) —
The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
token instead. str
, optional, defaults to "[SEP]"
) —
The separator token, which is used when building a sequence from multiple sequences, e.g. two sequences for
sequence classification or for a text and a question for question answering. It is also used as the last
token of a sequence built with special tokens. str
, optional, defaults to "[PAD]"
) —
The token used for padding, for example when batching sequences of different lengths. str
, optional, defaults to "[CLS]"
) —
The classifier token which is used when doing sequence classification (classification of the whole sequence
instead of per-token classification). It is the first token of the sequence when built with special tokens. str
, optional, defaults to "[MASK]"
) —
The token used for masking values. This is the token used when training this model with masked language
modeling. This is the token which the model will try to predict. bool
, optional, defaults to True
) —
Whether or not to clean the text before tokenization by removing any control characters and replacing all
whitespaces by the classic one. bool
, optional, defaults to True
) —
Whether or not to tokenize Chinese characters. This should likely be deactivated for Japanese (see this
issue). bool
, optional) —
Whether or not to strip all accents. If this option is not specified, then it will be determined by the
value for lowercase
(as in the original Lxmert). str
, optional, defaults to "##"
) —
The prefix for subwords. Construct a “fast” Lxmert tokenizer (backed by HuggingFace’s tokenizers library). Based on WordPiece.
This tokenizer inherits from PreTrainedTokenizerFast which contains most of the main methods. Users should refer to this superclass for more information regarding those methods.
( token_ids_0 token_ids_1 = None ) → List[int]
Parameters
List[int]
) —
List of IDs to which the special tokens will be added. List[int]
, optional) —
Optional second list of IDs for sequence pairs. Returns
List[int]
List of input IDs with the appropriate special tokens.
Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and adding special tokens. A Lxmert sequence has the following format:
[CLS] X [SEP]
[CLS] A [SEP] B [SEP]
( token_ids_0: List token_ids_1: Optional = None ) → List[int]
Parameters
List[int]
) —
List of IDs. List[int]
, optional) —
Optional second list of IDs for sequence pairs. Returns
List[int]
List of token type IDs according to the given sequence(s).
Create a mask from the two sequences passed to be used in a sequence-pair classification task. A Lxmert sequence
pair mask has the following format:
0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1
| first sequence | second sequence |
If token_ids_1
is None
, this method only returns the first portion of the mask (0s).
( language_output: Optional = None vision_output: Optional = None pooled_output: Optional = None language_hidden_states: Optional = None vision_hidden_states: Optional = None language_attentions: Optional = None vision_attentions: Optional = None cross_encoder_attentions: Optional = None )
Parameters
torch.FloatTensor
of shape (batch_size, sequence_length, hidden_size)
) —
Sequence of hidden-states at the output of the last layer of the language encoder. torch.FloatTensor
of shape (batch_size, sequence_length, hidden_size)
) —
Sequence of hidden-states at the output of the last layer of the visual encoder. torch.FloatTensor
of shape (batch_size, hidden_size)
) —
Last layer hidden-state of the first token of the sequence (classification, CLS, token) further processed
by a Linear layer and a Tanh activation function. The Linear 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 input features + one for the output of each cross-modality layer) of
shape (batch_size, sequence_length, hidden_size)
. 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 input features + one for the output of each cross-modality layer) of
shape (batch_size, sequence_length, hidden_size)
. 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. 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. 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. Lxmert’s outputs that contain the last hidden states, pooled outputs, and attention probabilities for the language, visual, and, cross-modality encoders. (note: the visual encoder in Lxmert is referred to as the “relation-ship” encoder”)
( loss: Optional = None prediction_logits: Optional = None cross_relationship_score: Optional = None question_answering_score: Optional = None language_hidden_states: Optional = None vision_hidden_states: Optional = None language_attentions: Optional = None vision_attentions: Optional = None cross_encoder_attentions: Optional = None )
Parameters
labels
is provided, torch.FloatTensor
of shape (1,)
) —
Total loss as the sum of the masked language modeling loss and the next sequence prediction
(classification) loss. 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). torch.FloatTensor
of shape (batch_size, 2)
) —
Prediction scores of the textual matching objective (classification) head (scores of True/False
continuation before SoftMax). torch.FloatTensor
of shape (batch_size, n_qa_answers)
) —
Prediction scores of question answering objective (classification). 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 input features + one for the output of each cross-modality layer) of
shape (batch_size, sequence_length, hidden_size)
. 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 input features + one for the output of each cross-modality layer) of
shape (batch_size, sequence_length, hidden_size)
. 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. 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. 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. Output type of LxmertForPreTraining.
( loss: Optional = None question_answering_score: Optional = None language_hidden_states: Optional = None vision_hidden_states: Optional = None language_attentions: Optional = None vision_attentions: Optional = None cross_encoder_attentions: Optional = None )
Parameters
labels
is provided, torch.FloatTensor
of shape (1,)
) —
Total loss as the sum of the masked language modeling loss and the next sequence prediction
(classification) loss.k. torch.FloatTensor
of shape (batch_size, n_qa_answers)
, optional) —
Prediction scores of question answering objective (classification). 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 input features + one for the output of each cross-modality layer) of
shape (batch_size, sequence_length, hidden_size)
. 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 input features + one for the output of each cross-modality layer) of
shape (batch_size, sequence_length, hidden_size)
. 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. 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. 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. Output type of LxmertForQuestionAnswering.
( language_output: tf.Tensor | None = None vision_output: tf.Tensor | None = None pooled_output: tf.Tensor | None = None language_hidden_states: Tuple[tf.Tensor] | None = None vision_hidden_states: Tuple[tf.Tensor] | None = None language_attentions: Tuple[tf.Tensor] | None = None vision_attentions: Tuple[tf.Tensor] | None = None cross_encoder_attentions: Tuple[tf.Tensor] | None = None )
Parameters
tf.Tensor
of shape (batch_size, sequence_length, hidden_size)
) —
Sequence of hidden-states at the output of the last layer of the language encoder. tf.Tensor
of shape (batch_size, sequence_length, hidden_size)
) —
Sequence of hidden-states at the output of the last layer of the visual encoder. tf.Tensor
of shape (batch_size, hidden_size)
) —
Last layer hidden-state of the first token of the sequence (classification, CLS, token) further processed
by a Linear layer and a Tanh activation function. The Linear tuple(tf.Tensor)
, optional, returned when output_hidden_states=True
is passed or when config.output_hidden_states=True
) —
Tuple of tf.Tensor
(one for input features + one for the output of each cross-modality layer) of shape
(batch_size, sequence_length, hidden_size)
. tuple(tf.Tensor)
, optional, returned when output_hidden_states=True
is passed or when config.output_hidden_states=True
) —
Tuple of tf.Tensor
(one for input features + one for the output of each cross-modality layer) of shape
(batch_size, sequence_length, hidden_size)
. tuple(tf.Tensor)
, optional, returned when output_attentions=True
is passed or when config.output_attentions=True
) —
Tuple of tf.Tensor
(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. tuple(tf.Tensor)
, optional, returned when output_attentions=True
is passed or when config.output_attentions=True
) —
Tuple of tf.Tensor
(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. tuple(tf.Tensor)
, optional, returned when output_attentions=True
is passed or when config.output_attentions=True
) —
Tuple of tf.Tensor
(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. Lxmert’s outputs that contain the last hidden states, pooled outputs, and attention probabilities for the language, visual, and, cross-modality encoders. (note: the visual encoder in Lxmert is referred to as the “relation-ship” encoder”)
( loss: tf.Tensor | None = None prediction_logits: tf.Tensor | None = None cross_relationship_score: tf.Tensor | None = None question_answering_score: tf.Tensor | None = None language_hidden_states: Tuple[tf.Tensor] | None = None vision_hidden_states: Tuple[tf.Tensor] | None = None language_attentions: Tuple[tf.Tensor] | None = None vision_attentions: Tuple[tf.Tensor] | None = None cross_encoder_attentions: Tuple[tf.Tensor] | None = None )
Parameters
labels
is provided, tf.Tensor
of shape (1,)
) —
Total loss as the sum of the masked language modeling loss and the next sequence prediction
(classification) loss. tf.Tensor
of shape (batch_size, sequence_length, config.vocab_size)
) —
Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax). tf.Tensor
of shape (batch_size, 2)
) —
Prediction scores of the textual matching objective (classification) head (scores of True/False
continuation before SoftMax). tf.Tensor
of shape (batch_size, n_qa_answers)
) —
Prediction scores of question answering objective (classification). tuple(tf.Tensor)
, optional, returned when output_hidden_states=True
is passed or when config.output_hidden_states=True
) —
Tuple of tf.Tensor
(one for input features + one for the output of each cross-modality layer) of shape
(batch_size, sequence_length, hidden_size)
. tuple(tf.Tensor)
, optional, returned when output_hidden_states=True
is passed or when config.output_hidden_states=True
) —
Tuple of tf.Tensor
(one for input features + one for the output of each cross-modality layer) of shape
(batch_size, sequence_length, hidden_size)
. tuple(tf.Tensor)
, optional, returned when output_attentions=True
is passed or when config.output_attentions=True
) —
Tuple of tf.Tensor
(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. tuple(tf.Tensor)
, optional, returned when output_attentions=True
is passed or when config.output_attentions=True
) —
Tuple of tf.Tensor
(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. tuple(tf.Tensor)
, optional, returned when output_attentions=True
is passed or when config.output_attentions=True
) —
Tuple of tf.Tensor
(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. Output type of LxmertForPreTraining.
( config )
Parameters
The bare Lxmert Model transformer outputting raw hidden-states without any specific head on top.
The LXMERT model was proposed in LXMERT: Learning Cross-Modality Encoder Representations from Transformers by Hao Tan and Mohit Bansal. It’s a vision and language transformer model, pretrained on a variety of multi-modal datasets comprising of GQA, VQAv2.0, MSCOCO captions, and Visual genome, using a combination of masked language modeling, region of interest feature regression, cross entropy loss for question answering attribute prediction, and object tag prediction.
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.
( input_ids: Optional = None visual_feats: Optional = None visual_pos: Optional = None attention_mask: Optional = None visual_attention_mask: Optional = None token_type_ids: Optional = None inputs_embeds: Optional = None output_attentions: Optional = None output_hidden_states: Optional = None return_dict: Optional = None ) → transformers.models.lxmert.modeling_lxmert.LxmertModelOutput or tuple(torch.FloatTensor)
Parameters
torch.LongTensor
of shape (batch_size, sequence_length)
) —
Indices of input sequence tokens in the vocabulary.
Indices can be obtained using AutoTokenizer. See PreTrainedTokenizer.encode() and PreTrainedTokenizer.call() for details.
torch.FloatTensor
of shape (batch_size, num_visual_features, visual_feat_dim)
) —
This input represents visual features. They ROI pooled object features from bounding boxes using a
faster-RCNN model)
These are currently not provided by the transformers library.
torch.FloatTensor
of shape (batch_size, num_visual_features, visual_pos_dim)
) —
This input represents spacial features corresponding to their relative (via index) visual features. The
pre-trained LXMERT model expects these spacial features to be normalized bounding boxes on a scale of 0 to
These are currently not provided by the transformers library.
torch.FloatTensor
of shape (batch_size, sequence_length)
, optional) —
Mask to avoid performing attention on padding token indices. Mask values selected in [0, 1]
:
torch.FloatTensor
of shape (batch_size, sequence_length)
, optional) —
Mask to avoid performing attention on padding token indices. Mask values selected in [0, 1]
:
torch.LongTensor
of shape (batch_size, sequence_length)
, optional) —
Segment token indices to indicate first and second portions of the inputs. Indices are selected in [0, 1]
:
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. bool
, optional) —
Whether or not to return the attentions tensors of all attention layers. See attentions
under returned
tensors for more detail. bool
, optional) —
Whether or not to return the hidden states of all layers. See hidden_states
under returned tensors for
more detail. bool
, optional) —
Whether or not to return a ModelOutput instead of a plain tuple. Returns
transformers.models.lxmert.modeling_lxmert.LxmertModelOutput or tuple(torch.FloatTensor)
A transformers.models.lxmert.modeling_lxmert.LxmertModelOutput 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 (LxmertConfig) and inputs.
torch.FloatTensor
of shape (batch_size, sequence_length, hidden_size)
) — Sequence of hidden-states at the output of the last layer of the language encoder.torch.FloatTensor
of shape (batch_size, sequence_length, hidden_size)
) — Sequence of hidden-states at the output of the last layer of the visual encoder.torch.FloatTensor
of shape (batch_size, hidden_size)
) — Last layer hidden-state of the first token of the sequence (classification, CLS, token) further processed
by a Linear layer and a Tanh activation function. The Lineartuple(torch.FloatTensor)
, optional, returned when output_hidden_states=True
is passed or when config.output_hidden_states=True
) — Tuple of torch.FloatTensor
(one for input features + one for the output of each cross-modality layer) of
shape (batch_size, sequence_length, hidden_size)
.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 input features + one for the output of each cross-modality layer) of
shape (batch_size, sequence_length, hidden_size)
.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.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.tuple(torch.FloatTensor)
, optional, returned when output_attentions=True
is passed or when config.output_attentions=True
) — Tuple of torch.FloatTensor
(one for each layer) of shape (batch_size, num_heads, sequence_length, sequence_length)
. Attentions weights after the attention softmax, used to compute the weighted average in
the self-attention heads.The LxmertModel forward method, overrides the __call__
special method.
Although the recipe for forward pass needs to be defined within this function, one should call the Module
instance afterwards instead of this since the former takes care of running the pre and post processing steps while
the latter silently ignores them.
Example:
>>> from transformers import AutoTokenizer, LxmertModel
>>> import torch
>>> tokenizer = AutoTokenizer.from_pretrained("unc-nlp/lxmert-base-uncased")
>>> model = LxmertModel.from_pretrained("unc-nlp/lxmert-base-uncased")
>>> inputs = tokenizer("Hello, my dog is cute", return_tensors="pt")
>>> outputs = model(**inputs)
>>> last_hidden_states = outputs.last_hidden_state
( config )
Parameters
Lxmert Model with a specified pretraining head on top.
The LXMERT model was proposed in LXMERT: Learning Cross-Modality Encoder Representations from Transformers by Hao Tan and Mohit Bansal. It’s a vision and language transformer model, pretrained on a variety of multi-modal datasets comprising of GQA, VQAv2.0, MSCOCO captions, and Visual genome, using a combination of masked language modeling, region of interest feature regression, cross entropy loss for question answering attribute prediction, and object tag prediction.
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.
( input_ids: Optional = None visual_feats: Optional = None visual_pos: Optional = None attention_mask: Optional = None visual_attention_mask: Optional = None token_type_ids: Optional = None inputs_embeds: Optional = None labels: Optional = None obj_labels: Optional = None matched_label: Optional = None ans: Optional = None output_attentions: Optional = None output_hidden_states: Optional = None return_dict: Optional = None **kwargs ) → transformers.models.lxmert.modeling_lxmert.LxmertForPreTrainingOutput or tuple(torch.FloatTensor)
Parameters
torch.LongTensor
of shape (batch_size, sequence_length)
) —
Indices of input sequence tokens in the vocabulary.
Indices can be obtained using AutoTokenizer. See PreTrainedTokenizer.encode() and PreTrainedTokenizer.call() for details.
torch.FloatTensor
of shape (batch_size, num_visual_features, visual_feat_dim)
) —
This input represents visual features. They ROI pooled object features from bounding boxes using a
faster-RCNN model)
These are currently not provided by the transformers library.
torch.FloatTensor
of shape (batch_size, num_visual_features, visual_pos_dim)
) —
This input represents spacial features corresponding to their relative (via index) visual features. The
pre-trained LXMERT model expects these spacial features to be normalized bounding boxes on a scale of 0 to
These are currently not provided by the transformers library.
torch.FloatTensor
of shape (batch_size, sequence_length)
, optional) —
Mask to avoid performing attention on padding token indices. Mask values selected in [0, 1]
:
torch.FloatTensor
of shape (batch_size, sequence_length)
, optional) —
Mask to avoid performing attention on padding token indices. Mask values selected in [0, 1]
:
torch.LongTensor
of shape (batch_size, sequence_length)
, optional) —
Segment token indices to indicate first and second portions of the inputs. Indices are selected in [0, 1]
:
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. bool
, optional) —
Whether or not to return the attentions tensors of all attention layers. See attentions
under returned
tensors for more detail. bool
, optional) —
Whether or not to return the hidden states of all layers. See hidden_states
under returned tensors for
more detail. bool
, optional) —
Whether or not to return a ModelOutput instead of a plain tuple. torch.LongTensor
of shape (batch_size, 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]
Dict[Str -- Tuple[Torch.FloatTensor, Torch.FloatTensor]]
, optional):
each key is named after each one of the visual losses and each element of the tuple is of the shape
(batch_size, num_features)
and (batch_size, num_features, visual_feature_dim)
for each the label id and
the label score respectively torch.LongTensor
of shape (batch_size,)
, optional) —
Labels for computing the whether or not the text input matches the image (classification) loss. Input
should be a sequence pair (see input_ids
docstring) Indices should be in [0, 1]
:
Torch.Tensor
of shape (batch_size)
, optional) —
a one hot representation hof the correct answer optional Returns
transformers.models.lxmert.modeling_lxmert.LxmertForPreTrainingOutput or tuple(torch.FloatTensor)
A transformers.models.lxmert.modeling_lxmert.LxmertForPreTrainingOutput 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 (LxmertConfig) and inputs.
labels
is provided, torch.FloatTensor
of shape (1,)
) — Total loss as the sum of the masked language modeling loss and the next sequence prediction
(classification) loss.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).torch.FloatTensor
of shape (batch_size, 2)
) — Prediction scores of the textual matching objective (classification) head (scores of True/False
continuation before SoftMax).torch.FloatTensor
of shape (batch_size, n_qa_answers)
) — Prediction scores of question answering objective (classification).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 input features + one for the output of each cross-modality layer) of
shape (batch_size, sequence_length, hidden_size)
.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 input features + one for the output of each cross-modality layer) of
shape (batch_size, sequence_length, hidden_size)
.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.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.tuple(torch.FloatTensor)
, optional, returned when output_attentions=True
is passed or when config.output_attentions=True
) — Tuple of torch.FloatTensor
(one for each layer) of shape (batch_size, num_heads, sequence_length, sequence_length)
. Attentions weights after the attention softmax, used to compute the weighted average in
the self-attention heads.The LxmertForPreTraining forward method, overrides the __call__
special method.
Although the recipe for forward pass needs to be defined within this function, one should call the Module
instance afterwards instead of this since the former takes care of running the pre and post processing steps while
the latter silently ignores them.
( config )
Parameters
Lxmert Model with a visual-answering head on top for downstream QA tasks
The LXMERT model was proposed in LXMERT: Learning Cross-Modality Encoder Representations from Transformers by Hao Tan and Mohit Bansal. It’s a vision and language transformer model, pretrained on a variety of multi-modal datasets comprising of GQA, VQAv2.0, MSCOCO captions, and Visual genome, using a combination of masked language modeling, region of interest feature regression, cross entropy loss for question answering attribute prediction, and object tag prediction.
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.
( input_ids: Optional = None visual_feats: Optional = None visual_pos: Optional = None attention_mask: Optional = None visual_attention_mask: Optional = None token_type_ids: Optional = None inputs_embeds: Optional = None labels: Optional = None output_attentions: Optional = None output_hidden_states: Optional = None return_dict: Optional = None ) → transformers.models.lxmert.modeling_lxmert.LxmertForQuestionAnsweringOutput or tuple(torch.FloatTensor)
Parameters
torch.LongTensor
of shape (batch_size, sequence_length)
) —
Indices of input sequence tokens in the vocabulary.
Indices can be obtained using AutoTokenizer. See PreTrainedTokenizer.encode() and PreTrainedTokenizer.call() for details.
torch.FloatTensor
of shape (batch_size, num_visual_features, visual_feat_dim)
) —
This input represents visual features. They ROI pooled object features from bounding boxes using a
faster-RCNN model)
These are currently not provided by the transformers library.
torch.FloatTensor
of shape (batch_size, num_visual_features, visual_pos_dim)
) —
This input represents spacial features corresponding to their relative (via index) visual features. The
pre-trained LXMERT model expects these spacial features to be normalized bounding boxes on a scale of 0 to
These are currently not provided by the transformers library.
torch.FloatTensor
of shape (batch_size, sequence_length)
, optional) —
Mask to avoid performing attention on padding token indices. Mask values selected in [0, 1]
:
torch.FloatTensor
of shape (batch_size, sequence_length)
, optional) —
Mask to avoid performing attention on padding token indices. Mask values selected in [0, 1]
:
torch.LongTensor
of shape (batch_size, sequence_length)
, optional) —
Segment token indices to indicate first and second portions of the inputs. Indices are selected in [0, 1]
:
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. bool
, optional) —
Whether or not to return the attentions tensors of all attention layers. See attentions
under returned
tensors for more detail. bool
, optional) —
Whether or not to return the hidden states of all layers. See hidden_states
under returned tensors for
more detail. bool
, optional) —
Whether or not to return a ModelOutput instead of a plain tuple. Torch.Tensor
of shape (batch_size)
, optional) —
A one-hot representation of the correct answer Returns
transformers.models.lxmert.modeling_lxmert.LxmertForQuestionAnsweringOutput or tuple(torch.FloatTensor)
A transformers.models.lxmert.modeling_lxmert.LxmertForQuestionAnsweringOutput 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 (LxmertConfig) and inputs.
labels
is provided, torch.FloatTensor
of shape (1,)
) — Total loss as the sum of the masked language modeling loss and the next sequence prediction
(classification) loss.k.torch.FloatTensor
of shape (batch_size, n_qa_answers)
, optional) — Prediction scores of question answering objective (classification).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 input features + one for the output of each cross-modality layer) of
shape (batch_size, sequence_length, hidden_size)
.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 input features + one for the output of each cross-modality layer) of
shape (batch_size, sequence_length, hidden_size)
.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.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.tuple(torch.FloatTensor)
, optional, returned when output_attentions=True
is passed or when config.output_attentions=True
) — Tuple of torch.FloatTensor
(one for each layer) of shape (batch_size, num_heads, sequence_length, sequence_length)
. Attentions weights after the attention softmax, used to compute the weighted average in
the self-attention heads.The LxmertForQuestionAnswering forward method, overrides the __call__
special method.
Although the recipe for forward pass needs to be defined within this function, one should call the Module
instance afterwards instead of this since the former takes care of running the pre and post processing steps while
the latter silently ignores them.
Example:
>>> from transformers import AutoTokenizer, LxmertForQuestionAnswering
>>> import torch
>>> tokenizer = AutoTokenizer.from_pretrained("unc-nlp/lxmert-base-uncased")
>>> model = LxmertForQuestionAnswering.from_pretrained("unc-nlp/lxmert-base-uncased")
>>> question, text = "Who was Jim Henson?", "Jim Henson was a nice puppet"
>>> inputs = tokenizer(question, text, return_tensors="pt")
>>> with torch.no_grad():
... outputs = model(**inputs)
>>> answer_start_index = outputs.start_logits.argmax()
>>> answer_end_index = outputs.end_logits.argmax()
>>> predict_answer_tokens = inputs.input_ids[0, answer_start_index : answer_end_index + 1]
>>> # target is "nice puppet"
>>> target_start_index = torch.tensor([14])
>>> target_end_index = torch.tensor([15])
>>> outputs = model(**inputs, start_positions=target_start_index, end_positions=target_end_index)
>>> loss = outputs.loss
( config *inputs **kwargs )
Parameters
The bare Lxmert Model transformer outputting raw hidden-states without any specific head on top.
The LXMERT model was proposed in LXMERT: Learning Cross-Modality Encoder Representations from Transformers by Hao Tan and Mohit Bansal. It’s a vision and language transformer model, pre-trained on a variety of multi-modal datasets comprising of GQA, VQAv2.0, MCSCOCO captions, and Visual genome, using a combination of masked language modeling, region of interest feature regression, cross entropy loss for question answering attribute prediction, and object tag prediction.
This model is also a keras.Model subclass. Use it as a regular TF 2.0 Keras Model and refer to the TF 2.0 documentation for all matter related to general usage and behavior.
TensorFlow models and layers in transformers
accept two formats as input:
The reason the second format is supported is that Keras methods prefer this format when passing inputs to models
and layers. Because of this support, when using methods like model.fit()
things should “just work” for you - just
pass your inputs and labels in any format that model.fit()
supports! If, however, you want to use the second
format outside of Keras methods like fit()
and predict()
, such as when creating your own layers or models with
the Keras Functional
API, there are three possibilities you can use to gather all the input Tensors in the first
positional argument:
input_ids
only and nothing else: model(input_ids)
model([input_ids, attention_mask])
or model([input_ids, attention_mask, token_type_ids])
model({"input_ids": input_ids, "token_type_ids": token_type_ids})
Note that when creating models and layers with subclassing then you don’t need to worry about any of this, as you can just pass inputs like you would to any other Python function!
( input_ids: TFModelInputType | None = None visual_feats: tf.Tensor | None = None visual_pos: tf.Tensor | None = None attention_mask: np.ndarray | tf.Tensor | None = None visual_attention_mask: np.ndarray | tf.Tensor | None = None token_type_ids: np.ndarray | tf.Tensor | None = None inputs_embeds: np.ndarray | tf.Tensor | None = None output_attentions: Optional[bool] = None output_hidden_states: Optional[bool] = None return_dict: Optional[bool] = None training: bool = False ) → transformers.models.lxmert.modeling_tf_lxmert.TFLxmertModelOutput or tuple(tf.Tensor)
Parameters
np.ndarray
or tf.Tensor
of shape (batch_size, sequence_length)
) —
Indices of input sequence tokens in the vocabulary.
Indices can be obtained using AutoTokenizer. See PreTrainedTokenizer.call() and PreTrainedTokenizer.encode() for details.
tf.Tensor
of shape (batch_size, num_visual_features, visual_feat_dim)
) —
This input represents visual features. They ROI pooled object features from bounding boxes using a
faster-RCNN model)
These are currently not provided by the transformers library.
tf.Tensor
of shape (batch_size, num_visual_features, visual_feat_dim)
) —
This input represents spacial features corresponding to their relative (via index) visual features. The
pre-trained LXMERT model expects these spacial features to be normalized bounding boxes on a scale of 0 to
These are currently not provided by the transformers library.
tf.Tensor
of shape (batch_size, sequence_length)
, optional) —
Mask to avoid performing attention on padding token indices. Mask values selected in [0, 1]
:
tf.Tensor
of shape (batch_size, sequence_length)
, optional) —
MMask to avoid performing attention on padding token indices. Mask values selected in [0, 1]
:
tf.Tensor
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]
:
tf.Tensor
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. bool
, optional) —
Whether or not to return the attentions tensors of all attention layers. See attentions
under returned
tensors for more detail. This argument can be used only in eager mode, in graph mode the value in the
config will be used instead. bool
, optional) —
Whether or not to return the hidden states of all layers. See hidden_states
under returned tensors for
more detail. This argument can be used only in eager mode, in graph mode the value in the config will be
used instead. bool
, optional) —
Whether or not to return a ModelOutput instead of a plain tuple. This argument can be used in
eager mode, in graph mode the value will always be set to True. bool
, optional, defaults to False
) —
Whether or not to use the model in training mode (some modules like dropout modules have different
behaviors between training and evaluation). Returns
transformers.models.lxmert.modeling_tf_lxmert.TFLxmertModelOutput or tuple(tf.Tensor)
A transformers.models.lxmert.modeling_tf_lxmert.TFLxmertModelOutput or a tuple of tf.Tensor
(if
return_dict=False
is passed or when config.return_dict=False
) comprising various elements depending on the
configuration (LxmertConfig) and inputs.
tf.Tensor
of shape (batch_size, sequence_length, hidden_size)
) — Sequence of hidden-states at the output of the last layer of the language encoder.tf.Tensor
of shape (batch_size, sequence_length, hidden_size)
) — Sequence of hidden-states at the output of the last layer of the visual encoder.tf.Tensor
of shape (batch_size, hidden_size)
) — Last layer hidden-state of the first token of the sequence (classification, CLS, token) further processed
by a Linear layer and a Tanh activation function. The Lineartuple(tf.Tensor)
, optional, returned when output_hidden_states=True
is passed or when config.output_hidden_states=True
) — Tuple of tf.Tensor
(one for input features + one for the output of each cross-modality layer) of shape
(batch_size, sequence_length, hidden_size)
.tuple(tf.Tensor)
, optional, returned when output_hidden_states=True
is passed or when config.output_hidden_states=True
) — Tuple of tf.Tensor
(one for input features + one for the output of each cross-modality layer) of shape
(batch_size, sequence_length, hidden_size)
.tuple(tf.Tensor)
, optional, returned when output_attentions=True
is passed or when config.output_attentions=True
) — Tuple of tf.Tensor
(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.tuple(tf.Tensor)
, optional, returned when output_attentions=True
is passed or when config.output_attentions=True
) — Tuple of tf.Tensor
(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.tuple(tf.Tensor)
, optional, returned when output_attentions=True
is passed or when config.output_attentions=True
) — Tuple of tf.Tensor
(one for each layer) of shape (batch_size, num_heads, sequence_length, sequence_length)
. Attentions weights after the attention softmax, used to compute the weighted average in
the self-attention heads.The TFLxmertModel forward method, overrides the __call__
special method.
Although the recipe for forward pass needs to be defined within this function, one should call the Module
instance afterwards instead of this since the former takes care of running the pre and post processing steps while
the latter silently ignores them.
Example:
>>> from transformers import AutoTokenizer, TFLxmertModel
>>> import tensorflow as tf
>>> tokenizer = AutoTokenizer.from_pretrained("unc-nlp/lxmert-base-uncased")
>>> model = TFLxmertModel.from_pretrained("unc-nlp/lxmert-base-uncased")
>>> inputs = tokenizer("Hello, my dog is cute", return_tensors="tf")
>>> outputs = model(inputs)
>>> last_hidden_states = outputs.last_hidden_state
( config *inputs **kwargs )
Parameters
Lxmert Model with a language modeling
head on top.
The LXMERT model was proposed in LXMERT: Learning Cross-Modality Encoder Representations from Transformers by Hao Tan and Mohit Bansal. It’s a vision and language transformer model, pre-trained on a variety of multi-modal datasets comprising of GQA, VQAv2.0, MCSCOCO captions, and Visual genome, using a combination of masked language modeling, region of interest feature regression, cross entropy loss for question answering attribute prediction, and object tag prediction.
This model is also a keras.Model subclass. Use it as a regular TF 2.0 Keras Model and refer to the TF 2.0 documentation for all matter related to general usage and behavior.
TensorFlow models and layers in transformers
accept two formats as input:
The reason the second format is supported is that Keras methods prefer this format when passing inputs to models
and layers. Because of this support, when using methods like model.fit()
things should “just work” for you - just
pass your inputs and labels in any format that model.fit()
supports! If, however, you want to use the second
format outside of Keras methods like fit()
and predict()
, such as when creating your own layers or models with
the Keras Functional
API, there are three possibilities you can use to gather all the input Tensors in the first
positional argument:
input_ids
only and nothing else: model(input_ids)
model([input_ids, attention_mask])
or model([input_ids, attention_mask, token_type_ids])
model({"input_ids": input_ids, "token_type_ids": token_type_ids})
Note that when creating models and layers with subclassing then you don’t need to worry about any of this, as you can just pass inputs like you would to any other Python function!
( input_ids: TFModelInputType | None = None visual_feats: tf.Tensor | None = None visual_pos: tf.Tensor | None = None attention_mask: tf.Tensor | None = None visual_attention_mask: tf.Tensor | None = None token_type_ids: tf.Tensor | None = None inputs_embeds: tf.Tensor | None = None masked_lm_labels: tf.Tensor | None = None obj_labels: Dict[str, Tuple[tf.Tensor, tf.Tensor]] | None = None matched_label: tf.Tensor | None = None ans: tf.Tensor | None = None output_attentions: bool | None = None output_hidden_states: bool | None = None return_dict: bool | None = None training: bool = False ) → transformers.models.lxmert.modeling_tf_lxmert.TFLxmertForPreTrainingOutput or tuple(tf.Tensor)
Parameters
np.ndarray
or tf.Tensor
of shape (batch_size, sequence_length)
) —
Indices of input sequence tokens in the vocabulary.
Indices can be obtained using AutoTokenizer. See PreTrainedTokenizer.call() and PreTrainedTokenizer.encode() for details.
tf.Tensor
of shape (batch_size, num_visual_features, visual_feat_dim)
) —
This input represents visual features. They ROI pooled object features from bounding boxes using a
faster-RCNN model)
These are currently not provided by the transformers library.
tf.Tensor
of shape (batch_size, num_visual_features, visual_feat_dim)
) —
This input represents spacial features corresponding to their relative (via index) visual features. The
pre-trained LXMERT model expects these spacial features to be normalized bounding boxes on a scale of 0 to
These are currently not provided by the transformers library.
tf.Tensor
of shape (batch_size, sequence_length)
, optional) —
Mask to avoid performing attention on padding token indices. Mask values selected in [0, 1]
:
tf.Tensor
of shape (batch_size, sequence_length)
, optional) —
MMask to avoid performing attention on padding token indices. Mask values selected in [0, 1]
:
tf.Tensor
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]
:
tf.Tensor
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. bool
, optional) —
Whether or not to return the attentions tensors of all attention layers. See attentions
under returned
tensors for more detail. This argument can be used only in eager mode, in graph mode the value in the
config will be used instead. bool
, optional) —
Whether or not to return the hidden states of all layers. See hidden_states
under returned tensors for
more detail. This argument can be used only in eager mode, in graph mode the value in the config will be
used instead. bool
, optional) —
Whether or not to return a ModelOutput instead of a plain tuple. This argument can be used in
eager mode, in graph mode the value will always be set to True. bool
, optional, defaults to False
) —
Whether or not to use the model in training mode (some modules like dropout modules have different
behaviors between training and evaluation). tf.Tensor
of shape (batch_size, 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]
Dict[Str -- Tuple[tf.Tensor, tf.Tensor]]
, optional, defaults to None
):
each key is named after each one of the visual losses and each element of the tuple is of the shape
(batch_size, num_features)
and (batch_size, num_features, visual_feature_dim)
for each the label id and
the label score respectively tf.Tensor
of shape (batch_size,)
, optional) —
Labels for computing the whether or not the text input matches the image (classification) loss. Input
should be a sequence pair (see input_ids
docstring) Indices should be in [0, 1]
:
tf.Tensor
of shape (batch_size)
, optional, defaults to None
) —
a one hot representation hof the correct answer optional Returns
transformers.models.lxmert.modeling_tf_lxmert.TFLxmertForPreTrainingOutput or tuple(tf.Tensor)
A transformers.models.lxmert.modeling_tf_lxmert.TFLxmertForPreTrainingOutput or a tuple of tf.Tensor
(if
return_dict=False
is passed or when config.return_dict=False
) comprising various elements depending on the
configuration (LxmertConfig) and inputs.
labels
is provided, tf.Tensor
of shape (1,)
) — Total loss as the sum of the masked language modeling loss and the next sequence prediction
(classification) loss.tf.Tensor
of shape (batch_size, sequence_length, config.vocab_size)
) — Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).tf.Tensor
of shape (batch_size, 2)
) — Prediction scores of the textual matching objective (classification) head (scores of True/False
continuation before SoftMax).tf.Tensor
of shape (batch_size, n_qa_answers)
) — Prediction scores of question answering objective (classification).tuple(tf.Tensor)
, optional, returned when output_hidden_states=True
is passed or when config.output_hidden_states=True
) — Tuple of tf.Tensor
(one for input features + one for the output of each cross-modality layer) of shape
(batch_size, sequence_length, hidden_size)
.tuple(tf.Tensor)
, optional, returned when output_hidden_states=True
is passed or when config.output_hidden_states=True
) — Tuple of tf.Tensor
(one for input features + one for the output of each cross-modality layer) of shape
(batch_size, sequence_length, hidden_size)
.tuple(tf.Tensor)
, optional, returned when output_attentions=True
is passed or when config.output_attentions=True
) — Tuple of tf.Tensor
(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.tuple(tf.Tensor)
, optional, returned when output_attentions=True
is passed or when config.output_attentions=True
) — Tuple of tf.Tensor
(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.tuple(tf.Tensor)
, optional, returned when output_attentions=True
is passed or when config.output_attentions=True
) — Tuple of tf.Tensor
(one for each layer) of shape (batch_size, num_heads, sequence_length, sequence_length)
. Attentions weights after the attention softmax, used to compute the weighted average in
the self-attention heads.The TFLxmertForPreTraining forward method, overrides the __call__
special method.
Although the recipe for forward pass needs to be defined within this function, one should call the Module
instance afterwards instead of this since the former takes care of running the pre and post processing steps while
the latter silently ignores them.