LXMERT

## [](#overview)Overview

The LXMERT model was proposed in [LXMERT: Learning Cross-Modality Encoder Representations from Transformers](https://arxiv.org/abs/1908.07490) 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_

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 bidirectional 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.

This model was contributed by [eltoto1219](https://huggingface.co/eltoto1219). The original code can be found [here](https://github.com/airsplay/lxmert).

## [](#documentation-resources)Documentation resources

-   [Question answering task guide](../tasks/question_answering)

## [](#transformers.LxmertConfig)LxmertConfig

### class transformers.LxmertConfig

[](#transformers.LxmertConfig)[< source \>](https://github.com/huggingface/transformers/blob/v4.30.0/src/transformers/models/lxmert/configuration_lxmert.py#L29)

( vocab\_size = 30522hidden\_size = 768num\_attention\_heads = 12num\_qa\_labels = 9500num\_object\_labels = 1600num\_attr\_labels = 400intermediate\_size = 3072hidden\_act = 'gelu'hidden\_dropout\_prob = 0.1attention\_probs\_dropout\_prob = 0.1max\_position\_embeddings = 512type\_vocab\_size = 2initializer\_range = 0.02layer\_norm\_eps = 1e-12l\_layers = 9x\_layers = 5r\_layers = 5visual\_feat\_dim = 2048visual\_pos\_dim = 4visual\_loss\_normalizer = 6.67task\_matched = Truetask\_mask\_lm = Truetask\_obj\_predict = Truetask\_qa = Truevisual\_obj\_loss = Truevisual\_attr\_loss = Truevisual\_feat\_loss = True\*\*kwargs )

This is the configuration class to store the configuration of a [LxmertModel](/docs/transformers/v4.30.0/en/model_doc/lxmert#transformers.LxmertModel) or a [TFLxmertModel](/docs/transformers/v4.30.0/en/model_doc/lxmert#transformers.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](https://huggingface.co/unc-nlp/lxmert-base-uncased) architecture.

Configuration objects inherit from [PretrainedConfig](/docs/transformers/v4.30.0/en/main_classes/configuration#transformers.PretrainedConfig) and can be used to control the model outputs. Read the documentation from [PretrainedConfig](/docs/transformers/v4.30.0/en/main_classes/configuration#transformers.PretrainedConfig) for more information.

## [](#transformers.LxmertTokenizer)LxmertTokenizer

### class transformers.LxmertTokenizer

[](#transformers.LxmertTokenizer)[< source \>](https://github.com/huggingface/transformers/blob/v4.30.0/src/transformers/models/lxmert/tokenization_lxmert.py#L67)

( vocab\_filedo\_lower\_case = Truedo\_basic\_tokenize = Truenever\_split = Noneunk\_token = '\[UNK\]'sep\_token = '\[SEP\]'pad\_token = '\[PAD\]'cls\_token = '\[CLS\]'mask\_token = '\[MASK\]'tokenize\_chinese\_chars = Truestrip\_accents = None\*\*kwargs )

Construct a Lxmert tokenizer. Based on WordPiece.

This tokenizer inherits from [PreTrainedTokenizer](/docs/transformers/v4.30.0/en/main_classes/tokenizer#transformers.PreTrainedTokenizer) which contains most of the main methods. Users should refer to this superclass for more information regarding those methods.

#### build\_inputs\_with\_special\_tokens

[](#transformers.LxmertTokenizer.build_inputs_with_special_tokens)[< source \>](https://github.com/huggingface/transformers/blob/v4.30.0/src/transformers/models/lxmert/tokenization_lxmert.py#L197)

( token\_ids\_0: typing.List\[int\]token\_ids\_1: typing.Optional\[typing.List\[int\]\] = None ) → `List[int]`

Parameters

-   [](#transformers.LxmertTokenizer.build_inputs_with_special_tokens.token_ids_0)**token\_ids\_0** (`List[int]`) — List of IDs to which the special tokens will be added.
-   [](#transformers.LxmertTokenizer.build_inputs_with_special_tokens.token_ids_1)**token\_ids\_1** (`List[int]`, _optional_) — Optional second list of IDs for sequence pairs.

List of [input IDs](../glossary#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:

-   single sequence: `[CLS] X [SEP]`
-   pair of sequences: `[CLS] A [SEP] B [SEP]`

Converts a sequence of tokens (string) in a single string.

#### create\_token\_type\_ids\_from\_sequences

[](#transformers.LxmertTokenizer.create_token_type_ids_from_sequences)[< source \>](https://github.com/huggingface/transformers/blob/v4.30.0/src/transformers/models/lxmert/tokenization_lxmert.py#L250)

( token\_ids\_0: typing.List\[int\]token\_ids\_1: typing.Optional\[typing.List\[int\]\] = None ) → `List[int]`

Parameters

-   [](#transformers.LxmertTokenizer.create_token_type_ids_from_sequences.token_ids_0)**token\_ids\_0** (`List[int]`) — List of IDs.
-   [](#transformers.LxmertTokenizer.create_token_type_ids_from_sequences.token_ids_1)**token\_ids\_1** (`List[int]`, _optional_) — Optional second list of IDs for sequence pairs.

List of [token type IDs](../glossary#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).

#### get\_special\_tokens\_mask

[](#transformers.LxmertTokenizer.get_special_tokens_mask)[< source \>](https://github.com/huggingface/transformers/blob/v4.30.0/src/transformers/models/lxmert/tokenization_lxmert.py#L222)

( token\_ids\_0: typing.List\[int\]token\_ids\_1: typing.Optional\[typing.List\[int\]\] = Nonealready\_has\_special\_tokens: bool = False ) → `List[int]`

Parameters

-   [](#transformers.LxmertTokenizer.get_special_tokens_mask.token_ids_0)**token\_ids\_0** (`List[int]`) — List of IDs.
-   [](#transformers.LxmertTokenizer.get_special_tokens_mask.token_ids_1)**token\_ids\_1** (`List[int]`, _optional_) — Optional second list of IDs for sequence pairs.
-   [](#transformers.LxmertTokenizer.get_special_tokens_mask.already_has_special_tokens)**already\_has\_special\_tokens** (`bool`, _optional_, defaults to `False`) — Whether or not the token list is already formatted with special tokens for the model.

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.

## [](#transformers.LxmertTokenizerFast)LxmertTokenizerFast

### class transformers.LxmertTokenizerFast

[](#transformers.LxmertTokenizerFast)[< source \>](https://github.com/huggingface/transformers/blob/v4.30.0/src/transformers/models/lxmert/tokenization_lxmert_fast.py#L48)

( vocab\_file = Nonetokenizer\_file = Nonedo\_lower\_case = Trueunk\_token = '\[UNK\]'sep\_token = '\[SEP\]'pad\_token = '\[PAD\]'cls\_token = '\[CLS\]'mask\_token = '\[MASK\]'tokenize\_chinese\_chars = Truestrip\_accents = None\*\*kwargs )

Construct a “fast” Lxmert tokenizer (backed by HuggingFace’s _tokenizers_ library). Based on WordPiece.

This tokenizer inherits from [PreTrainedTokenizerFast](/docs/transformers/v4.30.0/en/main_classes/tokenizer#transformers.PreTrainedTokenizerFast) which contains most of the main methods. Users should refer to this superclass for more information regarding those methods.

#### build\_inputs\_with\_special\_tokens

[](#transformers.LxmertTokenizerFast.build_inputs_with_special_tokens)[< source \>](https://github.com/huggingface/transformers/blob/v4.30.0/src/transformers/models/lxmert/tokenization_lxmert_fast.py#L136)

( token\_ids\_0token\_ids\_1 = None ) → `List[int]`

Parameters

-   [](#transformers.LxmertTokenizerFast.build_inputs_with_special_tokens.token_ids_0)**token\_ids\_0** (`List[int]`) — List of IDs to which the special tokens will be added.
-   [](#transformers.LxmertTokenizerFast.build_inputs_with_special_tokens.token_ids_1)**token\_ids\_1** (`List[int]`, _optional_) — Optional second list of IDs for sequence pairs.

List of [input IDs](../glossary#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:

-   single sequence: `[CLS] X [SEP]`
-   pair of sequences: `[CLS] A [SEP] B [SEP]`

#### create\_token\_type\_ids\_from\_sequences

[](#transformers.LxmertTokenizerFast.create_token_type_ids_from_sequences)[< source \>](https://github.com/huggingface/transformers/blob/v4.30.0/src/transformers/models/lxmert/tokenization_lxmert_fast.py#L160)

( token\_ids\_0: typing.List\[int\]token\_ids\_1: typing.Optional\[typing.List\[int\]\] = None ) → `List[int]`

Parameters

-   [](#transformers.LxmertTokenizerFast.create_token_type_ids_from_sequences.token_ids_0)**token\_ids\_0** (`List[int]`) — List of IDs.
-   [](#transformers.LxmertTokenizerFast.create_token_type_ids_from_sequences.token_ids_1)**token\_ids\_1** (`List[int]`, _optional_) — Optional second list of IDs for sequence pairs.

List of [token type IDs](../glossary#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).

## [](#transformers.models.lxmert.modeling_lxmert.LxmertModelOutput)Lxmert specific outputs

### class transformers.models.lxmert.modeling\_lxmert.LxmertModelOutput

[](#transformers.models.lxmert.modeling_lxmert.LxmertModelOutput)[< source \>](https://github.com/huggingface/transformers/blob/v4.30.0/src/transformers/models/lxmert/modeling_lxmert.py#L60)

( language\_output: typing.Optional\[torch.FloatTensor\] = Nonevision\_output: typing.Optional\[torch.FloatTensor\] = Nonepooled\_output: typing.Optional\[torch.FloatTensor\] = Nonelanguage\_hidden\_states: typing.Optional\[typing.Tuple\[torch.FloatTensor\]\] = Nonevision\_hidden\_states: typing.Optional\[typing.Tuple\[torch.FloatTensor\]\] = Nonelanguage\_attentions: typing.Optional\[typing.Tuple\[torch.FloatTensor\]\] = Nonevision\_attentions: typing.Optional\[typing.Tuple\[torch.FloatTensor\]\] = Nonecross\_encoder\_attentions: typing.Optional\[typing.Tuple\[torch.FloatTensor\]\] = None )

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”)

### class transformers.models.lxmert.modeling\_lxmert.LxmertForPreTrainingOutput

[](#transformers.models.lxmert.modeling_lxmert.LxmertForPreTrainingOutput)[< source \>](https://github.com/huggingface/transformers/blob/v4.30.0/src/transformers/models/lxmert/modeling_lxmert.py#L146)

( loss: typing.Optional\[torch.FloatTensor\] = Noneprediction\_logits: typing.Optional\[torch.FloatTensor\] = Nonecross\_relationship\_score: typing.Optional\[torch.FloatTensor\] = Nonequestion\_answering\_score: typing.Optional\[torch.FloatTensor\] = Nonelanguage\_hidden\_states: typing.Optional\[typing.Tuple\[torch.FloatTensor\]\] = Nonevision\_hidden\_states: typing.Optional\[typing.Tuple\[torch.FloatTensor\]\] = Nonelanguage\_attentions: typing.Optional\[typing.Tuple\[torch.FloatTensor\]\] = Nonevision\_attentions: typing.Optional\[typing.Tuple\[torch.FloatTensor\]\] = Nonecross\_encoder\_attentions: typing.Optional\[typing.Tuple\[torch.FloatTensor\]\] = None )

Output type of [LxmertForPreTraining](/docs/transformers/v4.30.0/en/model_doc/lxmert#transformers.LxmertForPreTraining).

### class transformers.models.lxmert.modeling\_lxmert.LxmertForQuestionAnsweringOutput

[](#transformers.models.lxmert.modeling_lxmert.LxmertForQuestionAnsweringOutput)[< source \>](https://github.com/huggingface/transformers/blob/v4.30.0/src/transformers/models/lxmert/modeling_lxmert.py#L106)

( loss: typing.Optional\[torch.FloatTensor\] = Nonequestion\_answering\_score: typing.Optional\[torch.FloatTensor\] = Nonelanguage\_hidden\_states: typing.Optional\[typing.Tuple\[torch.FloatTensor\]\] = Nonevision\_hidden\_states: typing.Optional\[typing.Tuple\[torch.FloatTensor\]\] = Nonelanguage\_attentions: typing.Optional\[typing.Tuple\[torch.FloatTensor\]\] = Nonevision\_attentions: typing.Optional\[typing.Tuple\[torch.FloatTensor\]\] = Nonecross\_encoder\_attentions: typing.Optional\[typing.Tuple\[torch.FloatTensor\]\] = None )

Output type of [LxmertForQuestionAnswering](/docs/transformers/v4.30.0/en/model_doc/lxmert#transformers.LxmertForQuestionAnswering).

### class transformers.models.lxmert.modeling\_tf\_lxmert.TFLxmertModelOutput

[](#transformers.models.lxmert.modeling_tf_lxmert.TFLxmertModelOutput)[< source \>](https://github.com/huggingface/transformers/blob/v4.30.0/src/transformers/models/lxmert/modeling_tf_lxmert.py#L61)

( language\_output: tf.Tensor | None = Nonevision\_output: tf.Tensor | None = Nonepooled\_output: tf.Tensor | None = Nonelanguage\_hidden\_states: Tuple\[tf.Tensor\] | None = Nonevision\_hidden\_states: Tuple\[tf.Tensor\] | None = Nonelanguage\_attentions: Tuple\[tf.Tensor\] | None = Nonevision\_attentions: Tuple\[tf.Tensor\] | None = Nonecross\_encoder\_attentions: Tuple\[tf.Tensor\] | None = None )

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”)

### class transformers.models.lxmert.modeling\_tf\_lxmert.TFLxmertForPreTrainingOutput

[](#transformers.models.lxmert.modeling_tf_lxmert.TFLxmertForPreTrainingOutput)[< source \>](https://github.com/huggingface/transformers/blob/v4.30.0/src/transformers/models/lxmert/modeling_tf_lxmert.py#L107)

( loss: tf.Tensor | None = Noneprediction\_logits: tf.Tensor | None = Nonecross\_relationship\_score: tf.Tensor | None = Nonequestion\_answering\_score: tf.Tensor | None = Nonelanguage\_hidden\_states: Tuple\[tf.Tensor\] | None = Nonevision\_hidden\_states: Tuple\[tf.Tensor\] | None = Nonelanguage\_attentions: Tuple\[tf.Tensor\] | None = Nonevision\_attentions: Tuple\[tf.Tensor\] | None = Nonecross\_encoder\_attentions: Tuple\[tf.Tensor\] | None = None )

Output type of [LxmertForPreTraining](/docs/transformers/v4.30.0/en/model_doc/lxmert#transformers.LxmertForPreTraining).

## [](#transformers.LxmertModel)LxmertModel

### class transformers.LxmertModel

[](#transformers.LxmertModel)[< source \>](https://github.com/huggingface/transformers/blob/v4.30.0/src/transformers/models/lxmert/modeling_lxmert.py#L883)

( config )

Parameters

-   [](#transformers.LxmertModel.config)**config** ([LxmertConfig](/docs/transformers/v4.30.0/en/model_doc/lxmert#transformers.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 the [from\_pretrained()](/docs/transformers/v4.30.0/en/main_classes/model#transformers.PreTrainedModel.from_pretrained) method to load the model weights.

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](https://arxiv.org/abs/1908.07490) 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](/docs/transformers/v4.30.0/en/main_classes/model#transformers.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](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and behavior.

#### forward

[](#transformers.LxmertModel.forward)[< source \>](https://github.com/huggingface/transformers/blob/v4.30.0/src/transformers/models/lxmert/modeling_lxmert.py#L898)

( input\_ids: typing.Optional\[torch.LongTensor\] = Nonevisual\_feats: typing.Optional\[torch.FloatTensor\] = Nonevisual\_pos: typing.Optional\[torch.FloatTensor\] = Noneattention\_mask: typing.Optional\[torch.FloatTensor\] = Nonevisual\_attention\_mask: typing.Optional\[torch.FloatTensor\] = Nonetoken\_type\_ids: typing.Optional\[torch.LongTensor\] = Noneinputs\_embeds: typing.Optional\[torch.FloatTensor\] = Noneoutput\_attentions: typing.Optional\[bool\] = Noneoutput\_hidden\_states: typing.Optional\[bool\] = Nonereturn\_dict: typing.Optional\[bool\] = None ) → [transformers.models.lxmert.modeling\_lxmert.LxmertModelOutput](/docs/transformers/v4.30.0/en/model_doc/lxmert#transformers.models.lxmert.modeling_lxmert.LxmertModelOutput) or `tuple(torch.FloatTensor)`

The [LxmertModel](/docs/transformers/v4.30.0/en/model_doc/lxmert#transformers.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```

## [](#transformers.LxmertForPreTraining)LxmertForPreTraining

### class transformers.LxmertForPreTraining

[](#transformers.LxmertForPreTraining)[< source \>](https://github.com/huggingface/transformers/blob/v4.30.0/src/transformers/models/lxmert/modeling_lxmert.py#L1020)

( config )

Parameters

-   [](#transformers.LxmertForPreTraining.config)**config** ([LxmertConfig](/docs/transformers/v4.30.0/en/model_doc/lxmert#transformers.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 the [from\_pretrained()](/docs/transformers/v4.30.0/en/main_classes/model#transformers.PreTrainedModel.from_pretrained) method to load the model weights.

Lxmert Model with a specified pretraining head on top.

The LXMERT model was proposed in [LXMERT: Learning Cross-Modality Encoder Representations from Transformers](https://arxiv.org/abs/1908.07490) 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](/docs/transformers/v4.30.0/en/main_classes/model#transformers.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](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and behavior.

#### forward

[](#transformers.LxmertForPreTraining.forward)[< source \>](https://github.com/huggingface/transformers/blob/v4.30.0/src/transformers/models/lxmert/modeling_lxmert.py#L1149)

( input\_ids: typing.Optional\[torch.LongTensor\] = Nonevisual\_feats: typing.Optional\[torch.FloatTensor\] = Nonevisual\_pos: typing.Optional\[torch.FloatTensor\] = Noneattention\_mask: typing.Optional\[torch.FloatTensor\] = Nonevisual\_attention\_mask: typing.Optional\[torch.FloatTensor\] = Nonetoken\_type\_ids: typing.Optional\[torch.LongTensor\] = Noneinputs\_embeds: typing.Optional\[torch.FloatTensor\] = Nonelabels: typing.Optional\[torch.LongTensor\] = Noneobj\_labels: typing.Union\[typing.Dict\[str, typing.Tuple\[torch.FloatTensor, torch.FloatTensor\]\], NoneType\] = Nonematched\_label: typing.Optional\[torch.LongTensor\] = Noneans: typing.Optional\[torch.Tensor\] = Noneoutput\_attentions: typing.Optional\[bool\] = Noneoutput\_hidden\_states: typing.Optional\[bool\] = Nonereturn\_dict: typing.Optional\[bool\] = None\*\*kwargs ) → [transformers.models.lxmert.modeling\_lxmert.LxmertForPreTrainingOutput](/docs/transformers/v4.30.0/en/model_doc/lxmert#transformers.models.lxmert.modeling_lxmert.LxmertForPreTrainingOutput) or `tuple(torch.FloatTensor)`

The [LxmertForPreTraining](/docs/transformers/v4.30.0/en/model_doc/lxmert#transformers.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.

## [](#transformers.LxmertForQuestionAnswering)LxmertForQuestionAnswering

### class transformers.LxmertForQuestionAnswering

[](#transformers.LxmertForQuestionAnswering)[< source \>](https://github.com/huggingface/transformers/blob/v4.30.0/src/transformers/models/lxmert/modeling_lxmert.py#L1288)

( config )

Parameters

-   [](#transformers.LxmertForQuestionAnswering.config)**config** ([LxmertConfig](/docs/transformers/v4.30.0/en/model_doc/lxmert#transformers.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 the [from\_pretrained()](/docs/transformers/v4.30.0/en/main_classes/model#transformers.PreTrainedModel.from_pretrained) method to load the model weights.

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](https://arxiv.org/abs/1908.07490) 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](/docs/transformers/v4.30.0/en/main_classes/model#transformers.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](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and behavior.

#### forward

[](#transformers.LxmertForQuestionAnswering.forward)[< source \>](https://github.com/huggingface/transformers/blob/v4.30.0/src/transformers/models/lxmert/modeling_lxmert.py#L1380)

( input\_ids: typing.Optional\[torch.LongTensor\] = Nonevisual\_feats: typing.Optional\[torch.FloatTensor\] = Nonevisual\_pos: typing.Optional\[torch.FloatTensor\] = Noneattention\_mask: typing.Optional\[torch.FloatTensor\] = Nonevisual\_attention\_mask: typing.Optional\[torch.FloatTensor\] = Nonetoken\_type\_ids: typing.Optional\[torch.LongTensor\] = Noneinputs\_embeds: typing.Optional\[torch.FloatTensor\] = Nonelabels: typing.Optional\[torch.Tensor\] = Noneoutput\_attentions: typing.Optional\[bool\] = Noneoutput\_hidden\_states: typing.Optional\[bool\] = Nonereturn\_dict: typing.Optional\[bool\] = None ) → [transformers.models.lxmert.modeling\_lxmert.LxmertForQuestionAnsweringOutput](/docs/transformers/v4.30.0/en/model_doc/lxmert#transformers.models.lxmert.modeling_lxmert.LxmertForQuestionAnsweringOutput) or `tuple(torch.FloatTensor)`

The [LxmertForQuestionAnswering](/docs/transformers/v4.30.0/en/model_doc/lxmert#transformers.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_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```

## [](#transformers.TFLxmertModel)TFLxmertModel

### class transformers.TFLxmertModel

[](#transformers.TFLxmertModel)[< source \>](https://github.com/huggingface/transformers/blob/v4.30.0/src/transformers/models/lxmert/modeling_tf_lxmert.py#L927)

( \*args\*\*kwargs )

Parameters

-   [](#transformers.TFLxmertModel.config)**config** ([LxmertConfig](/docs/transformers/v4.30.0/en/model_doc/lxmert#transformers.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 the [from\_pretrained()](/docs/transformers/v4.30.0/en/main_classes/model#transformers.PreTrainedModel.from_pretrained) method to load the model weights.

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](https://arxiv.org/abs/1908.07490) 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 [tf.keras.Model](https://www.tensorflow.org/api_docs/python/tf/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:

-   having all inputs as keyword arguments (like PyTorch models), or
-   having all inputs as a list, tuple or dict in the first positional argument.

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:

-   a single Tensor with `input_ids` only and nothing else: `model(input_ids)`
-   a list of varying length with one or several input Tensors IN THE ORDER given in the docstring: `model([input_ids, attention_mask])` or `model([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})`

Note that when creating models and layers with [subclassing](https://keras.io/guides/making_new_layers_and_models_via_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!

#### call

[](#transformers.TFLxmertModel.call)[< source \>](https://github.com/huggingface/transformers/blob/v4.30.0/src/transformers/models/lxmert/modeling_tf_lxmert.py#L932)

( input\_ids: TFModelInputType | None = Nonevisual\_feats: tf.Tensor | None = Nonevisual\_pos: tf.Tensor | None = Noneattention\_mask: np.ndarray | tf.Tensor | None = Nonevisual\_attention\_mask: np.ndarray | tf.Tensor | None = Nonetoken\_type\_ids: np.ndarray | tf.Tensor | None = Noneinputs\_embeds: np.ndarray | tf.Tensor | None = Noneoutput\_attentions: Optional\[bool\] = Noneoutput\_hidden\_states: Optional\[bool\] = Nonereturn\_dict: Optional\[bool\] = Nonetraining: bool = False ) → [transformers.models.lxmert.modeling\_tf\_lxmert.TFLxmertModelOutput](/docs/transformers/v4.30.0/en/model_doc/lxmert#transformers.models.lxmert.modeling_tf_lxmert.TFLxmertModelOutput) or `tuple(tf.Tensor)`

The [TFLxmertModel](/docs/transformers/v4.30.0/en/model_doc/lxmert#transformers.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```

## [](#transformers.TFLxmertForPreTraining)TFLxmertForPreTraining

### class transformers.TFLxmertForPreTraining

[](#transformers.TFLxmertForPreTraining)[< source \>](https://github.com/huggingface/transformers/blob/v4.30.0/src/transformers/models/lxmert/modeling_tf_lxmert.py#L1149)

( \*args\*\*kwargs )

Parameters

-   [](#transformers.TFLxmertForPreTraining.config)**config** ([LxmertConfig](/docs/transformers/v4.30.0/en/model_doc/lxmert#transformers.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 the [from\_pretrained()](/docs/transformers/v4.30.0/en/main_classes/model#transformers.PreTrainedModel.from_pretrained) method to load the model weights.

Lxmert Model with a `language modeling` head on top.

The LXMERT model was proposed in [LXMERT: Learning Cross-Modality Encoder Representations from Transformers](https://arxiv.org/abs/1908.07490) 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 [tf.keras.Model](https://www.tensorflow.org/api_docs/python/tf/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:

-   having all inputs as keyword arguments (like PyTorch models), or
-   having all inputs as a list, tuple or dict in the first positional argument.

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:

-   a single Tensor with `input_ids` only and nothing else: `model(input_ids)`
-   a list of varying length with one or several input Tensors IN THE ORDER given in the docstring: `model([input_ids, attention_mask])` or `model([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})`

Note that when creating models and layers with [subclassing](https://keras.io/guides/making_new_layers_and_models_via_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!

The [TFLxmertForPreTraining](/docs/transformers/v4.30.0/en/model_doc/lxmert#transformers.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.