LXMERTΒΆ
OverviewΒΆ
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) pre-trained 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 pre-training 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
Tips:
Bounding boxes are not necessary to be used in the visual feature embeddings, any kind of visual-spacial features will work.
Both the language hidden states and the visual hidden states that LXMERT outputs are passed through the cross-modality layer, so they contain information from both modalities. To access a modality that only attends to itself, select the vision/language hidden states from the first input in the tuple.
The bi-directional cross-modality encoder attention only returns attention values when the language modality is used as the input and the vision modality is used as the context vector. Further, while the cross-modality encoder contains self-attention for each respective modality and cross-attention, only the cross attention is returned and both self attention outputs are disregarded.
The code can be found here
LxmertConfigΒΆ
-
class
transformers.
LxmertConfig
(vocab_size=30522, hidden_size=768, num_attention_heads=12, num_labels=2, 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, pad_token_id=0, 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, output_attentions=False, output_hidden_states=False, **kwargs)[source]ΒΆ This is the configuration class to store the configuration of a
BertModel
. It is used to instantiate an Lxmert model according to the specified arguments, defining the model architecture.- Parameters
vocab_size (
int
, optional, defaults to 30522) β Vocabulary size of the BERT model. Defines the different tokens that can be represented by the inputs_ids passed to the forward method ofBertModel
.hidden_size (
int
, optional, defaults to 768) β Dimensionality of the encoder layers and the pooler layer.r_layers (
int
, optional, defaults to 5) β Number of hidden layers in the Transformer visual encoder.l_layers (
int
, optional, defaults to 9) β Number of hidden layers in the Transformer language encoder.x_layers (
int
, optional, defaults to 5) β Number of hidden layers in the Transformer cross modality encoder.num_attention_heads (
int
, optional, defaults to 5) β 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
orfunction
, optional, defaults to βgeluβ) β The non-linear activation function (function or string) in the encoder and pooler. If string, βgeluβ, βreluβ, βswishβ and βgelu_newβ are supported.hidden_dropout_prob (
float
, optional, defaults to 0.1) β The dropout probabilitiy for all fully connected layers in the embeddings, encoder, and pooler.attention_probs_dropout_prob (
float
, optional, defaults to 0.1) β The dropout ratio for the attention probabilities.max_position_embeddings (
int
, optional, defaults to 512) β The maximum sequence length that this model might ever be used with. Typically set this to something large just in case (e.g., 512 or 1024 or 2048).type_vocab_size (
int
, optional, defaults to 2) β The vocabulary size of the token_type_ids passed intoBertModel
.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.visual_feat_dim (
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.visual_pos_dim (
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)visual_loss_normalizer (
float
, optional, defaults to 1/15) β 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.num_qa_labels (
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.num_object_labels (
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.num_attr_labels (
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.task_matched (
bool
, optional, defaults toTrue
) β 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.task_mask_lm (
bool
, optional, defaults toTrue
) β This task is the defacto masked langauge modeling used in pretraining models such as BERT.task_obj_predict (
bool
, optional, defaults toTrue
) β This task is set to true if the user would like to perform one of the following loss objectives: object predicition, atrribute predicition, feature regressiontask_qa (
bool
, optional, defaults toTrue
) β This task specifies whether or not Lxmert will calculate the question-asnwering loss objectivevisual_obj_loss (
bool
, optional, defaults toTrue
) β This task specifies whether or not Lxmert will calculate the object-prediction loss objectivevisual_attr_loss (
bool
, optional, defaults toTrue
) β This task specifies whether or not Lxmert will calculate the attribute-prediction loss objectivevisual_feat_loss (
bool
, optional, defaults toTrue
) β This task specifies whether or not Lxmert will calculate the feature-regression loss objectiveoutput_attentions (
bool
, optional, defaults toFalse
) β if True, the vision, langauge, and cross-modality layers will be returnedoutput_hidden_states (
bool
, optional, defaults toFalse
) β if True, final cross-modality hidden states for language and vision features will be returned
LxmertTokenizerΒΆ
-
class
transformers.
LxmertTokenizer
(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)[source]ΒΆ Constructs an Lxmert tokenizer.
LxmertTokenizer
is identical toBertTokenizer
and runs end-to-end tokenization: punctuation splitting + wordpiece.Refer to superclass
BertTokenizer
for usage examples and documentation concerning parameters.-
build_inputs_with_special_tokens
(token_ids_0: List[int], token_ids_1: Optional[List[int]] = None) → List[int]ΒΆ Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and adding special tokens. A BERT sequence has the following format:
single sequence:
[CLS] X [SEP]
pair of sequences:
[CLS] A [SEP] B [SEP]
- Parameters
token_ids_0 (
List[int]
) β List of IDs to which the special tokens will be addedtoken_ids_1 (
List[int]
, optional) β Optional second list of IDs for sequence pairs.
- Returns
list of input IDs with the appropriate special tokens.
- Return type
List[int]
-
create_token_type_ids_from_sequences
(token_ids_0: List[int], token_ids_1: Optional[List[int]] = None) → List[int]ΒΆ Creates a mask from the two sequences passed to be used in a sequence-pair classification task. A BERT 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, only returns the first portion of the mask (0βs).
- Parameters
token_ids_0 (
List[int]
) β List of ids.token_ids_1 (
List[int]
, optional) β Optional second list of IDs for sequence pairs.
- Returns
List of token type IDs according to the given sequence(s).
- Return type
List[int]
-
get_special_tokens_mask
(token_ids_0: List[int], token_ids_1: Optional[List[int]] = None, already_has_special_tokens: bool = False) → List[int]ΒΆ Retrieves 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.- Parameters
token_ids_0 (
List[int]
) β List of ids.token_ids_1 (
List[int]
, optional) β Optional second list of IDs for sequence pairs.already_has_special_tokens (
bool
, optional, defaults toFalse
) β Set to True if the token list is already formatted with special tokens for the model
- Returns
A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
- Return type
List[int]
-
save_vocabulary
(vocab_path)ΒΆ Save the sentencepiece vocabulary (copy original file) and special tokens file to a directory.
- Parameters
vocab_path (
str
) β The directory in which to save the vocabulary.- Returns
Paths to the files saved.
- Return type
Tuple(str)
-
Lxmert specific outputsΒΆ
-
class
transformers.modeling_lxmert.
LxmertModelOutput
(language_output: Optional[torch.FloatTensor] = None, vision_output: Optional[torch.FloatTensor] = None, pooled_output: Optional[torch.FloatTensor] = None, language_hidden_states: Optional[Tuple[torch.FloatTensor]] = None, vision_hidden_states: Optional[Tuple[torch.FloatTensor]] = None, language_attentions: Optional[Tuple[torch.FloatTensor]] = None, vision_attentions: Optional[Tuple[torch.FloatTensor]] = None, cross_encoder_attentions: Optional[Tuple[torch.FloatTensor]] = None)[source]ΒΆ Lxmertβs outputs that contain the last hidden states, pooled outputs, and attention probabilites for the language, visual, and, cross-modality encoders. (note: the visual encoder in Lxmert is referred to as the βrelation-shipβ encoderβ)
- Parameters
language_output (
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.vision_output (
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.pooled_output (
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 Linearlanguage_hidden_states (
tuple(torch.FloatTensor)
, optional, returned whenoutput_hidden_states=True
is passed or whenconfig.output_hidden_states=True
) β Tuple oftorch.FloatTensor
(one for input features + one for the output of each cross-modality layer) of shape(batch_size, sequence_length, hidden_size)
.vision_hidden_states (
tuple(torch.FloatTensor)
, optional, returned whenoutput_hidden_states=True
is passed or whenconfig.output_hidden_states=True
) β Tuple oftorch.FloatTensor
(one for input features + one for the output of each cross-modality layer) of shape(batch_size, sequence_length, hidden_size)
.language_attentions (
tuple(torch.FloatTensor)
, optional, returned whenoutput_attentions=True
is passed or whenconfig.output_attentions=True
) β Tuple oftorch.FloatTensor
(one for each layer) of shape(batch_size, num_heads, sequence_length, sequence_length)
. Attentions weights after the attention softmax, used to compute the weighted average in the self-attention heads.vision_attentions (
tuple(torch.FloatTensor)
, optional, returned whenoutput_attentions=True
is passed or whenconfig.output_attentions=True
) β Tuple oftorch.FloatTensor
(one for each layer) of shape(batch_size, num_heads, sequence_length, sequence_length)
. Attentions weights after the attention softmax, used to compute the weighted average in the self-attention heads.cross_encoder_attentions (
tuple(torch.FloatTensor)
, optional, returned whenoutput_attentions=True
is passed or whenconfig.output_attentions=True
) β Tuple oftorch.FloatTensor
(one for each layer) of shape(batch_size, num_heads, sequence_length, sequence_length)
. Attentions weights after the attention softmax, used to compute the weighted average in the self-attention heads.
-
class
transformers.modeling_lxmert.
LxmertForPreTrainingOutput
(loss: [<class 'torch.FloatTensor'>] = None, prediction_logits: Optional[torch.FloatTensor] = None, cross_relationship_score: Optional[torch.FloatTensor] = None, question_answering_score: Optional[torch.FloatTensor] = None, language_hidden_states: Optional[Tuple[torch.FloatTensor]] = None, vision_hidden_states: Optional[Tuple[torch.FloatTensor]] = None, language_attentions: Optional[Tuple[torch.FloatTensor]] = None, vision_attentions: Optional[Tuple[torch.FloatTensor]] = None, cross_encoder_attentions: Optional[Tuple[torch.FloatTensor]] = None)[source]ΒΆ Output type of
LxmertForPreTrainingModel
.- Parameters
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 next sequence 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).cross_relationship_score β (
torch.FloatTensor
of shape(batch_size, 2)
): Prediction scores of the textual matching objective (classification) head (scores of True/False continuation before SoftMax).question_answering_score β (
torch.FloatTensor
of shape(batch_size, n_qa_answers)
): Prediction scores of question answering objective (classification).language_hidden_states (
tuple(torch.FloatTensor)
, optional, returned whenoutput_hidden_states=True
is passed or whenconfig.output_hidden_states=True
) β Tuple oftorch.FloatTensor
(one for input features + one for the output of each cross-modality layer) of shape(batch_size, sequence_length, hidden_size)
.vision_hidden_states (
tuple(torch.FloatTensor)
, optional, returned whenoutput_hidden_states=True
is passed or whenconfig.output_hidden_states=True
) β Tuple oftorch.FloatTensor
(one for input features + one for the output of each cross-modality layer) of shape(batch_size, sequence_length, hidden_size)
.language_attentions (
tuple(torch.FloatTensor)
, optional, returned whenoutput_attentions=True
is passed or whenconfig.output_attentions=True
) β Tuple oftorch.FloatTensor
(one for each layer) of shape(batch_size, num_heads, sequence_length, sequence_length)
. Attentions weights after the attention softmax, used to compute the weighted average in the self-attention heads.vision_attentions (
tuple(torch.FloatTensor)
, optional, returned whenoutput_attentions=True
is passed or whenconfig.output_attentions=True
) β Tuple oftorch.FloatTensor
(one for each layer) of shape(batch_size, num_heads, sequence_length, sequence_length)
. Attentions weights after the attention softmax, used to compute the weighted average in the self-attention heads.cross_encoder_attentions (
tuple(torch.FloatTensor)
, optional, returned whenoutput_attentions=True
is passed or whenconfig.output_attentions=True
) β Tuple oftorch.FloatTensor
(one for each layer) of shape(batch_size, num_heads, sequence_length, sequence_length)
. Attentions weights after the attention softmax, used to compute the weighted average in the self-attention heads.
-
class
transformers.modeling_lxmert.
LxmertForQuestionAnsweringOutput
(loss: Optional[torch.FloatTensor] = None, question_answering_score: Optional[torch.FloatTensor] = None, language_hidden_states: Optional[Tuple[torch.FloatTensor]] = None, vision_hidden_states: Optional[Tuple[torch.FloatTensor]] = None, language_attentions: Optional[Tuple[torch.FloatTensor]] = None, vision_attentions: Optional[Tuple[torch.FloatTensor]] = None, cross_encoder_attentions: Optional[Tuple[torch.FloatTensor]] = None)[source]ΒΆ Output type of
LxmertForQuestionAnswering
.- Parameters
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 next sequence prediction (classification) loss.k.question_answering_score β (
torch.FloatTensor
of shape(batch_size, n_qa_answers)
, optional): Prediction scores of question answering objective (classification).language_hidden_states (
tuple(torch.FloatTensor)
, optional, returned whenoutput_hidden_states=True
is passed or whenconfig.output_hidden_states=True
) β Tuple oftorch.FloatTensor
(one for input features + one for the output of each cross-modality layer) of shape(batch_size, sequence_length, hidden_size)
.vision_hidden_states (
tuple(torch.FloatTensor)
, optional, returned whenoutput_hidden_states=True
is passed or whenconfig.output_hidden_states=True
) β Tuple oftorch.FloatTensor
(one for input features + one for the output of each cross-modality layer) of shape(batch_size, sequence_length, hidden_size)
.language_attentions (
tuple(torch.FloatTensor)
, optional, returned whenoutput_attentions=True
is passed or whenconfig.output_attentions=True
) β Tuple oftorch.FloatTensor
(one for each layer) of shape(batch_size, num_heads, sequence_length, sequence_length)
. Attentions weights after the attention softmax, used to compute the weighted average in the self-attention heads.vision_attentions (
tuple(torch.FloatTensor)
, optional, returned whenoutput_attentions=True
is passed or whenconfig.output_attentions=True
) β Tuple oftorch.FloatTensor
(one for each layer) of shape(batch_size, num_heads, sequence_length, sequence_length)
. Attentions weights after the attention softmax, used to compute the weighted average in the self-attention heads.cross_encoder_attentions (
tuple(torch.FloatTensor)
, optional, returned whenoutput_attentions=True
is passed or whenconfig.output_attentions=True
) β Tuple oftorch.FloatTensor
(one for each layer) of shape(batch_size, num_heads, sequence_length, sequence_length)
. Attentions weights after the attention softmax, used to compute the weighted average in the self-attention heads.
-
class
transformers.modeling_tf_lxmert.
TFLxmertModelOutput
(language_output: Optional[tensorflow.python.framework.ops.Tensor] = None, vision_output: Optional[tensorflow.python.framework.ops.Tensor] = None, pooled_output: Optional[tensorflow.python.framework.ops.Tensor] = None, language_hidden_states: Optional[Tuple[tensorflow.python.framework.ops.Tensor]] = None, vision_hidden_states: Optional[Tuple[tensorflow.python.framework.ops.Tensor]] = None, language_attentions: Optional[Tuple[tensorflow.python.framework.ops.Tensor]] = None, vision_attentions: Optional[Tuple[tensorflow.python.framework.ops.Tensor]] = None, cross_encoder_attentions: Optional[Tuple[tensorflow.python.framework.ops.Tensor]] = None)[source]ΒΆ Lxmertβs outputs that contain the last hidden states, pooled outputs, and attention probabilites for the language, visual, and, cross-modality encoders. (note: the visual encoder in Lxmert is referred to as the βrelation-shipβ encoderβ)
- Parameters
language_output (
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.vision_output (
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.pooled_output (
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 Linearlanguage_hidden_states (
tuple(tf.Tensor)
, optional, returned whenoutput_hidden_states=True
is passed or whenconfig.output_hidden_states=True
) β Tuple oftf.Tensor
(one for input features + one for the output of each cross-modality layer) of shape(batch_size, sequence_length, hidden_size)
.vision_hidden_states (
tuple(tf.Tensor)
, optional, returned whenoutput_hidden_states=True
is passed or whenconfig.output_hidden_states=True
) β Tuple oftf.Tensor
(one for input features + one for the output of each cross-modality layer) of shape(batch_size, sequence_length, hidden_size)
.language_attentions (
tuple(tf.Tensor)
, optional, returned whenoutput_attentions=True
is passed or whenconfig.output_attentions=True
) β Tuple oftf.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.vision_attentions (
tuple(tf.Tensor)
, optional, returned whenoutput_attentions=True
is passed or whenconfig.output_attentions=True
) β Tuple oftf.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.cross_encoder_attentions (
tuple(tf.Tensor)
, optional, returned whenoutput_attentions=True
is passed or whenconfig.output_attentions=True
) β Tuple oftf.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.
-
class
transformers.modeling_tf_lxmert.
TFLxmertForPreTrainingOutput
(loss: [<class 'tensorflow.python.framework.ops.Tensor'>] = None, prediction_logits: Optional[tensorflow.python.framework.ops.Tensor] = None, cross_relationship_score: Optional[tensorflow.python.framework.ops.Tensor] = None, question_answering_score: Optional[tensorflow.python.framework.ops.Tensor] = None, language_hidden_states: Optional[Tuple[tensorflow.python.framework.ops.Tensor]] = None, vision_hidden_states: Optional[Tuple[tensorflow.python.framework.ops.Tensor]] = None, language_attentions: Optional[Tuple[tensorflow.python.framework.ops.Tensor]] = None, vision_attentions: Optional[Tuple[tensorflow.python.framework.ops.Tensor]] = None, cross_encoder_attentions: Optional[Tuple[tensorflow.python.framework.ops.Tensor]] = None)[source]ΒΆ Output type of
LxmertForPreTrainingModel
.- Parameters
loss (optional, returned when
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.prediction_logits (
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).cross_relationship_score β (
tf.Tensor
of shape(batch_size, 2)
): Prediction scores of the textual matching objective (classification) head (scores of True/False continuation before SoftMax).question_answering_score β (
tf.Tensor
of shape(batch_size, n_qa_answers)
): Prediction scores of question answering objective (classification).language_hidden_states (
tuple(tf.Tensor)
, optional, returned whenoutput_hidden_states=True
is passed or whenconfig.output_hidden_states=True
) β Tuple oftf.Tensor
(one for input features + one for the output of each cross-modality layer) of shape(batch_size, sequence_length, hidden_size)
.vision_hidden_states (
tuple(tf.Tensor)
, optional, returned whenoutput_hidden_states=True
is passed or whenconfig.output_hidden_states=True
) β Tuple oftf.Tensor
(one for input features + one for the output of each cross-modality layer) of shape(batch_size, sequence_length, hidden_size)
.language_attentions (
tuple(tf.Tensor)
, optional, returned whenoutput_attentions=True
is passed or whenconfig.output_attentions=True
) β Tuple oftf.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.vision_attentions (
tuple(tf.Tensor)
, optional, returned whenoutput_attentions=True
is passed or whenconfig.output_attentions=True
) β Tuple oftf.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.cross_encoder_attentions (
tuple(tf.Tensor)
, optional, returned whenoutput_attentions=True
is passed or whenconfig.output_attentions=True
) β Tuple oftf.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.
LxmertModelΒΆ
-
class
transformers.
LxmertModel
(config)[source]ΒΆ 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 predicition.
This model is a PyTorch torch.nn.Module sub-class. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and behavior.
- Parameters
config (
LxmertConfig
) β Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. Check out thefrom_pretrained()
method to load the model weights.
-
forward
(input_ids=None, visual_feats=None, visual_pos=None, attention_mask=None, visual_attention_mask=None, token_type_ids=None, inputs_embeds=None, output_attentions=None, output_hidden_states=None, return_dict=None)[source]ΒΆ The
LxmertModel
forward method, overrides the__call__()
special method.Note
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.- Parameters
input_ids (
torch.LongTensor
of shape(batch_size, sequence_length)
) βIndices of input sequence tokens in the vocabulary.
Indices can be obtained using
transformers.LxmertTokenizer
. Seetransformers.PreTrainedTokenizer.encode()
andtransformers.PreTrainedTokenizer.__call__()
for details.visual_feats β (
torch.FloatTensor
of shape :obj:Υ(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 libraryvisual_pos β (
torch.FloatTensor
of shape :obj:Υ(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~1. These are currently not provided by the transformers libraryattention_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 MASKED tokens.visual_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 MASKED tokens.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 tokeninputs_embeds (
torch.FloatTensor
of shape(batch_size, sequence_length, hidden_size)
, optional) β Optionally, instead of passinginput_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.output_attentions β (
bool
, optional): If set toTrue
, the attentions tensors of all attention layers for the visual, language, and cross-modality encoder are returned.output_hidden_states (
bool
, optional) β If set toTrue
, the hidden states for each respective modality will be returned when used as the input vector in the cross-modality encoder.return_dict (
bool
, optional) β If set toTrue
, the model will return aLxmertModelOutput
instead of a plain tuple.
- Returns
A
LxmertModelOutput
(ifreturn_dict=True
is passed or whenconfig.return_dict=True
) or a tuple oftorch.FloatTensor
comprising various elements depending on the configuration (LxmertConfig
) and inputs.language_output (
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.vision_output (
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.pooled_output (
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 Linearlanguage_hidden_states (
tuple(torch.FloatTensor)
, optional, returned whenoutput_hidden_states=True
is passed or whenconfig.output_hidden_states=True
) β Tuple oftorch.FloatTensor
(one for input features + one for the output of each cross-modality layer) of shape(batch_size, sequence_length, hidden_size)
.vision_hidden_states (
tuple(torch.FloatTensor)
, optional, returned whenoutput_hidden_states=True
is passed or whenconfig.output_hidden_states=True
) β Tuple oftorch.FloatTensor
(one for input features + one for the output of each cross-modality layer) of shape(batch_size, sequence_length, hidden_size)
.language_attentions (
tuple(torch.FloatTensor)
, optional, returned whenoutput_attentions=True
is passed or whenconfig.output_attentions=True
) β Tuple oftorch.FloatTensor
(one for each layer) of shape(batch_size, num_heads, sequence_length, sequence_length)
. Attentions weights after the attention softmax, used to compute the weighted average in the self-attention heads.vision_attentions (
tuple(torch.FloatTensor)
, optional, returned whenoutput_attentions=True
is passed or whenconfig.output_attentions=True
) β Tuple oftorch.FloatTensor
(one for each layer) of shape(batch_size, num_heads, sequence_length, sequence_length)
. Attentions weights after the attention softmax, used to compute the weighted average in the self-attention heads.cross_encoder_attentions (
tuple(torch.FloatTensor)
, optional, returned whenoutput_attentions=True
is passed or whenconfig.output_attentions=True
) β Tuple oftorch.FloatTensor
(one for each layer) of shape(batch_size, num_heads, sequence_length, sequence_length)
. Attentions weights after the attention softmax, used to compute the weighted average in the self-attention heads.
- Return type
LxmertModelOutput
ortuple(torch.FloatTensor)
Example:
>>> from transformers import LxmertTokenizer, LxmertModel >>> import torch >>> tokenizer = LxmertTokenizer.from_pretrained('unc-nlp/lxmert-base-uncased') >>> model = LxmertModel.from_pretrained('unc-nlp/lxmert-base-uncased', return_dict=True) >>> inputs = tokenizer("Hello, my dog is cute", return_tensors="pt") >>> outputs = model(**inputs) >>> last_hidden_states = outputs.last_hidden_state
LxmertForPreTrainingΒΆ
-
class
transformers.
LxmertForPreTraining
(config)[source]ΒΆ Lxmert Model with a specified pre-training 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 predicition.
This model is a PyTorch torch.nn.Module sub-class. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and behavior.
- Parameters
config (
LxmertConfig
) β Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. Check out thefrom_pretrained()
method to load the model weights.
-
forward
(input_ids=None, visual_feats=None, visual_pos=None, attention_mask=None, visual_attention_mask=None, token_type_ids=None, inputs_embeds=None, masked_lm_labels=None, obj_labels=None, matched_label=None, ans=None, output_attentions=None, output_hidden_states=None, return_dict=None)[source]ΒΆ The
LxmertForPreTraining
forward method, overrides the__call__()
special method.Note
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.- Parameters
input_ids (
torch.LongTensor
of shape(batch_size, sequence_length)
) βIndices of input sequence tokens in the vocabulary.
Indices can be obtained using
transformers.LxmertTokenizer
. Seetransformers.PreTrainedTokenizer.encode()
andtransformers.PreTrainedTokenizer.__call__()
for details.visual_feats β (
torch.FloatTensor
of shape :obj:Υ(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 libraryvisual_pos β (
torch.FloatTensor
of shape :obj:Υ(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~1. These are currently not provided by the transformers libraryattention_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 MASKED tokens.visual_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 MASKED tokens.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 tokeninputs_embeds (
torch.FloatTensor
of shape(batch_size, sequence_length, hidden_size)
, optional) β Optionally, instead of passinginput_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.output_attentions β (
bool
, optional): If set toTrue
, the attentions tensors of all attention layers for the visual, language, and cross-modality encoder are returned.output_hidden_states (
bool
, optional) β If set toTrue
, the hidden states for each respective modality will be returned when used as the input vector in the cross-modality encoder.return_dict (
bool
, optional) β If set toTrue
, the model will return aLxmertModelOutput
instead of a plain tuple.masked_lm_labels (
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]
(seeinput_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]
obj_labels β (
Dict[Str: Tuple[Torch.FloatTensor, Torch.FloatTensor]]
, optional, defaults to :obj: 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 respectivelymatched_label (
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 (seeinput_ids
docstring) Indices should be in[0, 1]
.0
indicates that the sentence does not match the image1
indicates that the sentence does match the imageans β (
Torch.Tensor
of shape(batch_size)
, optional, defaults to :obj: None): a one hot representation hof the correct answer optional
- Returns
A
LxmertForPreTrainingOutput
(ifreturn_dict=True
is passed or whenconfig.return_dict=True
) or a tuple oftorch.FloatTensor
comprising various elements depending on the configuration (LxmertConfig
) and inputs.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 next sequence 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).cross_relationship_score: (
torch.FloatTensor
of shape(batch_size, 2)
) β Prediction scores of the textual matching objective (classification) head (scores of True/False continuation before SoftMax).question_answering_score: (
torch.FloatTensor
of shape(batch_size, n_qa_answers)
) β Prediction scores of question answering objective (classification).language_hidden_states (
tuple(torch.FloatTensor)
, optional, returned whenoutput_hidden_states=True
is passed or whenconfig.output_hidden_states=True
) β Tuple oftorch.FloatTensor
(one for input features + one for the output of each cross-modality layer) of shape(batch_size, sequence_length, hidden_size)
.vision_hidden_states (
tuple(torch.FloatTensor)
, optional, returned whenoutput_hidden_states=True
is passed or whenconfig.output_hidden_states=True
) β Tuple oftorch.FloatTensor
(one for input features + one for the output of each cross-modality layer) of shape(batch_size, sequence_length, hidden_size)
.language_attentions (
tuple(torch.FloatTensor)
, optional, returned whenoutput_attentions=True
is passed or whenconfig.output_attentions=True
) β Tuple oftorch.FloatTensor
(one for each layer) of shape(batch_size, num_heads, sequence_length, sequence_length)
. Attentions weights after the attention softmax, used to compute the weighted average in the self-attention heads.vision_attentions (
tuple(torch.FloatTensor)
, optional, returned whenoutput_attentions=True
is passed or whenconfig.output_attentions=True
) β Tuple oftorch.FloatTensor
(one for each layer) of shape(batch_size, num_heads, sequence_length, sequence_length)
. Attentions weights after the attention softmax, used to compute the weighted average in the self-attention heads.cross_encoder_attentions (
tuple(torch.FloatTensor)
, optional, returned whenoutput_attentions=True
is passed or whenconfig.output_attentions=True
) β Tuple oftorch.FloatTensor
(one for each layer) of shape(batch_size, num_heads, sequence_length, sequence_length)
. Attentions weights after the attention softmax, used to compute the weighted average in the self-attention heads.
- Return type
LxmertForPreTrainingOutput
ortuple(torch.FloatTensor)
-
get_qa_logit_layer
() → torch.nn.modules.module.Module[source]ΒΆ Returns the the linear layer that produces question answering logits.
- Returns
- A torch module mapping the question answering prediction hidden states or
None
if LXMERT does not have a visual answering head.
- A torch module mapping the question answering prediction hidden states or
- Return type
nn.Module
-
resize_num_qa_labels
(num_labels)[source]ΒΆ Build a resized question answering linear layer Module from a provided new linear layer. Increasing the size will add newly initialized weights. Reducing the size will remove weights from the end
- Parameters
cur_qa_logit_layer (
torch.nn.Linear
) β Old linear layer to be resized.num_labels (
int
, optional) β New number of labels in the linear layer weight matrix. Increasing the size will add newly initialized weights at the end. Reducing the size will remove weights from the end. If not provided orNone
, just returns a pointer to the qa labelstorch.nn.Linear`
module of the model wihtout doing anything.
- Returns
Pointer to the resized Linear layer or the old Linear layer
- Return type
torch.nn.Linear
LxmertForQuestionAnsweringΒΆ
-
class
transformers.
LxmertForQuestionAnswering
(config)[source]ΒΆ 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, 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 predicition.
This model is a PyTorch torch.nn.Module sub-class. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and behavior.
- Parameters
config (
LxmertConfig
) β Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. Check out thefrom_pretrained()
method to load the model weights.
-
forward
(input_ids=None, visual_feats=None, visual_pos=None, attention_mask=None, visual_attention_mask=None, token_type_ids=None, inputs_embeds=None, labels=None, output_attentions=None, output_hidden_states=None, return_dict=None)[source]ΒΆ The
LxmertForQuestionAnswering
forward method, overrides the__call__()
special method.Note
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.- Parameters
input_ids (
torch.LongTensor
of shape(batch_size, sequence_length)
) βIndices of input sequence tokens in the vocabulary.
Indices can be obtained using
transformers.LxmertTokenizer
. Seetransformers.PreTrainedTokenizer.encode()
andtransformers.PreTrainedTokenizer.__call__()
for details.visual_feats β (
torch.FloatTensor
of shape :obj:Υ(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 libraryvisual_pos β (
torch.FloatTensor
of shape :obj:Υ(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~1. These are currently not provided by the transformers libraryattention_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 MASKED tokens.visual_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 MASKED tokens.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 tokeninputs_embeds (
torch.FloatTensor
of shape(batch_size, sequence_length, hidden_size)
, optional) β Optionally, instead of passinginput_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.output_attentions β (
bool
, optional): If set toTrue
, the attentions tensors of all attention layers for the visual, language, and cross-modality encoder are returned.output_hidden_states (
bool
, optional) β If set toTrue
, the hidden states for each respective modality will be returned when used as the input vector in the cross-modality encoder.return_dict (
bool
, optional) β If set toTrue
, the model will return aLxmertModelOutput
instead of a plain tuple.labels β (
Torch.Tensor
of shape(batch_size)
, optional): a one hot representation of the correct answerReturns β
- Returns
A
LxmertForQuestionAnsweringOutput
(ifreturn_dict=True
is passed or whenconfig.return_dict=True
) or a tuple oftorch.FloatTensor
comprising various elements depending on the configuration (LxmertConfig
) and inputs.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 next sequence prediction (classification) loss.k.question_answering_score: (
torch.FloatTensor
of shape(batch_size, n_qa_answers)
, optional) β Prediction scores of question answering objective (classification).language_hidden_states (
tuple(torch.FloatTensor)
, optional, returned whenoutput_hidden_states=True
is passed or whenconfig.output_hidden_states=True
) β Tuple oftorch.FloatTensor
(one for input features + one for the output of each cross-modality layer) of shape(batch_size, sequence_length, hidden_size)
.vision_hidden_states (
tuple(torch.FloatTensor)
, optional, returned whenoutput_hidden_states=True
is passed or whenconfig.output_hidden_states=True
) β Tuple oftorch.FloatTensor
(one for input features + one for the output of each cross-modality layer) of shape(batch_size, sequence_length, hidden_size)
.language_attentions (
tuple(torch.FloatTensor)
, optional, returned whenoutput_attentions=True
is passed or whenconfig.output_attentions=True
) β Tuple oftorch.FloatTensor
(one for each layer) of shape(batch_size, num_heads, sequence_length, sequence_length)
. Attentions weights after the attention softmax, used to compute the weighted average in the self-attention heads.vision_attentions (
tuple(torch.FloatTensor)
, optional, returned whenoutput_attentions=True
is passed or whenconfig.output_attentions=True
) β Tuple oftorch.FloatTensor
(one for each layer) of shape(batch_size, num_heads, sequence_length, sequence_length)
. Attentions weights after the attention softmax, used to compute the weighted average in the self-attention heads.cross_encoder_attentions (
tuple(torch.FloatTensor)
, optional, returned whenoutput_attentions=True
is passed or whenconfig.output_attentions=True
) β Tuple oftorch.FloatTensor
(one for each layer) of shape(batch_size, num_heads, sequence_length, sequence_length)
. Attentions weights after the attention softmax, used to compute the weighted average in the self-attention heads.
- Return type
LxmertForQuestionAnsweringOutput
ortuple(torch.FloatTensor)
Example:
>>> from transformers import LxmertTokenizer, LxmertForQuestionAnswering >>> import torch >>> tokenizer = LxmertTokenizer.from_pretrained('unc-nlp/lxmert-base-uncased') >>> model = LxmertForQuestionAnswering.from_pretrained('unc-nlp/lxmert-base-uncased', return_dict=True) >>> question, text = "Who was Jim Henson?", "Jim Henson was a nice puppet" >>> inputs = tokenizer(question, text, return_tensors='pt') >>> start_positions = torch.tensor([1]) >>> end_positions = torch.tensor([3]) >>> outputs = model(**inputs, start_positions=start_positions, end_positions=end_positions) >>> loss = outputs.loss >>> start_scores = outputs.start_logits >>> end_scores = outputs.end_logits
-
get_qa_logit_layer
() → torch.nn.modules.module.Module[source]ΒΆ Returns the the linear layer that produces question answering logits
- Returns
A torch module mapping the question answering prediction hidden states.
None
: A NoneType object if Lxmert does not have the visual answering head.- Return type
nn.Module
-
resize_num_qa_labels
(num_labels)[source]ΒΆ Build a resized question answering linear layer Module from a provided new linear layer. Increasing the size will add newly initialized weights. Reducing the size will remove weights from the end
- Parameters
cur_qa_logit_layer (
torch.nn.Linear
) β Old linear layer to be resized.num_labels (
int
, optional) β New number of labels in the linear layer weight matrix. Increasing the size will add newly initialized weights at the end. Reducing the size will remove weights from the end. If not provided orNone
, just returns a pointer to the qa labelstorch.nn.Linear`
module of the model wihtout doing anything.
- Returns
Pointer to the resized Linear layer or the old Linear layer
- Return type
torch.nn.Linear
TFLxmertModelΒΆ
-
class
transformers.
TFLxmertModel
(*args, **kwargs)[source]ΒΆ The bare Lxmert Model transformer outputing 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 predicition.
This model is a tf.keras.Model sub-class. 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.
- Note on the model inputs:
TF 2.0 models accepts two formats as inputs:
having all inputs as keyword arguments (like PyTorch models), or
having all inputs as a list, tuple or dict in the first positional arguments.
This second option is useful when using
tf.keras.Model.fit()
method which currently requires having all the tensors in the first argument of the model call function:model(inputs)
.If you choose this second option, there are three possibilities you can use to gather all the input Tensors in the first positional argument :
a single Tensor with input_ids only and nothing else:
model(inputs_ids)
a list of varying length with one or several input Tensors IN THE ORDER given in the docstring:
model([input_ids, attention_mask])
ormodel([input_ids, attention_mask, token_type_ids])
a dictionary with one or several input Tensors associated to the input names given in the docstring:
model({'input_ids': input_ids, 'token_type_ids': token_type_ids})
- Parameters
config (
LxmertConfig
) β Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. Check out thefrom_pretrained()
method to load the model weights.
-
call
(inputs, *args, **kwargs)[source]ΒΆ The
TFLxmertModel
forward method, overrides the__call__()
special method.Note
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.- Parameters
input_ids (
np.ndarray
ortf.Tensor
of shape(batch_size, sequence_length)
) βIndices of input sequence tokens in the vocabulary.
Indices can be obtained using
transformers.LxmertTokenizer
. Seetransformers.PreTrainedTokenizer.encode()
andtransformers.PreTrainedTokenizer.__call__()
for details.attention_mask (
tf.Tensor
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 MASKED tokens.token_type_ids (
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]
:0
corresponds to a sentence A token,1
corresponds to a sentence B tokenvisual_feats β (
tf.Tensor
of shape :obj:Υ(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 libraryvisual_attention_mask (
tf.Tensor
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 MASKED tokens.
- Returns
A
TFLxmertModelOutput
(ifreturn_dict=True
is passed or whenconfig.return_dict=True
) or a tuple oftf.Tensor
comprising various elements depending on the configuration (LxmertConfig
) and inputs.language_output (
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.vision_output (
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.pooled_output (
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 Linearlanguage_hidden_states (
tuple(tf.Tensor)
, optional, returned whenoutput_hidden_states=True
is passed or whenconfig.output_hidden_states=True
) β Tuple oftf.Tensor
(one for input features + one for the output of each cross-modality layer) of shape(batch_size, sequence_length, hidden_size)
.vision_hidden_states (
tuple(tf.Tensor)
, optional, returned whenoutput_hidden_states=True
is passed or whenconfig.output_hidden_states=True
) β Tuple oftf.Tensor
(one for input features + one for the output of each cross-modality layer) of shape(batch_size, sequence_length, hidden_size)
.language_attentions (
tuple(tf.Tensor)
, optional, returned whenoutput_attentions=True
is passed or whenconfig.output_attentions=True
) β Tuple oftf.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.vision_attentions (
tuple(tf.Tensor)
, optional, returned whenoutput_attentions=True
is passed or whenconfig.output_attentions=True
) β Tuple oftf.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.cross_encoder_attentions (
tuple(tf.Tensor)
, optional, returned whenoutput_attentions=True
is passed or whenconfig.output_attentions=True
) β Tuple oftf.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.
- Return type
TFLxmertModelOutput
ortuple(tf.Tensor)
Example:
>>> from transformers import LxmertTokenizer, TFLxmertModel >>> import tensorflow as tf >>> tokenizer = LxmertTokenizer.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[0] # The last hidden-state is the first element of the output tuple
TFLxmertForPreTrainingΒΆ
-
class
transformers.
TFLxmertForPreTraining
(*args, **kwargs)[source]ΒΆ 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 predicition.
This model is a tf.keras.Model sub-class. 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.
- Note on the model inputs:
TF 2.0 models accepts two formats as inputs:
having all inputs as keyword arguments (like PyTorch models), or
having all inputs as a list, tuple or dict in the first positional arguments.
This second option is useful when using
tf.keras.Model.fit()
method which currently requires having all the tensors in the first argument of the model call function:model(inputs)
.If you choose this second option, there are three possibilities you can use to gather all the input Tensors in the first positional argument :
a single Tensor with input_ids only and nothing else:
model(inputs_ids)
a list of varying length with one or several input Tensors IN THE ORDER given in the docstring:
model([input_ids, attention_mask])
ormodel([input_ids, attention_mask, token_type_ids])
a dictionary with one or several input Tensors associated to the input names given in the docstring:
model({'input_ids': input_ids, 'token_type_ids': token_type_ids})
- Parameters
config (
LxmertConfig
) β Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. Check out thefrom_pretrained()
method to load the model weights.
-
call
(inputs=None, visual_feats=None, visual_pos=None, attention_mask=None, visual_attention_mask=None, token_type_ids=None, inputs_embeds=None, masked_lm_labels=None, obj_labels=None, matched_label=None, ans=None, output_attentions=None, output_hidden_states=None, return_dict=None)[source]ΒΆ The
TFLxmertForPreTraining
forward method, overrides the__call__()
special method.Note
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.- Parameters
input_ids (
np.ndarray
ortf.Tensor
of shape(batch_size, sequence_length)
) βIndices of input sequence tokens in the vocabulary.
Indices can be obtained using
transformers.LxmertTokenizer
. Seetransformers.PreTrainedTokenizer.encode()
andtransformers.PreTrainedTokenizer.__call__()
for details.attention_mask (
tf.Tensor
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 MASKED tokens.token_type_ids (
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]
:0
corresponds to a sentence A token,1
corresponds to a sentence B tokenvisual_feats β (
tf.Tensor
of shape :obj:Υ(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 libraryvisual_attention_mask (
tf.Tensor
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 MASKED tokens.masked_lm_labels (
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]
(seeinput_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]
obj_labels β (
Dict[Str: Tuple[tf.Tensor, tf.Tensor]]
, optional, defaults to :obj: 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 respectivelymatched_label (
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 (seeinput_ids
docstring) Indices should be in[0, 1]
.0
indicates that the sentence does not match the image1
indicates that the sentence does match the imageans β (
Torch.Tensor
of shape(batch_size)
, optional, defaults to :obj: None): a one hot representation hof the correct answer optional
- Returns
A
TFLxmertForPreTrainingOutput
(ifreturn_dict=True
is passed or whenconfig.return_dict=True
) or a tuple oftf.Tensor
comprising various elements depending on the configuration (LxmertConfig
) and inputs.loss (optional, returned when
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.prediction_logits (
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).cross_relationship_score: (
tf.Tensor
of shape(batch_size, 2)
) β Prediction scores of the textual matching objective (classification) head (scores of True/False continuation before SoftMax).question_answering_score: (
tf.Tensor
of shape(batch_size, n_qa_answers)
) β Prediction scores of question answering objective (classification).language_hidden_states (
tuple(tf.Tensor)
, optional, returned whenoutput_hidden_states=True
is passed or whenconfig.output_hidden_states=True
) β Tuple oftf.Tensor
(one for input features + one for the output of each cross-modality layer) of shape(batch_size, sequence_length, hidden_size)
.vision_hidden_states (
tuple(tf.Tensor)
, optional, returned whenoutput_hidden_states=True
is passed or whenconfig.output_hidden_states=True
) β Tuple oftf.Tensor
(one for input features + one for the output of each cross-modality layer) of shape(batch_size, sequence_length, hidden_size)
.language_attentions (
tuple(tf.Tensor)
, optional, returned whenoutput_attentions=True
is passed or whenconfig.output_attentions=True
) β Tuple oftf.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.vision_attentions (
tuple(tf.Tensor)
, optional, returned whenoutput_attentions=True
is passed or whenconfig.output_attentions=True
) β Tuple oftf.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.cross_encoder_attentions (
tuple(tf.Tensor)
, optional, returned whenoutput_attentions=True
is passed or whenconfig.output_attentions=True
) β Tuple oftf.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.
- Return type
TFLxmertForPreTrainingOutput
ortuple(tf.Tensor)
-
property
dummy_inputs
ΒΆ Dummy inputs to build the network.
- Returns
tf.Tensor with dummy inputs